Yii2 - How to include multiple records using activeform and checkbox

0
Hello, I'm using Yii to test some things, I have a table called Order and another table called Order Products and in this table has the order_id and product_id, I wanted in the same form to include several records in this table (Ordered Products) with the same value of the order_id just changing the id_product, I did this by using a checkbox in the form but it gives an error

View of the product addition form to the order:

<?php $form = ActiveForm::begin(['action' =>['produtos-pedidos/create'], 'id' => 'adiciona-produtos', 'method' => 'post',]); ?>

<?= $form->field($modelProdutoPedido, 'id_produto')->checkboxList(ArrayHelper::map($modelProduto -> find()->all(), 'id', 'nome')) ?>
<?= $form-> field($modelProdutoPedido, 'id_pedido') -> hiddenInput(['value' => $pedidoId]) -> label('false') ?>
<div class="form-group">

    <?= Html::submitButton($modelProdutoPedido->isNewRecord ? 'Adicionar + produtos' : 'Update', ['class' => $modelProdutoPedido->isNewRecord ? 'btn btn-success btn-adiciona-produtos' : 'btn btn-primary']) ?>

</div>

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

Product ControllerOrders @ Create:

public function actionCreate()
{
    $model = new ProdutosPedidos();
    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['//pedidos/view', 'id' => $model->id_pedido]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

If I do this, I get an error (Array to string conversion) which should be due to being passed several values in the field "product_id", I tried to loop to save one by one but it did not work.     

asked by anonymous 24.07.2017 / 21:55

1 answer

0

The Front is unchanged, I just needed to change it in the controller, follow the new code

 public function actionCreate()
{
    $model = new ProdutosPedidos();



    if($model->load(Yii::$app->request->post())){

        $idsProdutos = Yii::$app -> request -> post("ProdutosPedidos",['id_produto']);

        foreach ($idsProdutos['id_produto'] as $produto) {
            $model->id_produto = $produto ;
            $model->isNewRecord = true;
            $model->save();
        }
        return $this->redirect(['//pedidos/view', 'id' => $model->id_pedido]);
    }

}

In this code I only change in the template that I get from the form the id for the product and keep the rest (order id) intact.

It's working, but if anyone knows a simpler / more efficient way, I appreciate it.

    
24.07.2017 / 23:37