Search code examples
yii2yii2-advanced-app

Yii2 DropdownList Value not being sent to Model


I have a dropdownList which looks like this:

<select id="singleregisterform-titleid" name="SingleRegisterForm[titleId]">
<option value="1">Dr</option>
<option value="2">Miss</option>
<option value="3">Mr</option>
<option value="4">Mrs</option>
<option value="5">Ms</option>
<option value="6">Prof</option>
</select>

When I submit my form I can see this in the app.log file:

'SingleRegisterForm' => [
    'titleId' => '1'
    'firstName' => 'Kate'
    'lastName' => 'Becky'

But when the Model tries to do the save:

$person = new Person();
$person->title_id = $this->titleId;
$person->firstname = $this->firstName;
$person->lastname = $this->lastName;
$person->save();

I get this error:

COLUMN title_id cannot be NULL.
INSERT INTO `person_register` (`title_id`, `firstname`, `lastname`) VALUES (NULL, 'Kate', 'Becky');

Any ideas?


Solution

  • This is very funny. I would have expected Yii2 to not worry about fields which are not part of the validation rules. In this case with my DropDownList, even if the user does not change it, it will still have a value which will be 1, the first one in the list.

    Yii2 did not send this back to the Model because I don't have this field as part of the validation rules.

    I had to add this to my rules:

    ['titleId', 'required'],
    

    Now it works perfectly.