Yii: How to populate a Select input with another model data?

断了今生、忘了曾经 提交于 2019-12-10 23:54:19

问题


I'm playing around with a small app in order to learn to use Yii.

I've created a small webapp with 2 models / tables: Projects and tasks. (1-to-many relationship, properly configured in the model classes).

I'm now trying to customize the Task/create view, replacing the text input field with a select box proposing the list of available projects.

I opened the form view and tried this:

<div class="row">
    <?php echo $form->labelEx($model,'project_id'); ?>
    <?php echo $form->textField($model,'project_id'); ?>
    <?php 
// my hack starts here
    $projects = Project::model()->findAll();
    $list = CHtml::listData($projects, 'id', 'name');
    echo $form->listBox($model,'project_id','', $list); ?>

// my hack ends here
    <?php echo $form->error($model,'project_id'); ?>
</div>

But it keeps throwing warnings or error (such as Invalid argument supplied for foreach(), and definitely does not work. I'm failing to understand what i'm doing wrong. Can you help ?


回答1:


Your arguments are not in order (it should be):

$frameworks = Framework::model()->findAll();
$list = CHtml::listData($frameworks, 'id', 'name');
echo $form->listBox($model,'framework_id', $list,array());

Check the documentation




回答2:


OK, i found it, thanks to Larry Ullman excellent tutorial.

Here it is:

<?php echo $form->dropDownList($model,'project_id', CHtml::listData(Project::model()->findAll(), 'id', 'name')); ?>


来源:https://stackoverflow.com/questions/10744479/yii-how-to-populate-a-select-input-with-another-model-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!