I Need To Display Mysql Now() By Default On Form

I’m new to Yii and need to display MySQL NOW() by default in a form field. My table looks like:

±-----------±-----------------±-----±----±------------------±----------------------------+

| Field | Type | Null | Key | Default | Extra |

±-----------±-----------------±-----±----±------------------±----------------------------+

| id | int(10) unsigned | NO | PRI | NULL | auto_increment |

| start_time | timestamp | NO | | CURRENT_TIMESTAMP | |

| end_time | timestamp | YES | | NULL | on update CURRENT_TIMESTAMP |

| notes | text | NO | | NULL | |

±-----------±-----------------±-----±----±------------------±----------------------------+

I’d like the ‘Start_time’ field to display ‘now()’ output as the default and then have ‘end_time’ receive ‘now()’ upon INSERT, so that there should be a difference in times dependind upon the time it takes to enter the ‘notes’ data.

So far I’ve generated the model and think additional code should be added to ‘_form.php’, but I’m not sure. I’ve looked all over for examples on how to do this on the Yii site as well as refering to a couple of tutorials, but I’m in over my head. Can anyone give me any pointers?

Hi,

please see this

http://www.yiiframework.com/doc/api/1.1/CTimestampBehavior

just put your model




public function behaviors(){

	return array(

		'CTimestampBehavior' => array(

			'class' => 'zii.behaviors.CTimestampBehavior',

			'createAttribute' => 'start_time',

			'updateAttribute' => 'end_time',

		)

	);

}

I added the following to my model. However, when the page associated with the model is requested, I only get a blank textbox where I was hoping to see a time displayed. Do I have to source or import anyrhing, or am I overlooking something else?

// My added code

public function behaviors(){


return array(


	'CTimestampBehavior' => array(


		'class' => 'zii.behaviors.CTimestampBehavior',


		'createAttribute' => 'create_time_attribute',


		'updateAttribute' => 'update_time_attribute',


	)


);


}

Hi ronallensmith,

Maggie Q has provided you with the complete code that you can copy and paste directly into your model. Your code is different.


'createAttribute' => 'create_time_attribute',

'updateAttribute' => 'update_time_attribute',



You don’t have any ‘create_time_attribute’ or ‘update_time_attribute’ in your table.

It should be ‘start_time’ and ‘end_time’

Doh,

Thanks Maggie Q and BlkRaven. That got by me. However, the following is added to the model now:

public function behaviors(){

return array(

'CTimestampBehavior' => array(


	'class' => 'zii.behaviors.CTimestampBehavior',


	'createAttribute' => 'start_time',


	'updateAttribute' => 'end_time',


)

);

}

The textbox is still empty when the page is requested though. The only thing I can think of is that the ‘framework’ folder is moved up a directory, out of the app directory, to www/webroot. Although it is referenced correctly as ‘$yii=dirname(FILE).’/../../framework/yii.php’;’ in the app index.php file. I don’t know if that is meaningful.

Any thoughts? Thanks for your help.

Hi ronallensmith

Since you can request a page, the path to the framework is okay.

Which textbox is still empty? Is it both the start and end time? If it’s just the end time, add the line ‘setUpdateOnCreate’=>true as shown below:


 return array(

                'CTimestampBehavior' => array(

                        'class' => 'zii.behaviors.CTimestampBehavior',

                        'createAttribute' => 'start_time',

                        'updateAttribute' => 'end_time',

                       'setUpdateOnCreate'=>true,//<---ADD THIS LINE

                )

        );




If it’s not just the end_time textbox, can you post your model, controller and view code, please?

<?php

/**

  • This is the model class for table "tblcontacts".

  • The followings are the available columns in table ‘tblcontacts’:

  • @property string $id

  • @property string $start_time

  • @property string $end_time

  • @property string $notes

*/

class TblContacts extends CActiveRecord

