Nathan Nathan - 29 days ago 18
PHP Question

Symfony sonata make make formmapper item editable with logical condition

I have a very small problem with symfony but I simply don't now how to start. I now keep changing when I'm coding, never finishing an actual thing.

protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('id')
->add('schedule');
}


Now, schedule is type datetime. An cronjob so that the code will be executed when the schedule matches the current daytime.

The administrator only has to be able to change the schedule datetime when it lies in the future, so read_only should be set to true when it happened in the past.

Small problem, but I don't know what is the best method to do this? I can think of multiple solutions:


  1. Should I create a custom template to override the default edit and build logic using twig?

  2. Inside the configureListField should a create a custom action that links to a custom template?

  3. Should I create a custom controller to let controller decide, and if so, can I keep my configureListField and configureShowField in the admin intact or should list and create also be done via this controller?



Thank you!

Answer

I finally solved it

What I also tried was was getting the value of something you added to the formmapper.

//todo get value
$formMapper
  ->add('date')

So i decided to do a var_dump inside the configureFormField function.

protected function configureFormFields(FormMapper $formMapper)
{
   die("DIED ".var_dump($this)." DIED @".__FILE__." line ".__LINE__);
}

Within the var_dump I found the a variable called subject, within that subject all information you can add to the formmapper is stored.

You can get subject by using:

$this->getSubject()

From within subject you can handle it like it's the entity your trying to edit. In my case this was schedule.

if ($this->getSubject->getSchedule > new \Datetime('now')
{
  $formMapper
     ->add('channel', null, array('label' => 'Choose a channel'));
else
{
  $formMapper
     ->add('channel', null, array('label' => 'Channel', 'read_only' => 'true'));
Comments