Reputation: 110
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.
Upvotes: 1
Views: 1879
Reputation: 128
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'));
Upvotes: 2
Reputation: 6296
The field in your table would be something like 'category_id'.
Your dropdown code should therefore be
echo Html::activeDropDownList($model,'category_id',$kategori,[]);
Upvotes: 0