{

/**


 * Returns the static model of the specified AR class.


 * @param string &#036;className active record class name.


 * @return TblContacts the static model class


 */


public static function model(&#036;className=__CLASS__)


{


	return parent::model(&#036;className);


}





/**


 * @return string the associated database table name


 */


public function tableName()


{


	return 'tblcontacts';


}





/**


 * @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('start_time, notes', 'required'),


		array('end_time', 'safe'),


		// The following rule is used by search().


		// Please remove those attributes that should not be searched.


		array('id, start_time, end_time, notes', 'safe', 'on'=&gt;'search'),


	);


}





// My added code


public function behaviors(){


return array(


	'CTimestampBehavior' =&gt; array(


		'class' =&gt; 'zii.behaviors.CTimestampBehavior',


		'createAttribute' =&gt; 'start_time',


		'updateAttribute' =&gt; 'end_time',


	)


);


}





/**


 * @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=&gt;label)


 */


public function attributeLabels()


{


	return array(


		'id' =&gt; 'ID',


		'start_time' =&gt; 'Start Time',


		'end_time' =&gt; 'End Time',


		'notes' =&gt; 'Notes',


	);


}





/**


 * 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.





	&#036;criteria=new CDbCriteria;





	&#036;criteria-&gt;compare('id',&#036;this-&gt;id,true);


	&#036;criteria-&gt;compare('start_time',&#036;this-&gt;start_time,true);


	&#036;criteria-&gt;compare('end_time',&#036;this-&gt;end_time,true);


	&#036;criteria-&gt;compare('notes',&#036;this-&gt;notes,true);





	return new CActiveDataProvider(&#036;this, array(


		'criteria'=&gt;&#036;criteria,


	));


}

}

----------------snip----------------

<?php

class TblContactsController 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 &#036;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'=&gt;array('index','view'),


			'users'=&gt;array('*'),


		),


		array('allow', // allow authenticated user to perform 'create' and 'update' actions


			'actions'=&gt;array('create','update'),


			'users'=&gt;array('@'),


		),


		array('allow', // allow admin user to perform 'admin' and 'delete' actions


			'actions'=&gt;array('admin','delete'),


			'users'=&gt;array('admin'),


		),


		array('deny',  // deny all users


			'users'=&gt;array('*'),


		),


	);


}





/**


 * Displays a particular model.


 * @param integer &#036;id the ID of the model to be displayed


 */


public function actionView(&#036;id)


{


	&#036;this-&gt;render('view',array(


		'model'=&gt;&#036;this-&gt;loadModel(&#036;id),


	));


}





/**


 * Creates a new model.


 * If creation is successful, the browser will be redirected to the 'view' page.


 */


public function actionCreate()


{


	&#036;model=new TblContacts;





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['TblContacts']))


	{


		&#036;model-&gt;attributes=&#036;_POST['TblContacts'];


		if(&#036;model-&gt;save())


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


	}





	&#036;this-&gt;render('create',array(


		'model'=&gt;&#036;model,


	));


}





/**


 * Updates a particular model.


 * If update is successful, the browser will be redirected to the 'view' page.


 * @param integer &#036;id the ID of the model to be updated


 */


public function actionUpdate(&#036;id)


{


	&#036;model=&#036;this-&gt;loadModel(&#036;id);





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['TblContacts']))


	{


		&#036;model-&gt;attributes=&#036;_POST['TblContacts'];


		if(&#036;model-&gt;save())


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


	}





	&#036;this-&gt;render('update',array(


		'model'=&gt;&#036;model,


	));


}





/**


 * Deletes a particular model.


 * If deletion is successful, the browser will be redirected to the 'admin' page.


 * @param integer &#036;id the ID of the model to be deleted


 */


public function actionDelete(&#036;id)


{


	&#036;this-&gt;loadModel(&#036;id)-&gt;delete();





	// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser


	if(&#33;isset(&#036;_GET['ajax']))


		&#036;this-&gt;redirect(isset(&#036;_POST['returnUrl']) ? &#036;_POST['returnUrl'] : array('admin'));


}





/**


 * Lists all models.


 */


public function actionIndex()


{


	&#036;dataProvider=new CActiveDataProvider('TblContacts');


	&#036;this-&gt;render('index',array(


		'dataProvider'=&gt;&#036;dataProvider,


	));


}





/**


 * Manages all models.


 */


public function actionAdmin()


