Wednesday 18 April 2012

How to add a date without form post submit  in database?
=============================================
First Method :
=>put  below code in your model file 
 
public function beforeSave() {
    if ($this->isNewRecord)
        $this->created = new CDbExpression('NOW()');

    $this->modified = new CDbExpression('NOW()');

    return parent::beforeSave();
}

Second Method:

1)first upon model base file copy the below line:


    public function rules() {
         //in function rules
        array('created_at, updated_at', 'default', 'setOnEmpty' => true, 'value' => null),
    }
    public function attributeLabels() {
       //in attributesLabels function
        'created_at' => Yii::t('app', 'Created At'),
        'updated_at' => Yii::t('app', 'Updated At'),
    }
  
    public function search() {
         //in serch function
        $criteria->compare('created_at', $this->created_at, true);
        $criteria->compare('updated_at', $this->updated_at, true);
    }
  
2)In controller file :

    public action Create(){
            if (isset($_POST['User'])) {
                $tmp=array('created_at'=>date("Y-m-d H:i:s"));
                $_POST['User']=array_merge($_POST['User'],$tmp);
        }  
    }
  
    public actionUpdate(){
            if (isset($_POST['User'])) {
                $tmp=array('updated_at'=>date("Y-m-d H:i:s"));
                    if(isset($model->attributes))
                    {  
                        $g=$model->created_at;
                        //print_r($g); die;
                        $tm=explode("/",$g);
                        //print_r($tm); die;
                        $y=$tm['2'];
                        $m=$tm['1'];
                        $d=$tm['0'];
                    }  
                    $fy=$m."-".$d."-".$y;
                    //print_r($fy); die;
                    $model->created_at    =    date("Y-m-d ",strtotime($fy));
                    //print_r($model->created_at); die;
                    $model->updated_at    =    1;
                    $_POST['User']=array_merge($_POST['User'],$tmp);
                    $model->setAttributes($_POST['User']);
                    }  
    }
  
3) then put your function in model file(Whatever using Model):


        public function afterFind()
            {
                $this->created_at = strtotime($this->created_at);
                $this->created_at = date('m/d/Y', $this->created_at);
              
                $this->updated_at = strtotime($this->updated_at);
                $this->updated_at = date('m/d/Y', $this->updated_at);

                parent::afterFind ();
            }
   

1 comment:

  1. It is nice post and I found some interesting information on this blog, keep it up. Thanks for sharing. . .
    Remote Yii Framework Developers in India

    ReplyDelete