PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, March 6, 2022

[FIXED] Yii2 dropdown different Activerecord

 March 06, 2022     activerecord, php, yii, yii2, yii2-model     No comments   

Issue

I'm creating a form to input product which has activeDropdownList to select product category from different table. I'm using ActiveRecord class in product and category models and use category models to populate dropdown list. When i'm trying to insert product, it's failed because the dropdownlist's name.

All other field's name is like name="CreateEvent[tanggal]">, and my category dropdown : name="id">

How to integrate it without hardcoding dropdown attribute?

On my controller :

$kategori = $items = ArrayHelper::map(Kategori::find()->all(), 'id', 'nama');

        // check post header, call $model->save() if post is exist
        if($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('status', 'success');
            return $this->redirect(['create']);
        }

On my view :

$form = ActiveForm::begin();
echo $form->field($model, 'nama')->input('text');
echo $form->field($model, 'lokasi')->input('text');
echo $form->field($model, 'tanggal')->widget(DatePicker:: classname(),
    [
    ]);
echo Html::activeDropDownList($model,'id',$kategori,[]);
echo Html::submitButton('Submit', ['class'=>'btn btn-primary']);
ActiveForm::end();

Thanks.


Solution

If i understood you correctly, What is your column name in product table where you saving the categories?

instead of using HTML why not you are using something like this:

use yii\helpers\ArrayHelper;

$form->field($model,'your column name')->dropdownlist(ArrayHelper::map(Kategori::find()->all(), 'id', 'nama'));


Answered By - Virendra Gawade
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing