要完成 Yii 表单字段,用户通常需要搜索引用的模型记录(例如在社交应用中搜索朋友的个人资料)。我确信其他 Yii 应用程序正在优雅地做到这一点。但是在我的肮脏方法中,在搜索结果页面中,我使用 aCHtml::submitButton
将两个模型发布回包含以下内容的表单:
- “找到”记录(与搜索结果中的配置文件之一关联的用户 ID)
- 先前输入的表单域内容(关系特征域)
或者,自动完成小部件效果很好,但没有进行我需要的详细搜索(例如,基于部分名称和城市或州或其他用户配置文件内容的搜索)。
或者,您可能会认为在搜索结果视图中,我可以修改表单成员以包含找到的记录(新朋友的用户 ID),然后从搜索结果页面发布/提交修改后的模型。但是为了使列表中的每个搜索结果都能正常工作,需要在该表单字段中填充一个唯一的用户 ID,并且在为每个搜索修改一个成员服务器端之前,我无法弄清楚如何复制表单模型结果的“提交”或“选择”按钮,创建所有这些表单模型似乎并不正确。因此,似乎可行的是使用子表单(在搜索结果视图中)提交两个单独submitButton
的模型,分别发布模型和额外的参数(用户 ID)。
有没有更好的办法?...链接到搜索结果页面和表单字段,保留已输入的数据并使用搜索结果中的选定记录填充搜索字段。
这是控制器/站点控制器:
public function actionBefriend() {
$model=new BefriendForm;
if(isset($_POST['BefriendForm'])) {
$model->attributes=$_POST['BefriendForm'];
if ($model->validate()) {
$model->createFriendship();
$this->redirect('Index'); }
else
$er=$model->getErrors(); }
if(isset($_POST['idfriend'])) {
$model->idfriend=$_POST['idfriend']; }
if(isset($model->idfriend)) {
$model->friend_name=Bio::model()->findByPk($model->idfriend)->name; }
$this->render('newFrienship', array('model' =>$model)); // newFriendship is the form view }
这是控制器/Bio.php(配置文件)
public function actionIndex() {
$criteria = new CDbCriteria();
$model=new BefriendForm;
if(isset($_GET['q']))
$q = $_GET['q'];
elseif (isset($_POST['BefriendForm'])) {
$model->attributes=$_POST['BefriendForm'];
$q = $model['friend_name']; }
if(isset($q)) {
$criteria->compare('name', $q, true, 'OR');
$criteria->compare('city', $q, true, 'OR');
$criteria->compare('state', $q, true, 'OR');
$criteria->compare('bio_text', $q, true, 'OR'); }
else
$q = '';
$dataProvider=new CActiveDataProvider('Bio', array('criteria'=>$criteria));
$this->render('index',array('dataProvider'=>$dataProvider, 'q'=>$q, 'model'=>$model )); }
这是views/site/newFriendship(表单视图)的开始
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'newFriendship-BefriendForm',
'enableAjaxValidation'=>true,)); ?>
这是views/bio/index.php(搜索结果索引页面)的核心:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'viewData'=>array('model'=>$model) )); ?>
这是 views/bio/_view.php 中的搜索结果行,它链接回 BefriendForm (SiteController),发送用户的 id 以填充表单中的朋友字段(从 id 获取名称):
<form method="POST">
<input type="hidden" name="idfriend" value="<?php echo $data->idfriend ?>" />
// Here's that submit button that I can't get to send both the model
//and the idfriend back to the form to repopulate it
// without manually writing HTML to submit all the fields individually
// or creating 2 subforms to submit together with a signle submitButton.
<?php echo CHtml::submitButton('Befriend', array('submit' => array('site/Befriend'),'model'=$model);
</form>