user4568438 user4568438 - 22 days ago 6
PHP Question

Textbox data saved to database but dropdown box data didn't

I custom form designed HTML and its working fine with Yii2 but only the data within textboxes is going into database and data within dropdown boxes doesn't go into database.

Sample code:

<form id="form-signup" action="/frontend/web/index.php?r=site%2Fsignup" method="post" role="form">
<input type="text" class="form-control" id="inputFirstName" name="SignupForm[firstName]" placeholder="Type First Name">

<select onchange="getCountList(this.value)" id="inpCountry" name="SignupForm[region]" class="gwt-ListBox stdTextWidth">
<option value="">Select Region</option>
<option value="1">Australia and the Pacific</option>
<option value="2">Africa</option>
<option value="51">Asia</option>
<option value="3">Europe</option>
<option value="4">North America</option>
<option value="5">South America</option>
</select>
</form>


When I submit the form the first name goes into database but the region id doesn't go into database.

My Model:

public function signup()
{
if ($this->validate()) {
$user = new User();
$user->FirstName = $this->firstName;
$user->UserRegionID = $this->region;
if ($user->save()) {
return $user;
}
}

return null;
}


In debugger I can see data is being submitted by the form but its not saving in database.

[
'firstName' => 'Pen'
'region' => '1'
]


My table name is User and my fields are
FirstName
and
UserRegionID

Answer

If you don't want to validate some model attributes, in order to massively assign them, you need at least explicitly mark them as safe:

public function rules()
{
    ['UserRegionID', 'safe'],
}

Please read these official documentation sections to better understand validation: