Yii Framework Forum

Getting a Dropdown to return Null


(DBCreator) #1

I have a form in which I have a dropdown which may, or may not, be filled in initially. I have setup the table field to accept NULL entries and the field in question is related to another table for its allowable values.

<?= $form->field(
		$model, 
		'BillingCurrency',
		[
			'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-2">{input}{error}</div>',
			'labelOptions' => [
				'class'=>'control-label'
			],
		]
	)->dropDownList(
		ArrayHelper::map(
			Currencies::find()
				->all(),
			'BillingCurrency',
			'BillingCurrency'
		),
		[
			'prompt'=>'Select ...',
		]
	)
?>

The issue I’m having is when the form is submitted with no selection being made it errs because the generate update query is try to pass ‘’ as the field’s value rather than NULL. What is the proper way of handling this type of situation?

Thank you in advance for your guidance.


(Mehdi Achour) #2

When no selection is being made, it means that the prompt is still showing.
The prompt option value is “”, and this is what gets submitted to your controller.

In your controller, after loading the POST data, you can check the value and manually set it to null.


(DBCreator) #3

So simple. For some reason, I just couldn’t see it. Thank you. Adding

$model->BillingCurrency = ($model->BillingCurrency== “” ? Null : $model->BillingCurrency); //Replace ‘’ with Null

to my controller has remedied the issue. Can’t thank you enough.

Being that is my first post in this forum, if there is something I need to do to close the question, mark it as solved, … just let me know.