forms best practice

Hello,

I am wondering what is considered best practice when it comes to forms and form validation.

I wrote a date validator that will turn the date into a unix timestamp for further processing, analogue to the numeric validator that will also normalize the value.

Now i use my Model directly for the form as suggested in the documentation.

Problem is: when a user enters an invalid date, the form is of course re-displayed to him, but the original invalid data he entered is lost, so he just gets an empty field instead of his wrong input.

I would like the user to see his original field input again, so he can correct it instead of re-typing it.

How would you do that?

Thanks for your answers,

mh

That's because your validator does the conversion even when the user enters an invalid date. You should only do so when the date is valid.

I already do that.

I was a bit off-track; the actual problem is how i output the date input field:

<?php echo CHtml::activeTextField($mitarbeiter,'ma_geburtsdatum', array('value'=>

        Yii::app()->dateFormatter->formatDateTime( $mitarbeiter->ma_geburtsdatum, 'medium',null))); ?>

if $mitarbeiter->ma_geburtsdatum is 'abc', formatDateTime will of course try to parse it as a time and output it as a time.

My problem: if the date comes from the database, i want it to run through formatDateTime; if it comes from the user, i don't.

How would you handle that? is there a nice and elegant way?

I would avoid setting the 'value' attribute this way. The conversion should only occur when the input is validated. You may call formatDateTime() inside your date validator.

if i have a update form, i get the data from the database in a format which i do not want to show to my users without formatting first; the validator does not seem the right place for that.

As I understand it, the validator should turn user input into normalized data if correct and else throw an error; I also need to turn normalized data (from db) into user-suitable formatted output somewhere.

Because the DB format is different from user input, I would define a new property using getter/setter to store user input.



private $_dateText;





public function getDateText()


{


    if($this->_dateText===null) // not set before 


         // return the formatted DB value


    else


         return $this->_dateText;


}





public function setDateText($value)


{


     // this is called when user enters data


     $this->_dateText=$value;


}


Then, in beforeSave(), you need to convert _dateText and save it to your DB field.

Your validation should be against 'dateText'. Make sure you also declare 'dateText' in safeAttributes()