添加表单到结果页


Yii - Add form to results page

n00b at OOP and yii。我很难理解yii以及它如何将变量传递给视图。我有1个模型,访问mt数据库,也是一个形式,我可以张贴一个字符串和复选框值被添加到数据库。从gii构建的预构建页面中发布和检索工作良好。但我想做的是有形式和"读"从数据库都在同一页上。因此,当通过表单发布帖子时,它会被添加到同一页面底部的"历史"类型部分。

我能把<?php $this->renderPartial('_form', array('model'=>$model)); ?>添加到我的索引页吗??显然不是因为我得到一个错误:Undefined variable: model .

模型:

<?php
/**
 * This is the model class for table "fb_post".
 *
 * The followings are the available columns in table 'fb_post':
 * @property integer $id
 * @property string $post
 * @property integer $checkbox
 */
class FbPost extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'fb_post';
    }
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('post', 'required'),
            array('checkbox', 'numerical', 'integerOnly'=>true),
            array('post', 'length', 'max'=>255),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, post, checkbox', 'safe', 'on'=>'search'),
        );
    }
    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'post' => 'Post',
            'checkbox' => 'Checkbox',
        );
    }
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.
        $criteria=new CDbCriteria;
        $criteria->compare('id',$this->id);
        $criteria->compare('post',$this->post,true);
        $criteria->compare('checkbox',$this->checkbox);
        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return FbPost the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

控制器:

    <?php
class FbPostController extends Controller
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout='//layouts/fbhistory';
    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }
    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }
    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model=new FbPost;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['FbPost']))
        {
            $model->attributes=$_POST['FbPost'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }
        $this->render('create',array(
            'model'=>$model,
        ));
    }
    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['FbPost']))
        {
            $model->attributes=$_POST['FbPost'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }
        $this->render('update',array(
            'model'=>$model,
        ));
    }
    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        $this->loadModel($id)->delete();
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }
    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('FbPost');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }
    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new FbPost('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['FbPost']))
            $model->attributes=$_GET['FbPost'];
        $this->render('admin',array(
            'model'=>$model,
        ));
    }
    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer $id the ID of the model to be loaded
     * @return FbPost the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=FbPost::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }
    /**
     * Performs the AJAX validation.
     * @param FbPost $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='fb-post-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
视图

<?php
/* @var $this FbPostController */
/* @var $dataProvider CActiveDataProvider */
$this->breadcrumbs=array(
    'Fb Posts',
);
$this->menu=array(
    array('label'=>'Create FbPost', 'url'=>array('create')),
    array('label'=>'Manage FbPost', 'url'=>array('admin')),
);
?>
<h1>Fb Posts</h1>
<?php
    $this->render('index', array('mode'=>$mode));
?>
<?php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
)); ?>

表单需要一个模型,它的数据被张贴,你必须在控制器actionIndex中创建模型,并将其传递给索引视图。例子:

class FbPostController extends Controller
{
    ...
    public function actionIndex()
    {
        // Create model
        $model=new FbPost;
        // Process posted form data if any
        if (isset($_POST['FbPost']))
        {
            $model->attributes=$_POST['FbPost'];
            $model->save();
        }
        $dataProvider=new CActiveDataProvider('FbPost');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
            'model'=>$model,
        ));
    }
...
}

现在你可以添加你的代码:

<?php $this->renderPartial('_form', array('model'=>$model)); ?>