{


	&#036;model=new TblContacts('search');


	&#036;model-&gt;unsetAttributes();  // clear any default values


	if(isset(&#036;_GET['TblContacts']))


		&#036;model-&gt;attributes=&#036;_GET['TblContacts'];





	&#036;this-&gt;render('admin',array(


		'model'=&gt;&#036;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 &#036;id the ID of the model to be loaded


 * @return TblContacts the loaded model


 * @throws CHttpException


 */


public function loadModel(&#036;id)


{


	&#036;model=TblContacts::model()-&gt;findByPk(&#036;id);


	if(&#036;model===null)


		throw new CHttpException(404,'The requested page does not exist.');


	return &#036;model;


}





/**


 * Performs the AJAX validation.


 * @param TblContacts &#036;model the model to be validated


 */


protected function performAjaxValidation(&#036;model)


{


	if(isset(&#036;_POST['ajax']) &amp;&amp; &#036;_POST['ajax']==='tbl-contacts-form')


	{


		echo CActiveForm::validate(&#036;model);


		Yii::app()-&gt;end();


	}


}

}

----------------snip----------------

This is _form.php:

<?php

/* @var $this TblContactsController */

/* @var $model TblContacts */

/* @var $form CActiveForm */

?>

<div class="form">

<?php $form=$this->beginWidget(‘CActiveForm’, array(

'id'=&gt;'tbl-contacts-form',


'enableAjaxValidation'=&gt;false,


// start the form with the cursor in the notes field


'focus'=&gt;array(&#036;model, 'notes')

)); ?>

&lt;p class=&quot;note&quot;&gt;Fields with &lt;span class=&quot;required&quot;&gt;*&lt;/span&gt; are required.&lt;/p&gt;





&lt;?php echo &#036;form-&gt;errorSummary(&#036;model); ?&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'start_time'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'start_time'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'start_time'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'end_time'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'end_time'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'end_time'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'notes'); ?&gt;


	&lt;?php echo &#036;form-&gt;textArea(&#036;model,'notes',array('rows'=&gt;6, 'cols'=&gt;50)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'notes'); ?&gt;


&lt;/div&gt;





&lt;div class=&quot;row buttons&quot;&gt;


	&lt;?php echo CHtml::submitButton(&#036;model-&gt;isNewRecord ? 'Create' : 'Save'); ?&gt;


&lt;/div&gt;

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

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

Thanks for that. I can’t see where the problem lies. In what view are you trying to looking at the textbox? Is it in the update or create view?

Edit:

In the rules in your model, the start_time does not need to be required as it doesn’t require user input.

Thanks,

I’ll take care of “…the start_time does not need to be required…”.

From ‘/index.php/site/login’ I log in and go to ‘/index.php/tblContacts/create’, where I get a normal form–only both the textboxes are empty. I only need the datetime displayed in the “Start Time” field, with the following INSERT taking care of the datetime for the “End Time” field, after typing in the “Notes”. I think ‘/index.php/tblContacts/create’ requests _form.php. I think that’s right???

Now my rules are:

public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('notes', 'required'),


		array('end_time', 'safe'),


		// The following rule is used by search().


		// Please remove those attributes that should not be searched.


		array('start_time, notes', 'safe', 'on'=&gt;'search'),


	);


}

However, now I’m wondering if I even need the “End Time” field, since the whole idea is ti have the system do the INSERT of that value upon an UPDATE.

Hi

In the create view, those fields will be empty. The CTimestamp behavior adds the timestamp just before the record is saved to your database.

Try and create some notes and save them. If they validate and save successfully, you should be able to see them in your admin view.

Wow, you’re right! I wasn’t countinting on that behavior–never would’ve guessed it. Now the problem is that CTimestampBehavior is only needed for the ‘end_time’ field. This is because the whole point is to time how long it takes to create what’s in the “Notes” field. So, the idea is to have the start_time be the time at which the Create view is requested by clicking on the Create TblContacts link. I’ll take a look at some of the other Classes and I’ll also have to add another field to the table. I’ll post additional code after that. Thanks, you’ve given me some direction now. :)

Glad to hear you are making progress. To do what you described in your last post:

In TblContactsController, under actionCreate(), set the start time before the view is rendered like so:




public function actionCreate()

{

$model=new TblContacts;

$model->start_time=NOW(); //ADD THIS LINE




  • In your CTimeStamp behavior code, set ‘createAttribute’ to null like so:

'createAttribute' => NULL,

Good luck :)

I added the following to the tblContactsController:

public function actionCreate()

{

&#036;model=new TblContacts;





// added code to set the start time of the record


&#036;model-&gt;startTime=NOW(); // I changed the field name/format in the table

}

However, I got the message ‘Fatal error: Call to undefined function NOW()’, when rendering ‘/index.php/tblContacts/create’.

Also, changed the following in the TblContacts model since I want the creation of the record to record the endTime (Let me know if I’m wrong on this.):

public function behaviors()

{

    return array(


            'CTimestampBehavior' =&gt; array(


                    'class' =&gt; 'zii.behaviors.CTimestampBehavior',


                    'createAttribute' =&gt; 'endTime',


                    'updateAttribute' =&gt; NULL,


            )


    );

}

Thanks again.

also you can try this


$model->startTime=date('Y-m-d H:i:s');

Thanks for the correction, Maggie Q :)

NOW() is a sql function.

ronallensmith,

re your question:

No, it’s not wrong. You are welcome :)

:) Now things are getting interesting. I noticed ‘$model->startTime=date(‘Y-m-d H:i:s’);’ produces a time different from that of:

public function behaviors()

{


    return array(


            'CTimestampBehavior' =&gt; array(


                    'class' =&gt; 'zii.behaviors.CTimestampBehavior',


                    'createAttribute' =&gt; 'endTime',


                    'updateAttribute' =&gt; NULL,


            )


    );


}

It seems like a timezone issue. I’ll look into that, but ‘index.php/tblContacts/create’ is doing a proper INSERT–no errors now. Thanks to you both.

As a newbie I think my weakest area is what controls/affects what in the framework and how to use the different classes/methods. Do either of you have pointers on any books or sites that would be of benefit?

If you want to start step by step, then I would recommend the Yii Tutorial or one of the Yii books. When looking at the Yii tutorial, try to read the comments at the bottom of the tutorial. There’s a lot of knowledge there.

If you want to know what affects what, then the API documentation will help a lot with that. An example is the CTimeStampBehavior. The api documentation gives a description for each property and function. You can also view the source code to get a better idea of what is going on. If you look the beforeSave() function of that class, you’ll see that that’s when the timestamp gets assigned to your createAttribute or updateAttribute. If need help understanding any part of the API documentation, then do a search in the forums and the wiki because it’s highly likely that someone else has had a similar problem and an answer has been provided.

Hope that helps.