我试图让集合原型(prototype)具有一组默认值而不是空白值。理想情况下,我希望能够在模型类或表单定义类的某处定义这些默认值,但我无法在任何地方找到这样做的方法。
举个例子:
我为我的表单创建了一个 AbstractType,其中包含 Person 行的嵌套集合(相关代码如下所示):
public function buildForm(FormBuilder $builder, array $options)
{
...
$builder->add('people', 'collection', array(
'type' => new PersonType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
));
...
}
PersonType 类包含以下代码:
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('name', 'text');
$builder->add('date_of_birth', 'date');
$builder->add('age', 'number');
// This would be great if I could do this but I can't:
//$builder->add('date_of_birth', 'date', array('empty_value' => new \DateTime(...))); // some default value defined here
}
到目前为止,我能想到的最好的在 View 文件中显示如下(显示的代码用于呈现集合原型(prototype)):
...
<tr>
<td> {{ form_widget(person.name) }} </td>
{# THIS DOES NOT WORK (I just get the default selected date) #}
<td> {{ form_widget(person.date_of_birth, {'value': person.date_of_birth.get('value')|default({'year':2010, 'month':10, 'day':15})} }} </td>
{# THIS WORKS (the field contains '0' instead of being empty) #}
<td> {{ form_widget(person.age, {'value': person.age.get('value')|default(0)} }} </td>
</tr>
...
protected $age = 10;
)或表单定义(AbstractType)类(例如数组('empty_value' => new DateTime() ),但目前都不可能。总而言之,我的问题是:
如何为模型类定义默认值,当将新项目添加到表单“集合”时将在客户端自动设置(而不仅仅是获取空白)。
有谁知道这样做的好方法?
最佳答案
在使用表单的实体的构造函数中,您只需使用\DateTime 对象设置日期,如下所示:
class MyEntity {
private $myDate;
public function __construct() {
$this->myDate = new \DateTime('today');
}
}
您也可以使用\DateTime('now') 或\DateTime('tomorrow'),如下面的讨论所述
http://groups.google.com/group/symfony2/browse_thread/thread/18a5b20aca485dc4/e9947d0f06d6519d
编辑 :实际上,这些信息在 symfony2 文档中:
http://symfony.com/doc/2.0/book/forms.html#building-the-form
关于Symfony2 - 表单集合原型(prototype)中的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7503661/