1

I am creating a blog using Yii2. I have basic DB structure having tables: Posts Categories Posts_Categories

I am using Yii2 ActiveForm to create post creation form. There are input fields for Title (text field), Content (text area), Categories (list box for multiple category selection).

I am not able to populate listBox with db values.

<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'Title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'Content')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'CategoryId')->listBox(\yii\helpers\ArrayHelper::map(\backend\models\Category::find()->all(),'CategoryId','CategoryName',['multiple' => true])); ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

It is throwing following error:

Unknown Property – yii\base\UnknownPropertyException

Getting unknown property: backend\models\Category::1

There is error in listbox line. Secondly, after populating the data in listbox, how can I handle data insertion with respect to posts and multiple categories relationship.

2 Answers 2

1

You have syntax error in listBox. so, complete end parenthesis ) before multiple property.

Like as,

<?= $form->field($model, 'CategoryId')->listBox(\yii\helpers\ArrayHelper::map(\backend\models\Category::find()->all(),'CategoryId','CategoryName'),['multiple' => true]); ?>
Sign up to request clarification or add additional context in comments.

Comments

1

For the second part of your question on data insertion. You may need to traverse the array of the selected (posted) items in the list box. Here is an example that may be included in the actionCreate() or actionUpdate() functions of your controller file (I am assuming PostController.php):

$selectedList = $_POST['model_name']['CategoryId'];
if(isset($selectedList)) {
    foreach($selectedList as $value){
        $pcmodel = new Post_Categories(); //assumption on model name
        //do neccessary check here
        $pcmodel->post_id = $postmodel->id;
        //assumption that value is being stored
        $pcmodel->category_id = $value; 
        $pcmodel->save(); 
    }
}

1 Comment

This is not ideal but yeah also doesn't work with just $modelForm->load(Yii::$app->request->post()) Why does Yii not automatically populate a model's member array from a listBox (POSTed) input?

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.