Yii2 - How to include multiple records using activeform and checkbox

Asked

Viewed 259 times

1

Hello, I am using Yii to test some things, I have a table called Order and another table called Productsproedido and this table has the id_order and id_product, I wanted in the same form to include several records in this table ( Productospedido) with the same value of the requested id_change only the product id_tetei do this using a checkbox in the form but gives an error

View of the product addition form on request:

<?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 Controller edidos@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 way I get an error ( Array to string Conversion ) which should be due to passing several values in the "id_product" field, I tried to make a loop to go saving one by one but it didn’t work.

1 answer

1

I solved it, I was having trouble getting what the form sent me, which turned out to be an array within an array (...)

Front is unchanged, I just needed to change in controller, follow 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 the template I receive from the form the id related to the product and keep the rest ( order id) intact .

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.