Reputation: 2210
I built a form not related to any entity.
class CalculatorType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('debutActivite', 'date', array(
'label' => 'Quand avez-vous commencé votre activité ?',
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'label_attr' => array(
'class' => 'control-label',
),
'attr' => array(
'class' => 'form-control createDatepicker',
'placeholder' => 'dd/mm/aaaa',
),
'required' => true,
))
->add('demandeAccreAccepteeDate', 'date', array(
'label' => 'A quelle date a-t-elle été acceptée ?',
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'label_attr' => array(
'class' => 'control-label',
),
'attr' => array(
'class' => 'form-control createDatepicker',
'placeholder' => 'dd/mm/aaaa',
),
))
}
}
And in my controller, I check if form is valid :
public function indexAction(Request $request)
{
$form = $this->createForm(new CalculatorType(), array());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
}
}
The "demandeAccreAccepteeDate" field is not required. But if it's not empty, i would like to validate that it is greater or equal to "debutActivite" field.
How can I do such a thing, knowing that I have no Calculator entity ?
Upvotes: 0
Views: 1878
Reputation: 1815
Create a class (you don't need to persist it do the DB) to hold your date
namespace Your\Bundle;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
class Daterange
{
/**
* @Assert\Date()
*/
public $debutActivite;
/**
* @Assert\Date()
*/
public $demandeAccreAccepteeDate;
/**
* @Assert\Callback
*/
public function validate(ExecutionContextInterface $context)
{
// Do your checks
if ( ($this->demandeAccreAccepteeDate != '') &&
($this->demandeAccreAccepteeDate < $this->debutActivite) ) {
$context->addViolationAt(
'demandeAccreAccepteeDate',
'Date not valid. Is before debutActivite',
array(),
null
);
}
}
}
Assign the date to your form
class CalculatorType extends AbstractType
{
[..]
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Your\Bundle\Daterange',
));
}
}
And in your controller create the form this way (add use Your\Bundle\Daterange
at the beginning)
$form = $this->createForm(new CalculatorType(), new Daterange());
Upvotes: 1