Страница 1 из 1

Datepicker и база данных

Добавлено: 2011.12.06, 12:48
Bellski
Пытаюсь положить дату в базу данных, но почему то поле уходит пустым.
_form

Код: Выделить всё

<?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'model'=> $model,
    'attribute''=>'birth'
    'language'=>Yii::app()->language=='et' ? 'et' : null,
    'options'=>array(
        'showAnim'=>'fold', // 'show' (the default), 'slideDown', 'fadeIn', 'fold'
    ),
    'htmlOptions'=>array(
        'style'=>'width:80px;vertical-align:top'
    ),  
)); ?>
Массив beforsave

Код: Выделить всё

print_r($model->attributes);
 
Array ( [title] => dasgfdsg [place] => gfhgfh [post] => fcxcxzczx [post_id] => [birth] => [author_id] => )

Re: Datepicker и база данных

Добавлено: 2011.12.06, 13:01
timlar
В правилах валидации нужно указать поле даты как safe.

Re: Datepicker и база данных

Добавлено: 2011.12.06, 13:03
Bellski
Вроде как, указан.
Post.php

Код: Выделить всё

public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, post,place', 'required'),
            array('title', 'length', 'max'=>128),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('post_id, title, post, author_id, place, birth', 'safe', 'on'=>'search'),
        );
    }
 

Re: Datepicker и база данных

Добавлено: 2011.12.06, 13:14
timlar
Ключевой момент: 'on'=>'search', т.е. только для сценария search. В данном случае, он не сработает.

Re: Datepicker и база данных

Добавлено: 2011.12.06, 13:35
ATI
А еще можно не safe, а например:

Код: Выделить всё

array('birth', 'date', 'format'=>'yyyy-MM-dd'),
 

Re: Datepicker и база данных

Добавлено: 2011.12.06, 14:05
Bellski

Код: Выделить всё

    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, post,place', 'required'),
            array('title', 'length', 'max'=>128),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('post_id, title, post, author_id, place', 'safe', 'on'=>'search'),
                        array('birth', 'safe'),
        );
    } 
Все равно пустая строка уходит 8(...

Re: Datepicker и база данных

Добавлено: 2011.12.06, 14:57
ATI
Bellski писал(а):

Код: Выделить всё

    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, post,place', 'required'),
            array('title', 'length', 'max'=>128),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('post_id, title, post, author_id, place', 'safe', 'on'=>'search'),
                        array('birth', 'safe'),
        );
    } 
