Data is not getting from model - Yii2

177 views Asked by At

I have inserting data from activeForm in yii

<?php $form = ActiveForm::begin([
    'id'          => 'register-form',
    'options'     => ['class' => 'form-horizontal'],
    'fieldConfig' => [
        'template'     => "<div class=\"\">{label}{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
        'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ],
]);?>

<?= $form->field($model, 'firstname')->textInput(['placeholder' => 'First Name']) ?>
<?= $form->field($model, 'middlename')->textInput(['placeholder' => 'Middle Name']) ?>
<?= $form->field($model, 'lastname')->textInput(['placeholder' => 'Last Name']) ?>

Then i created a model and insert a data into db by createCommand

$db = Yii::$app->db->createCommand();
$db->insert('person', [..])->execute();

Here i have giving rules(required) for firstname and lastname. So middle name value coming as NULL

If i give required for middlename, Then value is stored in db. otherwise it is NULL

1

There are 1 answers

0
Pavel Bariev On BEST ANSWER

You always need to have some validation rule for attribute you want to save via mass assignment. E.g. just add one more rule and your middlename will be saved:

public function rules()
{
    return [
         [['firstname', 'lastname'], 'required'],
         ['middlename', 'string'], // rule for middlename
    ];
}