Setting a many to many attribute to be required


I have two classes with a many to many relationship. For this question let’s call them Emp and Roles both were generated with gii. Each Emp can have many roles and they are linked with hasMany and viaTable.

Roles are created and updated with a checkboxlist with the following code:


 $optionsList = \yii\helpers\ArrayHelper::map(Roles::find()->all(), 'id', 'name');


 <?= $form->field($model, 'roles')->checkboxList($optionsList); ?>


How can make it required?

I cannot simply add ‘roles’ to the required array in Emp’s rules because then I get an InvalidCallException Setting read-only property.

Any ideas would be greatly appreciated.


Hi, hope this Yii2 Invalid Call: Setting read-only property will help you.

Roles is a relation name and returns the object and is not just a attribute or database column.

You cannot use it with textInput() like other attribute for eg email, first_name.

So you are given error of Setting read-only property.

In order to remove this error, you need to create new attribute or property to model like below

class Roles extends \yii\db\ActiveRecordsd


    public $roles;

    public function rules()


        return [

            // ...

            ['roles', 'string', 'required'],



    // ... 

In view file

<?= $form->field($model, 'roles')->checkboxList($optionsList); ?>


Thanks. I’ve seen this post in stackoverflow, but couldn’t make it work.

If I implement it as you suggested then the checkboxlist doesn’t get populated. I assume it’s because it is now mapped to the attribute $roles in the Emp class and not to the Emp relationship method getRoles.

Any other ideas?

We can not use "roles" as an attribute for user input, since we already have "roles" relation. We have to add some attribute with other name to handle user input, "role_ids" for example.

I hope the following wiki will be a help.