Добрый вечер.
Возникла небольшая проблема с выводом данных в dropDownList из связанной таблицы.
Есть три таблицы в базе:
1) Recipe // таблица с рецептами
2) Ingredients // таблица с ингредиентами
3) RecipesIngredients // связующая таблица, хранить id рецептов и ингредиентов
В моделях настроены связи:
// Recipe model
public function getIngred()
{
return $this->hasMany(Ingredients::className(), ['id' => 'ingredient_id'])->viaTable('{{%recipes_ingredients}}', ['recipe_id' => 'id']);
}
// Ingredients
public function getRecipe()
{
return $this->hasMany(Recipe::className(), ['id' => 'recipe_id'])->viaTable('{{%recipes_ingredients', ['ingredient_id' => 'id']);
}
Так же в модели Ingredients есть метод, который выводит все доступные ингредиенты.
public static function getActiveIngred()
{
return ArrayHelper::map(self::find()->where(['status' => self::STATUS_ACTIVE])->orderBy('name')->all(), 'id', 'name');
}
В контроллере RecipeController действие для создание рецепта
public function actionCreate()
{
$model = new Recipe();
for($i=0; $i<5; $i++){
$ingredient[] = new Ingredients();
}
$ingreds = Yii::$app->request->post('Ingredients');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
foreach($ingreds as $ingred){
$recipe_ingred = new RecipesIngredients();
$recipe_ingred->recipe_id = $model->id;
$recipe_ingred->ingredient_id = $ingred['name'];
$recipe_ingred->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'ingredient' => $ingredient
]);
}
}
Форма для создания рецепта
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?php
foreach($ingredient as $key => $value){
echo $form->field($value, '['.$key.']name')->dropDownList(Ingredients::getActiveIngred(), ['prompt' => 'Выбрать']);
}
?>
<?= $form->field($model, 'status')->dropDownList(Recipe::getStatusesArray()) ?>
<?= Html::submitButton($model->isNewRecord
? 'Сохранить'
: 'Обновить',
['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
Всё отлично работает, при создании рецепта выводится форма с полем для названия рецепта и пятью выпадающими списками для выбора ингредиентов.
Но при редактировании у меня возникла проблема.
Как мне вывести выпадающие списки с уже выбранными ингредиентами?
Пробовал через метод
Ingredients::getActiveIngred(), в форме выводится нужное количество ингредиентов(которые были выбраны при создании записи, select-ы), но вместо сохранённого ингредиента выводится просто prompt "Выбрать"
Подскажите, что я упустил?