duancai9010 2016-02-14 11:35
浏览 181
已采纳

Yii2无效呼叫:设置只读属性

I have a Post model that has a many-many relationship with Tags.

Defined in Post model:

public function getTags(){
    return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
        ->viaTable('post_tags', ['post_id' => 'id']);
}

But Post::tags is read-only. So when I try to set them in the Controller, I get an error:

Invalid Call – yii\base\InvalidCallException

Setting read-only property: app\models\Post::tags

The controller is using load to set all the properties:

public function actionCreate(){
    $P = new Post();
    if( Yii::$app->request->post() ){
        $P->load(Yii::$app->request->post());
        $P->save();
        return $this->redirect('/posts');
    }
    return $this->render('create', ['model'=>$P]);
}

The input field in the view:

<?= $form->field($model, 'tags')->textInput(['value'=>$model->stringTags()]) ?>

Why is Post::tags read-only? And whats the proper way to set a model relationship?

  • 写回答

1条回答 默认 最新

  • dongxuan2015 2016-02-14 12:03
    关注

    Here tags

    public function getTags(){
        return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
            ->viaTable('post_tags', ['post_id' => 'id']);
    }
    

    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 attrbute or property to model like below

    class Post extends \yii\db\ActiveRecordsd
    {
        public $tg;
        public function rules()
        {
            return [
                // ...
                ['tg', 'string', 'required'],
            ];
        }
        // ... 
    

    In view file

    <?= $form->field($model, 'tg')->textInput(['value'=>$model->stringTags()]) ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部