在yii中提交后,date字段返回空值

时间:2014-02-08 09:14:18

标签: yii

我是Yii的新手,我目前正在尝试在我的本地系统中创建产品页面。我将DateField声明为product_availability_date,product_end_date。但是当我在前端输入日期并提交时,它再次显示重新输入日期的错误。请说出一个解决方案。提前谢谢。

的ProductsController:

<?php

class ProductsController 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/column2';

    /**
     * @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','search'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update','search'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete','search'),
                '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 Products;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

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

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

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







    //search
    public function actionsearch()
    {
        $model=new Products;
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Products']))
            $model->attributes=$_GET['Products'];

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

    /**

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

产品型号:

<?php

/**
 * This is the model class for table "products".
 *
 * The followings are the available columns in table 'products':
 * @property integer $product_id
 * @property string $product_name
 * @property string $description
 * @property integer $quantity
 * @property integer $category_id
 * @property integer $location_id
 * @property string $vendor
 * @property string $status
 * @property integer $stock
 * @property string $prod_avl_date
 * @property string $prod_end_date
 */
class Products extends CActiveRecord
{

    public $vendor_name;
    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'products';
    }

    /**
     * @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('product_name, description, quantity, category_id, location_id, status, stock', 'required'),
            array('quantity, location_id, stock', 'numerical', 'integerOnly'=>true),
            array('product_name, vendor', 'length', 'max'=>50),
            array('status', 'length', 'max'=>2),
            array('prod_avl_date, prod_end_date', 'date','format'=>array('yyyy/MM/dd','yyyy/MM/d')),    
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('product_id, product_name, description, quantity, category_id, location_id, vendor, status, stock, prod_avl_date, prod_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('category_id'    => array(self::BELONGS_TO, 'Category','category_id'),
                'location_id'    => array(self::BELONGS_TO, 'Location','location_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'product_id' => 'Product',
            'product_name' => 'Product Name',
            'description' => 'Description',
            'quantity' => 'Quantity',
            'category_id' => 'Category',
            'location_id' => 'Location',
            'vendor' => 'Vendor',
            'status' => 'Status',
            'stock' => 'Stock',
            'prod_avl_date' => 'Prod Avl Date',
            'prod_end_date' => 'Prod End Date',
        );
    }

    /**
     * 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('product_id',$this->product_id);
        $criteria->compare('product_name',$this->product_name,true);
        $criteria->compare('description',$this->description,true);
        $criteria->compare('quantity',$this->quantity);
        $criteria->compare('category_id',$this->category_id);
        $criteria->compare('location_id',$this->location_id);
        $criteria->compare('vendor',$this->vendor,true);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('stock',$this->stock);
        $criteria->compare('prod_avl_date',$this->prod_avl_date,true);
        $criteria->compare('prod_end_date',$this->prod_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 Products the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
}

形式:

<?php
/* @var $this ProductsController */
/* @var $model Products */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'products-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'=>true,
)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

    <?php echo $form->errorSummary($model); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'product_name'); ?>
        <?php echo $form->textField($model,'product_name',array('size'=>50,'maxlength'=>50)); ?>
        <?php echo $form->error($model,'product_name'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'description'); ?>
        <?php echo $form->textArea($model,'description',array('rows'=>6, 'cols'=>50)); ?>
        <?php echo $form->error($model,'description'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'quantity'); ?>
        <?php echo $form->textField($model,'quantity'); ?>
        <?php echo $form->error($model,'quantity'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'category_id'); 
        echo $form->dropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'category_id', 'category_name'), array('prompt'=>'Select category','multiple' => 'multiple'));
         ?>
        <?php echo $form->error($model,'category_id'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'location_id'); 
        echo $form->dropDownList($model,'location_id', CHtml::listData(Location::model()->findAll(), 'location_id', 'location_name'), array('empty'=>'Select location'));?>
        <?php echo $form->error($model,'location_id'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'vendor');

        echo $form->dropDownList($model,'location_id',CHtml::listData(Vendor::model()->findAll(location_id),'location_id','vendor_name'),
                array(// htmlOptions
                        'ajax'=>array(// special htmlOption through clientChange, for ajax
                                'type'=>'GET',
                                'url'=>$this->createUrl('Vendor/Vendordetails'),// action that will generate the data
                                'data'=>'js:"id="+$(this).val()',// this is the data that we are sending to the action in the controller
                                'dataType'=>'json',// type of data we expect back from the server
                                'success'=>'js:updateFields'// a javascript function that will execute when the request completes successfully
                        ),


                )

        );





        //echo $form->dropDownList($model,'vendor', CHtml::listData(Vendor::model()->findAll(), 'location_id', 'vendor_name'), array('empty'=>'Select vendor'));?> 
        <?php echo $form->error($model,'vendor'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'status'); ?>
        <?php $status=array("AVAILABLE","NOT AVAILABLE")?>
        <?php echo $form->radioButtonList($model,'status',$status,array('separator'=>'')); ?>
        <?php echo $form->error($model,'status'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'stock'); ?>
        <?php echo $form->textField($model,'stock'); ?>
        <?php echo $form->error($model,'stock'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'prod_avl_date'); ?>
        <?php                    
       $this->widget('zii.widgets.jui.CJuiDatePicker',array(
    'name'=>'prod_avl_date',
    // additional javascript options for the date picker plugin
    'options'=>array(
        'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',

    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));                            
       ?> 
        <?php echo $form->error($model,'prod_avl_date'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'prod_end_date'); ?>
        <?php                    
       $this->widget('zii.widgets.jui.CJuiDatePicker',array(
    'name'=>'prod_end_date',
    // additional javascript options for the date picker plugin
    'options'=>array(
        'showAnim'=>'fold',
'dateFormat' => 'yy-mm-dd',
'timeFormat' => 'hh:mm:ss',
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));                            
       ?>
        <?php echo $form->error($model,'prod_end_date'); ?>

    </div>

    <div class="row buttons">
        <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
    </div>

<?php $this->endWidget(); ?>

</div>






<!-- form -->

1 个答案:

答案 0 :(得分:2)

CJuiDatePicker名称中的问题:

替换

'name'=>'prod_avl_date',

'name'=>'Products[prod_avl_date]',   

prod_end_date同样的事情

注意:您必须在CJuiDatePicker中设置日期格式,与模型规则中的日期格式完全相同

'dateFormat' => 'yy/mm/dd',