I have a task to show the user an expiration date for a page. To do this I created a formtype that contains two fields, the first one allows to choose between 1 week 1month and 1 year and custom. if the customer chooses custom, another calendar field is displayed. after I used the datatransformer because the first field returns a string ('1week', '1year' ...) and the second field it will be either null or a date the problem is that the reverse transform method works perfectly but the parameter of the transform method is null ie when the user wants to edit the page, he does not see the last values of the two fields.
class ExpiryDateType extends AbstractType {
public function buildForm(\Symfony\Component\Form\FormBuilderInterface $builder, array $options) {
$builder ->add("chosen", \Symfony\Component\Form\Extension\Core\Type\ChoiceType::class,array(
'choices' => array(
'1 week' => '7',
'1 month' => '30',
"1 year"=>"365",
"custom"=>"custom"
)))
->add('ExpiryDate', 'sonata_type_date_picker', array('format' => 'yyyy-MM-dd', 'label' => '', 'required' => false))
->addModelTransformer(new \ADS\CoreBundle\Form\DataTransformer\ExpiryDateTransformer());
}
public function configureOptions(\Symfony\Component\OptionsResolver\OptionsResolver $resolver) {}
public function buildView(\Symfony\Component\Form\FormView $view, \Symfony\Component\Form\FormInterface $form, array $options) {
parent::buildView($view, $form, $options);
}
public function getBlockPrefix()
{
return 'expirydate';
}
}
and that is transformer
class ExpiryDateTransformer implements DataTransformerInterface {
public function transform($date) {
//date is null !!!!
}
public function reverseTransform($array) {
if ($array["chosen"] == "7") {
$date = new \DateTime("now");
$date->modify("+1 week");
$date->format('Y-m-d H:i:s');
return($date);
} else if ($array["chosen"] == "30") {
$date = new \DateTime("now");
$date->modify("+1 month");
$date->format('Y-m-d H:i:s');
return($date);
} else if ($array["chosen"] == "365") {
$date = new \DateTime("now");
$date->modify("+1 year");
$date->format('Y-m-d H:i:s');
return($date);
} else {
return($array["ExpiryDate"]);
}
}
}