簡體   English   中英

過濾器在Yii CGridView中不起作用

[英]Filter not working in Yii CGridView

我是Yii的新手。 我在視圖中顯示一些數據。 我在視圖中添加了過濾器,但似乎無法正常工作。 請幫我解決這個問題。

我的觀點:

<?php
/* @var $this NimsoftHostsDetailsController */
/* @var $model NimsoftHostsDetails */
$this->breadcrumbs=array(
    'Nimsoft Hosts Details'=>array('index'),
    $model->id,
);

$this->menu=array(
    array('label'=>'List NimsoftHostsDetails', 'url'=>array('index')),
    array('label'=>'Create NimsoftHostsDetails', 'url'=>array('create')),
    array('label'=>'Update NimsoftHostsDetails', 'url'=>array('update', 'id'=>$model->id)),
    array('label'=>'Delete NimsoftHostsDetails', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')),
    array('label'=>'Manage NimsoftHostsDetails', 'url'=>array('admin')),
);
?>

<h1>View NimsoftHostsDetails - </h1><h3><?php echo "Host Name - ".$host_name;?></h3>
<?php 
      if(Yii::app()->user->hasFlash('error'))
        {
        echo Yii::app()->user->getFlash('error');
        }
?> 

<!--<a href="<?php //echo $this->createUrl('/NimsoftHostsDetails/create?id='.$host_id);?>" title="Add Date Entry" class="btn btn-primary circle_ok" style="text-decoration: none;" >Add Date Entry</a>-->
<a href="<?php echo $this->createUrl('/Nimsoft/search_host1?id='.$cust_id);?>" title="Back" class="btn btn-primary circle_ok" style="text-decoration: none;" >Back</a>
<?php /*$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
)); */?>
<div class="form">
<div class="row">
    <div style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
    <?php
    $host_id = $host_id;
    $form=$this->beginWidget('CActiveForm', array(
    'id'=>'nimsoft-hosts-details-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
    <div style="float:left;"><?php //echo $form->errorSummary($model); ?>
        <?php echo $form->labelEx($model,'host_start_date'); ?>
        <?php
                Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
            $this->widget('CJuiDateTimePicker', array(
            'attribute' => 'host_start_date',
            'language' => '',
            'model' => $model,
            'options' => array(
            'mode' => 'focus',
            'dateFormat' => 'yy-mm-dd',
            'minDate'=>'0',
            'showAnim' => 'slideDown',
            ),
            'htmlOptions' => array(
            'style'=>'height:20px;',
            'value' => $host_start_date,

            ),
            ));
            ?>
        <?php echo $form->error($model,'host_start_date'); ?></div>
<div style="float:left;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>
<div style="float:left;"><?php echo $form->labelEx($model,'host_end_date'); ?>
    <?php
                Yii::import('application.extensions.CJuiDateTimePicker.CJuiDateTimePicker');
            $this->widget('CJuiDateTimePicker', array(
            'attribute' => 'host_end_date',
            'language' => '',
            'model' => $model,
            'options' => array(
            'mode' => 'focus',
            'dateFormat' => 'yy-mm-dd',
            'minDate'=>'0',
            'showAnim' => 'slideDown',
            ),
            'htmlOptions' => array(
            'style'=>'height:20px;',
            'value' => $host_end_date,

            ),
            ));
            ?>
        <?php echo $form->error($model,'host_end_date'); ?>
</div>
</div>
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
    <?php $this->endWidget(); ?>
</div>     
<?php 

$obj=$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    ////'afterAjaxUpdate'=>'\'changeTRColor()\'',
    //'itemView'=>'_view',
        'filter'=>$model,
    'columns'=>array(

                array(            // display 'create_time' using an expression
                            'name'=>'host_start_date',
                                            'value'=>'$data->host_start_date',
                ),
                array(
                            'name'=>'host_end_date',
                            'value'=>'$data->host_end_date',
                ),
                array(
                                    'class'=>'CButtonColumn',
                                    'template'=>'{update}{delete}',
                                    )
                ),

)); 

?>
    <?php //echo Yii::app()->user->getFlash('error'); ?>

我的控制器:

<?php

class NimsoftHostsDetailsController 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/ticket_console';

    /**
     * @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)
    {
            $host_id=$id;
            $model1=new NimsoftHostsDetails;
            $detail = NimsoftHostsDetails::model()->findAllByAttributes(array('host_id'=>$id));
            if(isset($_POST['NimsoftHostsDetails']))
        {
                        $model1->attributes = $_POST['NimsoftHostsDetails'];
                        $model1->host_id=$id;
                        /*$model=new NimsoftHostsDetails;
            $model->attributes=$_POST['NimsoftHostsDetails'];
                        $model->host_id=$id;
            $criteria = new CDbCriteria;
                        $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_start_date,'host_end_date'=>$model->host_end_date,'host_id'=>$model->host_id));
                        if($date_details)
                        {echo "Hi";
                        //Yii::app()->user->setFlash('error', "DATA already present, Please Enter different Date");
                        //$this->render('view',array('message'=>"DATA already present, Please Enter different Date",'host_id'=>$model->host_id));
                        die();
                        }

                        $criteria = new CDbCriteria;
                        $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_end_date,'host_id'=>$model->host_id));
                        if($date_details)
                        {
                            Yii::app()->user->setFlash('a', "The End date ".$model->host_end_date." is already mentioned as a start date");
                            //$this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
                        die();

                        }



                        if($model->host_start_date == $model->host_end_date)
                        {
                            Yii::app()->user->setFlash('s', "Both dates same, Please Enter different Date");
                            //$this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
                        die();
                        }*/
                        if($model1->save())
                $this->redirect(array('view','id'=>$model1->host_id));
        }
            $criteria = new CDbCriteria();
            $criteria->condition = "host_id = '$id'";
            $details = NimsoftHostsDetails::model()->findAll($criteria);
            $model=new NimsoftHost;
            $detail2 = NimsoftHost::model()->findAllByAttributes(array('host_id'=>$id));
            foreach($detail2 as $val)
                {
                   $name=$val->host_name;
                   $id=$val->host_id;
                   $cust_id=$val->host_customer_id;

                }
            $dataProvider=new CActiveDataProvider('NimsoftHostsDetails',array(
            'criteria'   => $criteria,));
            $this->render('view',array(
                'dataProvider'=>$dataProvider,
        'host_name'=>$name,
                'host_id'=>$id,
                'cust_id'=>$cust_id,'model'=>$model1
        ));

    }