Все равно пустая строка уходит 8(...
Для начало глянь, что вообще приходит в $_POST.

Re: Datepicker и база данных

Добавлено: 2011.12.06, 15:10
Bellski
По сути сверхъестественного ничего нет.
Есть модель Post

Код: Выделить всё

    <?php

/**
 * This is the model class for table "{{post}}".
 *
 * The followings are the available columns in table '{{post}}':
 * @property integer $post_id
 * @property string $title
 * @property string $post
 * @property string $place
 * @property string $birth
 * @property integer $author_id
 * 
 *
 * The followings are the available model relations:
 * @property Users $author
 */
class Post extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @return Post the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{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('title, post,place', 'required'),
            array('title', 'length', 'max'=>128),
            // The following rule is used by search().
             // Please remove those attributes that should not be searched.
            array('post_id, title, post, author_id, place', 'safe', 'on'=>'search'),
                        array('birth', 'safe'),
        );
    }

    /**
     * @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(
            'author' => array(self::BELONGS_TO, 'Users', 'author_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'post_id' => 'Post',
            'title' => 'Title',
            'post' => 'Post',
            'author_id' => 'Author',
                        'place' => 'place',
                        'birth' => 'birth',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('post_id',$this->post_id);
        $criteria->compare('title',$this->title,true);
        $criteria->compare('post',$this->post,true);
        $criteria->compare('author_id',$this->author_id);
                $criteria->compare('place',$this->place,true);
                $criteria->compare('birth',$this->birth,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
        public function beforeSave()
            {
                // Если новая запись - присваиваем id автора
                if($this->isNewRecord)
                {
                    if(empty($this->author_id))
                    {
                        $this->author_id= Yii::app()->user->id;
                    }
                }
                return true;
            } 
}
 
PostController

Код: Выделить всё

<?php

class PostController 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(
               #         'updateOwn + update', // Apply this filter only for the update action
            'accessControl', // perform access control for CRUD operations
                        
        );
    }

    /**
     * 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 Post;

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

        if(isset($_POST['Post']))
        {
            $model->attributes=$_POST['Post'];
                        print_r($model->attributes);
            if($model->save())
                $this->redirect(array('view','id'=>$model->post_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 ($model->author_id == Yii::app()->user->id)
                {

        if(isset($_POST['Post']))
        {
            $model->attributes=$_POST['Post'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->post_id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
                }
                else {
                    throw new CHttpException('У вас нет прав на изменение этой темы');
                }
    }

    /**
     * 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)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $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'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Post');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

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

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

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='post-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
        
  
 
И форма. _form

Код: Выделить всё

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'post-form',
    'enableAjaxValidation'=>false,
)); ?>

    

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

    <div class="row">
        <?php echo $form->labelEx($model,'Тема'); ?>
        <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>128)); ?>
        <?php echo $form->error($model,'title'); ?>
    </div>
        <div class="row">
           
                <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'birth',
    'model'=> $model,
    'language'=>Yii::app()->language=='et' ? 'et' : null,
    'options'=>array(
        'showAnim'=>'fold', // 'show' (the default), 'slideDown', 'fadeIn', 'fold'
        'showOn'=>'button', // 'focus', 'button', 'both'
        'buttonText'=>Yii::t('ui','Select form calendar'), 
        'buttonImage'=>Yii::app()->request->baseUrl.'/images/calendar.gif', 
        'buttonImageOnly'=>true,
    ),
    'htmlOptions'=>array(
        'style'=>'width:80px;vertical-align:top'
    ),  
)); ?>

           
                        
        </div>
    <div class="row">
        
        <?php echo $form->labelEx($model,'Место события');?>
        <?php echo $form->textField($model,'place'); ?>

        
        
</div>
    
    <div class="row">
    
        <?php echo $form->textArea($model,'post', array('cols'=>80, 'rows'=>10)); ?>
        <?php echo $form->error($model,'post'); ?>
            
    </div>

    

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

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

</div><!-- form -->

Все поля работают нормально, причем некоторые добавлял руками и все ок, а вот с виджетом хрень какая то.
Поле для даты у меня string.

Re: Datepicker и база данных

Добавлено: 2011.12.06, 16:13
AlexMist
Поставь валидацию как написали, если поле в базе имеет формат date.

Код: Выделить всё

array('birth','type'=>'date','dateFormat'=>'yyyy-M-d','allowEmpty'=>true,
                          'message'=>'Некорректно указана дата.'),
 
И скорее всего выйдет ошибка =)

Нужный формат еще нужно указать в датапикере

Код: Выделить всё

<?php $this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'attribute'=>'birth', //поправил
    'model'=> $model,
    'value' => $model->date, //ВОТ ЭТО добавил бы, для редактирования записи
    'language'=>Yii::app()->language=='et' ? 'et' : null,
    'options'=>array(
        'showAnim'=>'fold', // 'show' (the default), 'slideDown', 'fadeIn', 'fold'
        'showOn'=>'button', // 'focus', 'button', 'both'
        'buttonText'=>Yii::t('ui','Select form calendar'), 
        'buttonImage'=>Yii::app()->request->baseUrl.'/images/calendar.gif', 
        'buttonImageOnly'=>true,
        'dateFormat' => 'yy-mm-dd', // Формат даты
    ),
    'htmlOptions'=>array(
        'style'=>'width:80px;vertical-align:top'
    ),  
)); ?>
upd заменил 'name' на 'attribute'

Re: Datepicker и база данных

Добавлено: 2011.12.06, 16:15
ATI
И лучше такие вещи задавать в методе attributeLabels

Код: Выделить всё

<?php echo $form->labelEx($model,'Тема'); ?>

Re: Datepicker и база данных

Добавлено: 2011.12.06, 16:24
because
всего-то надо поменять у виджета 'name'=>'birth' на 'attribute'=>'birth'

Re: Datepicker и база данных

Добавлено: 2011.12.06, 16:49
ATI
because писал(а):всего-то надо поменять у виджета 'name'=>'birth' на 'attribute'=>'birth'
Кстати да, и в первом посте автор пишет правильно 'attribute''=>'birth', а потом почему то пишет 'name'=>'birth'.

Re: Datepicker и база данных

Добавлено: 2011.12.07, 15:29
Bellski
Все получилось, разобрался.
Спасибо всем, кто помог )

p.s. странно вроде и так пробовал, только не работало ). Может просто, что то упустил.