好的,我得到了下面描述的 FormType。我将这个 Form 类用于创建和编辑表单。我决定使用选项数组中的属性设置默认日期(from_date
及to_date
以下) 。data
这在设置默认日期方面做得很好,事实上,做得太好了。它还覆盖了编辑表单中的现有日期,这根本不好,真的。
如何设置真正的“默认”值,而不是“始终”值?
<?php
namespace TechPeople\InvoiceBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Security\Core\SecurityContext;
class InvoiceType extends AbstractType
{
private $user;
public function __construct(SecurityContext $security_context)
{
$this->user = $security_context->getToken()->getUser();
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$lastMonth = new \DateTime();$lastMonth->modify('-1 month');
$builder
->add('month', 'choice', array(
'data' => $lastMonth->format('F'),
'choices' => array(
"January" => "January",
"February" => "February",
"March" => "March",
"April" => "April",
"May" => "May",
"June" => "June",
"July" => "July",
"August" => "August",
"September" => "September",
"October" => "October",
"Novemeber" => "Novemeber",
"December" => "December",
)
))
->add('year', null, array(
'data' => $lastMonth->format('Y')
))
->add('from_date', 'date', array(
'label' => 'From',
'data' => new \DateTime(),
))
->add('to_date', 'date', array(
'label' => 'To',
//'data' => new \DateTime(),
))
->add('hours')
->add('expenses')
->add('expense_amount', 'money',
array(
'required' => false,
))
->add('attachment', 'file',
array(
'path'=>$options['data']->getAttachmentPath(),
'required' => false,
)
)
;
if($this->user->hasRole('ROLE_ADMIN')){
$builder->add('vendor');
}
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'TechPeople\InvoiceBundle\Entity\Invoice'
));
}
public function getName()
{
return 'techpeople_invoicebundle_invoicetype';
}
}