问题
I have an Entity named Task and build a Symfony TaskType.php for the form. It is my aim to set the endDate datetime field by default to the input of the startDate datime field (which is required).
I tried this, but it doesn't work.
$builder->add('name');
$builder->add('startDate', 'datetime');
$builder->add('endDate', 'datetime', array(
'empty_value' => array('year' => 'Year', 'month' => 'Month', 'day' => 'Day'),
'required' => false,
'data' => isset($options['data']) ? $options['data']->getEndDate() : $options['data']->getStartDate(),
));
Exception:
An exception occurred while executing 'INSERT INTO Task (name, startDate, endDate) VALUES (?, ?, ?)' with params {"1":"test","2":"2013-03-30 00:00:00","3":null}:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'endDate' cannot be null 500 Internal Server Error - DBALException 1 linked Exception:
PDOException »
回答1:
Yes, of course it doesn't work. I recommend to read about how form works, if you have no time you can just read this "cheatsheet" - http://blog.stfalcon.com/wp-content/uploads/2012/01/how_symfony2_forms_works.pdf.
You can set the value after data was set. For example, try:
$form->bindRequest($request);
// now you can get data and set
$form->get('endDate')->setData($form->get('startDate')->getData());
Hope, it helps.
回答2:
You can also set the values in your entity class when it is instantiated:
class Task
{
protected $startDate;
protected $endDate;
public function __construct($startDate)
{
$this->startDate = $startDate;
$this->endDate = $startDate;
}
}
来源:https://stackoverflow.com/questions/15599375/formtype-default-input-value-in-same-form