I work with Symfony 2.8
我使用Symfony 2.8
I have a table named: "Docentes" with a DateTime field "fechaAlta"
我有一个名为“Docentes”的表,其日期时间字段为“fechaAlta”
I need the default value of this field is "today" when I add a new record
当我添加新记录时,我需要此字段的默认值为“today”
I generate CRUD, using command generate:doctrine:crud
我使用命令generate:doctrine:crud生成CRUD
In the file "DocentesController.php" Symfony create two function: "newAction" and "editAction" (among other). Both using the same Form, insert in the file "DocentesType.php" in the folder "Form":
在文件“DocentesController.php”中,Symfony创建了两个函数:“newAction”和“editAction”(以及其他)。两者都使用相同的表单,插入“Form”文件夹中的文件“DocentesType.php”:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fechaAlta', 'date')
->add('dni')
#
;
}
I tried two solutions:
我试过两个解决方案:
ONE: In the Entity file named, "Docentes.php" I add the function:
ONE:在名为“Docentes.php”的实体文件中添加函数:
public function __construct()
{
$this->fechaAlta = new \DateTime();
}
But when I use the form to add the new record, the field "fechaAlta" is displayed with the values: Day 01, Month 01 and Year 2011. Not with the current date.
但是当我使用表单添加新记录时,字段“fechaAlta”将显示为值:Day 01,Month 01和Year 2011.与当前日期不同。
TWO:
I edit the function buildForm:
我编辑函数buildForm:
->add('fechaAlta', 'date', array(
'data' => new \DateTime()))
##
Now, when I add a new record, I obtain again the values: Day 01, Month 01 and Year 2011 but when I edit a record, Symfony change my original value, for example 2016-03-25 and set the today value! All the opposite of what I need!
现在,当我添加新记录时,我再次获得值:第01天,第01个月和2011年,但是当我编辑记录时,Symfony会更改我的原始值,例如2016-03-25并设置今天的值!与我所需要的完全相反!
2 个解决方案
#1
0
You should replace :
你应该替换:
public function __construct()
{
$this->fechaAlta = new \DateTime();
}
by
public function __construct()
{
$this->fechaAlta = new \DateTime('now');
}
#2
0
Another option:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fechaAlta', 'date', array(
'empty_data' => new \DateTime('now'),
))
->add('dni')
;
}
#1
0
You should replace :
你应该替换:
public function __construct()
{
$this->fechaAlta = new \DateTime();
}
by
public function __construct()
{
$this->fechaAlta = new \DateTime('now');
}
#2
0
Another option:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('fechaAlta', 'date', array(
'empty_data' => new \DateTime('now'),
))
->add('dni')
;
}