1

I am new to Yii2 and tried to work out the tutorials first.

I simply tried to add a new field (name: group) to the "Working with Forms" Guide referring to this webpage: http://www.yiiframework.com/doc-2.0/guide-start-forms.html#.

But user input from the added field doesn´t appear in the model.

The model:

class EntryForm extends Model
{
    public $name;
    public $email;
    public $group;  // additional attribute !!!!!!!!!!!

    public function rules()
    {
        return [
            [['name', 'email'], 'required'],
            ['email', 'email'],
        ];      
    }   
}

The Site Controller stays without any changes to the guide.

Entry-Form:

<?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'name')->label('Your Name') ?>
    <?= $form->field($model, 'email')->label('Your E-Mail address') ?>
    <?= $form->field($model, 'group')->label('Your Group name') ?>      <!-- additional input !!!!!!!!!!! ->

    <div class="form-group">
        <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end(); ?>

Entry Confirm:

...
<ul>
    <li><label>Name</label>: <?= Html::encode($model->name) ?></li>
    <li><label>Email</label>: <?= Html::encode($model->email) ?></li>
    <li><label>Group</label>: <?= Html::encode($model->group) ?></li>       <!--additional attribute !!!!!!!!!!! ->
</ul>
...

Notes:

Except the additional field "group", everything works fine.

User input in the "group" field appears in $_POST as expected.

But it does not appears in the model if I call $model->getAttributes()

I already checked the documentation of model->load() but couldn`t find any hint.

Thanks a lot for any help.

1
  • 1
    beacuse group is not a safe attribute Commented Mar 30, 2015 at 12:30

1 Answer 1

0

A model's validation rules serve two purposes:

  • Ensure that fields entered in a form are entered properly
  • Define which form fields are allowed to be assigned to a $model variable

you are missing the second point here so change your model rules function to

 public function rules()
    {
        return [
            [['name', 'email'], 'required'],
            ['email', 'email'],
            ['group', 'safe'],
        ];      
    }   

and it will work

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. I really didn't get the point that you need a validation rule even if there is no special need to enshure a form check for missing input.
read this yiiframework.com/wiki/161/understanding-safe-validation-rules it will be helpful in understanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.