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.
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()