0

I work on a Symfony 2.8 project. The system work with TextType / DateTimeType / MoneyType but not for EntityType & DateType also.

I try to define default value on my EntityType from a value in session which is passed in parameters when I create the form in Controller like this:

$filter_form = $this->createForm(FilterActeType::class, null, [
        'filters' => array_merge(
            $defaultFilter,
            $paginatorService->getFiltersFromSessionByContext($usr->getId(), $request->attributes->get('_route'))
        )
    ]);

I have try to use data and choice_value parameters in the EntityType but the problem is the same : when I reload the page, the data is not present in the form filter while the data is in variable session.

Case with data parameter without anonymous function:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'data' => $this->getDataFromFilters($options, 'etude'),
        ]);

Observations: this case has been returned an error message : "... passed to the choice field must be managed. Maybe you forget to persist it in the entity manager ?".

Case with data parameter with anonymous function:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'data' => function (EntityRepository $er) use ($options) {
                if (null != $etude = $this->getDataFromFilters($options, 'etude')) {
                    $er->createQueryBuilder('e')->andWhere('e.id = :id')->setParameter('id', $etude->getId());
                }
            }
        ]);

Observations:: no error returns but no data also.

Case with choice_value parameter:

$builder->add('etude', EntityType::class, [
            'label' => $this->translator->trans('Étude'),
            'class' => Etude::class,
            'required'  => false,
            'attr' => array('dyn-form-data' => 'cabinet,createur,destinataire'), // Champs dynamique => on renseigne le ou les enfants (le(s) champ(s) qui doit être mise à jour à la modification de celui-ci)
            'choice_value' => function() use ($options) {
                return $this->getDataFromFilters($options, 'etude');
            },
        ]);

Observations: no error returns and no data also.

Code from getDataFromFilters method in Form object:

/**
 * @param array $filters
 * @param string $field
 *
 * @return \DateTime|Etude|Cabinet|string|int|float|TypeDocument|ModeDistribution|null
 */
private function getDataFromFilters(array $options, string $field)
{
    return (isset($options['filters'][$field]) && (null != $value = $options['filters'][$field])) ? $value : null;
}

EDIT (24/11/2021): debug added

This is the debug of the entity stored in session:

etude: Etude {#812 ▼
+__isInitialized__: true
-id: 1
-libelle: "Toto"
-mail: "yolo.toto@toto-france.fr"
-origines: PersistentCollection {#811 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#810 ▼
    -elements: []
  }
  #initialized: false
}
-utilisateurs: PersistentCollection {#809 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#808 ▼
    -elements: []
  }
  #initialized: false
}
-cabinets: PersistentCollection {#807 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#806 ▼
    -elements: array:1 [▼
      0 => Cabinet {#805 ▼
        -id: 1
        -libelle: "Cabinet Toto"
        -etude: Etude {#812 …2}
        -infoUserByEtude: PersistentCollection {#804 ▼
          -snapshot: []
          -owner: null
          -association: null
          -em: null
          -backRefFieldName: null
          -typeClass: null
          -isDirty: false
          #collection: ArrayCollection {#803 ▼
            -elements: []
          }
          #initialized: false
        }
        -adresse: null
        -villeCP: null
      }
    ]
  }
  #initialized: true
}
-actes: PersistentCollection {#802 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#801 ▼
    -elements: []
  }
  #initialized: false
}
-typeDocuments: PersistentCollection {#800 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#799 ▼
    -elements: []
  }
  #initialized: false
}
-modeDistributions: PersistentCollection {#798 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#797 ▼
    -elements: []
  }
  #initialized: false
}
-themeMainColor: null
-themeAccentColor: null
-logo: null
-background: null
-sous_domaine: "yolo"
-transactions: PersistentCollection {#794 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#795 ▼
    -elements: []
  }
  #initialized: false
}
-templates: PersistentCollection {#796 ▼
  -snapshot: []
  -owner: null
  -association: null
  -em: null
  -backRefFieldName: null
  -typeClass: null
  -isDirty: false
  #collection: ArrayCollection {#138 ▼
    -elements: []
  }
  #initialized: false
}
-aliasMail: "contact@toto-france.fr"
-smsActif: false
-notificationSmsActif: false
-paiementActif: true
-blocNoteActif: false
-connexionDirecteActif: false
-dureeTokenConnexionDirecte: 2
-smsSenderName: null
-locale: null
-faxActif: false
-dossierDebiteurActif: true
-defaultModuleActif: true
-frequenceNotification: "day"
-objetMail: null
-lienRgpd1: null
-lienRgpd2: null
-mailEchecNotification: null
 …2

}

nboulfroy
  • 201
  • 3
  • 14

1 Answers1

0

Using Symfony/PHP:

Take a look at this answer, hopefully it works for the version you are using, and I believe so cause it says it was added on the 2.7 version: https://stackoverflow.com/a/35941528/17089665

Using JS:

You can send a variable, even if it is stored in the current session, but you should do it in your controller. When you create your form, you can send variables in the render function.

Typically, you will send as an argument an object of the class you are making the form to. I recommend you use the Entity's setters for predefined values.

So... a simple example, if you want to display a dropdown:

AppleController for creating a box of apples:

$arrayOfTypes = however_you_get_your_info(); // <- With different types of apples
$newAppleBox = new AppleBox();
$newAppleBox->setWhateverVariableWithPredefinedValue() // Here, for example, if you were to create a modifyUserInfo template or something like this, you could prepopulate this with the current info so they don't need to write everything again.
$form = $this->createForm(AppleRegistrationType::class, $newAppleBox);

if ($form->isSubmitted() && $form->isValid()) {
// blablabla
}

return $this->render('registrations/appleBox.html.twig', [
        'appleBoxRegistrationForm' => $form->createView(),
        'typesArray' => $arrayOfTypes
]);

Then, in your form, you create your EntityType normally:

use App\Entity\User;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
// ...

$builder->add('users', EntityType::class, [
    'class' => User::class,
     blablabla
]);

And finally in your template you can use twig and js to dinamically retrieve that list and put it in your new <select> (I believe is what EntityType gets traduced to in HTML).

Also, take a look at the official documentation:

https://symfony.com/doc/current/reference/forms/types/entity.html#using-choices

S. Dre
  • 647
  • 1
  • 4
  • 18