/**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($id)
    {
            $model=new NimsoftHostsDetails;
                $host_id=$id;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['NimsoftHostsDetails']))
        {
            $model->attributes=$_POST['NimsoftHostsDetails'];
                        $model->host_id=$id;

                        $criteria = new CDbCriteria;
                        $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_start_date,'host_end_date'=>$model->host_end_date,'host_id'=>$model->host_id));
                        if($date_details)
                        {
                            $this->render('exist',array('message'=>"DATA already present, Please Enter different Date",'host_id'=>$model->host_id));
                        die();

                        }

                        $criteria = new CDbCriteria;
                        $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_end_date,'host_id'=>$model->host_id));
                        if($date_details)
                        {
                            $this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
                        die();

                        }



                        if($model->host_start_date == $model->host_end_date)
                        {
                            $this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
                        die();
                        }
                        if($model->save())
                $this->redirect(array('view','id'=>$model->host_id));
        }

        $this->render('create',array(
            'model'=>$model,
                    'host_id'=>$host_id,
        ));
    }

    /**
     * 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['NimsoftHostsDetails']))
        {
            $model->attributes=$_POST['NimsoftHostsDetails'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->host_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('NimsoftHostsDetails');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model=new NimsoftHostsDetails('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['NimsoftHostsDetails']))
            $model->attributes=$_GET['NimsoftHostsDetails'];

        $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 NimsoftHostsDetails the loaded model
     * @throws CHttpException
     */
    public function loadModel($id)
    {
        $model=NimsoftHostsDetails::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param NimsoftHostsDetails $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='nimsoft-hosts-details-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

我的模特:

<?php

/**
 * This is the model class for table "mst_nimsoft_hosts_details".
 *
 * The followings are the available columns in table 'mst_nimsoft_hosts_details':
 * @property integer $id
 * @property integer $host_id
 * @property string $host_start_date
 * @property string $host_end_date
 */
class NimsoftHostsDetails extends CActiveRecord
{
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'mst_nimsoft_hosts_details';
    }

    /**
     * @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('host_start_date, host_end_date', 'required'),
                    //array('host_start_date','date_validate'),
            array('host_start_date, host_end_date', 'date','format'=>array('yyyy-MM-dd H:m','yyyy-MM-dd H:m')),
            array('host_end_date','compare','compareAttribute'=>'host_start_date','operator'=>'>', 'allowEmpty'=>false,'message'=>'{attribute} must be greater than "{compareValue}".'),
                        //array('host_start_date,host_end_date', 'unique','message'=>'HOST Date already exists!'),
                        // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('host_start_date, host_end_date', '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',
            'host_id' => 'Host',
            'host_start_date' => 'Host Start Date',
            'host_end_date' => 'Host End Date',
        );
    }

        public function date_validate($attribute)
        {
            $this->host_start_date;
            $this->host_end_date;
            $model=new NimsoftHostsDetails;
            $model->attributes=$_POST['NimsoftHostsDetails'];
            $model->host_id=$id;
            $criteria = new CDbCriteria;
            $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$this->host_start_date,'host_end_date'=>$this->host_end_date,'host_id'=>$model->host_id));
            if($date_details)
            {
                $this->addError($attribute, 'DATA already present, Please Enter different Date');
            }

            $criteria = new CDbCriteria;
            $date_details = NimsoftHostsDetails::model()->findAllByAttributes(array('host_start_date'=>$model->host_end_date,'host_id'=>$model->host_id));
            if($date_details)
            {
                Yii::app()->user->setFlash('a', "The End date ".$model->host_end_date." is already mentioned as a start date");
                //$this->render('exist',array('message'=>"The End date ".$model->host_end_date." is already mentioned as a start date",'host_id'=>$model->host_id));
            die();

            }



            if($model->host_start_date == $model->host_end_date)
            {
                Yii::app()->user->setFlash('s', "Both dates same, Please Enter different Date");
                //$this->render('exist',array('message'=>"Both dates same, Please Enter different Date",'host_id'=>$model->host_id));
            die();
            }

        }
    /**
     * 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('host_id',$this->host_id);
        $criteria->compare('host_start_date',$this->host_start_date,true);
        $criteria->compare('host_end_date',$this->host_end_date,true);

        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 NimsoftHostsDetails the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

我的視圖顯示數據,但在過濾部分,如果我輸入任何文本,則它不返回任何內容。 請幫我。 提前致謝。

確保您在過濾器中使用的值進入模型

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('host_id',$this->host_id);
    $criteria->compare('host_start_date',$this->host_start_date,true);
    $criteria->compare('host_end_date',$this->host_end_date,true);

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

我很難閱讀您的代碼。 那么您添加了哪個字段用作過濾器? 默認情況下將其包含在您的模型中嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM