Yii Wont Update Single Field.

When i update using the form below, it wont change the date of birth… i all of a sudden stopped working…

//usersController




	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Users']))

		{

			$model->attributes=$_POST['Users'];

                        $model->LastUpdate=date_create()->format('Y-m-d H:i:s');

			if($model->save()) {

                                $auth=Yii::app()->authManager;

                                $auth->revoke(Roles::model()->findByPk(Users::model()->findByPk($model->id)->roles_id)->description,$model->id);

                                $auth->assign(Roles::model()->findByPk($model->roles_id)->description,$model->id);

				$this->redirect(array('viewProfile','id'=>$model->id));

                        }

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}



//Model Rules




public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('username, password, callsign, rank, joindate, DOB, gender, picture, fetishes, orientation, email, muted, DateCreated, LastUpdate, roles_id, positions_id', 'required'),

			array('rank, gender, muted, roles_id, positions_id', 'numerical', 'integerOnly'=>true),

			array('username, password, picture, fetishes, orientation, triggers, hypnotic_nuances, otherim', 'length', 'max'=>255),

			array('callsign', 'length', 'max'=>2),

			array('email, skype, aim, msn, yim', 'length', 'max'=>45),

			array('description', 'safe'),

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

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

			array('id, username, password, callsign, rank, joindate, DOB, gender, description, picture, fetishes, orientation, triggers, hypnotic_nuances, email, skype, aim, msn, yim, otherim, muted, DateCreated, LastUpdate, roles_id, positions_id', 'safe', 'on'=>'search'),

		);

	}



//Form Entry




	<div class="row">

		<?php echo $form->labelEx($model,'DOB'); ?>

		<?php $this->widget('zii.widgets.jui.CJuiDatePicker',array(

                                'name'=>'Modelname[DOB]',

                                'id'=>'Modelname_DOB',

                            'value'=>Yii::app()->dateFormatter->format("y-M-d",strtotime($model->DOB)),

                                'options'=>array(

                                'showAnim'=>'slideDown',

                                'changeMonth'=>true,

                                'changeYear'=>true,

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

                                'maxDate' => date('Y-m-d',strtotime('-18 years')),

                                ),

                                'htmlOptions'=>array(

                                'style'=>'height:20px;'

                                ),

                        )); ?>

		<?php echo $form->error($model,'DOB'); ?>

	</div>



i’ve checked the database… i’ve checked the Rules and have tried adding it into the rules in multiple places. it was working a while ago… and it gives no errors that the update to the database has failed…

just to be clear, DOB is stored as a DATE. and it was working with this form datepicker earlier. i’ve changed nothing in the form or the controller…

here’s the database.




Table structure for table `users`

--


CREATE TABLE IF NOT EXISTS `users` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(255) NOT NULL,

  `password` varchar(255) NOT NULL,

  `callsign` varchar(2) NOT NULL,

  `rank` int(11) NOT NULL,

  `joindate` date NOT NULL,

  `DOB` date NOT NULL,

  `gender` int(11) NOT NULL,

  `description` text,

  `picture` varchar(255) NOT NULL,

  `fetishes` varchar(255) NOT NULL,

  `orientation` varchar(255) NOT NULL,

  `triggers` varchar(255) DEFAULT NULL,

  `hypnotic_nuances` varchar(255) DEFAULT NULL,

  `email` varchar(45) NOT NULL,

  `skype` varchar(45) DEFAULT NULL,

  `aim` varchar(45) DEFAULT NULL,

  `msn` varchar(45) DEFAULT NULL,

  `yim` varchar(45) DEFAULT NULL,

  `otherim` varchar(255) DEFAULT NULL,

  `muted` tinyint(1) NOT NULL,

  `DateCreated` datetime NOT NULL,

  `LastUpdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  `roles_id` int(11) NOT NULL,

  `positions_id` int(11) NOT NULL,

  PRIMARY KEY (`id`),

  UNIQUE KEY `username_UNIQUE` (`username`),

  UNIQUE KEY `callsign_UNIQUE` (`callsign`),

  KEY `fk_users_roles_idx` (`roles_id`),

  KEY `fk_users_positions1_idx` (`positions_id`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;



Something must have changed for it to not be working now, but I can’t help with that at this time. I do have a couple of other observations:

RULES: Rules should only validate actual user input. Your action code is setting ‘last_update’ so it shouldn’t be required in the rules. Your SQL show that ‘id’ is an auto_increment. I would take both of these out of the rules. The CRUD generated by Gii in Yii 1.1 does not know if a field with a default needs to be changed by the user or not, so it puts everything in the rules. The SQL also indicates that ‘last_update’ will populate itself, so you really don’t need to set it in your action.

CJuiDatePicker: I have seen this code for setting the name and id in a number of posts, where did you find it? In a form I have always used:




$this->widget('zii.widgets.jui.CJuiDatePicker', array(

    'model' => $profileModel,

    'attribute' => 'birth_date',

    'value' => ...



Thinking on the original problem. I had a problem with using 2 digit dates. I finally went with a beforeSave() afterFind() routine. Actually I made a behavior




<?php


/**

 * Automatically convert date and datetime field to PHP5 DateTime object

 *

 * Inspired from DateTimeI18NBehavior and EDateTimeBehavior

 *

 * @author Jeff Kofsky

 * @version 1.0.0

 */

class DateTimeBehavior extends CActiveRecordBehavior {


    public $mySqlDateFormat = 'Y-m-d';

    public $mySqlDateTimeFormat = 'Y-m-d H:i:s';

    public $localDateFormat = 'm/d/Y';

    public $localDateTimeFormat = 'm/d/Y H:i:s';


    public function afterFind($event) {

        foreach ($event->sender->tableSchema->columns as $attribute => $column) {

            if (($column->dbType != 'date') && ( $column->dbType != 'datetime'))

                continue;


            if (!strlen($event->sender->$attribute)) {

                $event->sender->$attribute = null;

                continue;

            }


            $timestamp = strtotime($event->sender->$attribute);


            if ($column->dbType == 'date') {

                $event->sender->$attribute = date($this->localDateFormat, $timestamp);

            } elseif ($column->dbType == 'datetime') {

                $event->sender->$attribute = date($this->localDateTimeFormat, $timestamp);

            }

        }

    }


    public function beforeSave($event) {

        foreach ($this->getOwner()->tableSchema->columns as $attribute => $column) {

            if ((strtolower($column->dbType) != 'date') && (strtolower($column->dbType) != 'datetime')) {

                continue;

            }


            if (!strlen($event->sender->$attribute)) {

                $event->sender->$attribute = null;

                continue;

            }


            $timestamp = strtotime($event->sender->$attribute);


            if (strtolower($column->dbType) == 'date') {

                $sqlDate = date($this->mySqlDateFormat, $timestamp);

                $this->getOwner()->{$attribute} = $sqlDate;

            } elseif (strtolower($column->dbType) == 'datetime') {

                $sqlDateTime = date($this->mySqlDateTimeFormat, $timestamp);

                $event->sender->$attribute = $sqlDateTime;

            }

        }

    }


}



This looks through all attributes for DATE and DATETIME fields and modifies the value for the DB or user viewing. I had to use the 4-digit year to get my birthday to save properly.

that way didn’t work. it wouldn’t recognise “attribute” at all. i kept getting errors.

though, idk if this is relivant. something did happen to the database. it wouldn’t let me access it with the root user anymore… saying it wasn’t there… but i checked in the mysql directory and everything was still there… so i deleted it and imported it again. every other thing works though :C i’ll try saving already formatted dates in the database by making a new controller just to test stuff. i’ll give you the results.

FIXED.

had to change




'name'=>'Modelname[DOB]',

'id'=>'Modelname_DOB',



to




'name'=>'Users[DOB]',

'id'=>'Users_DOB',



i just didn’t understand it at first… so sorry. i feel so stupid.

the code i got it from was very very badly documented.