Select or create an entity - forms

I usually find answers to solve my problems after some research, but that is not the case today.
Let's suppose I have 2 entities, "Task" and "TaskCategory", each task has one category.
I want to let my users not only attribute an existing category to their tasks but also create new ones.
Here's the code I have so far:
<?php
// TaskCategoryType.php
class TaskCategoryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
;
}
// Some stuff...
and
<?php
// TaskType.php
// Some stuff...
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// Add some fields there
->add(
'category',
TransformableEntityType::class,
['class' => 'AppBundle:TaskCategory']
)
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$task = $event->getData();
$form = $event->getForm();
if (empty($task['category']['id']) && !empty($task['category']['name'])) {
$task['category']['id'] = null;
$event->setData($task);
$form->remove('category');
$form->add('category', TaskCategoryType::class);
}
})
;
}
// Some stuff...
It works fine for task creation, but when I edit an existing task, it edit the associated TaskCategory instead of creating a new one.
I was trying to force the creation of a new TaskCategory with : $task['category']['id'] = null; but it does not work.
Thanks for your help I'm really stuck :(
EDIT: I forgot to mention that I'm using this form only as an API that's why I have only one 'category' field, otherwise I would have used another 'category_new' field.

Well it seems I finally found something working, it's not pretty, I'm not pretty happy with how it's done but at the moment I have not found any alternative.
If you have a cleaner solution I'll be happy to learn.
<?php
class TaskType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// Some fields...
->add(
'category',
TransformableEntityType::class,
['class' => 'AppBundle:TaskCategory']
)
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$task = $event->getData();
$form = $event->getForm();
if (empty($task['category']['id']) && !empty($task['category']['name'])) {
// If there is no category id but there is a category
// name it means it is a new category. so replace
// the custom entity field with this simple field
$form->remove('category');
$form->add('category', TaskCategoryType::class, ['allow_extra_fields' => true]);
}
})
->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
$catForm = $event->getForm()->get('category');
if ($catForm->has('name') && $catForm->get('name')->getData() !== "") {
// If there is a category name it means
// it is a new category.
$category = new TaskCategory(); // Create new category
$category->setName($catForm->get('name')->getData());
$task = $event->getData()->setCategory($category);
$event->setData($task);
}
})
;
}

Considering you have cascade-persist enabled for your association from Task to TaskCategory. I guess the best work around will be, to use an autocompleter which should work as tag based.
The Transformer should check with database if given TaskCategory is available, else create a new one.

Related

how to retrieve data from a form in the controller of an api rest in symfony

I am registering a doctor in my api through my symfony controller. And for that I created a form for the doctor, and then I have to persist these data in my database. And that's where I can not get the data from the form, that's what I tried on my postman, but it returns me a 500 error saying:
Child \"username\" does not exist.
I'm trying to recover my form data through this query:
$user->setUsername($form['username']);
Controller
/**
* #Route("/api/inscription/medecin")
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Method("POST")
*/
public function postDocAction(Request $request){
$medecin = new Medecin();
$user = new User();
$user->setSalt('');
$form = $this->createForm('Doctix\MedecinBundle\Form\MedecinType', $medecin);
$form->submit($request->request->all()); // Validation des données
if ($form->isValid()){
$encoder = $this->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encoded);
$user->setUsername($form['username']);
$user->setRoles(array('ROLE_MEDECIN'));
$user->setNom($form['nom']);
$user->setPrenom($form['prenom']);
$user->setNumTel($form['numTel']);
$user->setAdresse($form['adresse']);
$medecin->setUser($user);
$medecin->setSexe($form['sexe']);
$medecin->setQuartier($form['quartier']);
$medecin->setNumOrdre($form['numordre']);
$medecin->setSpecialite($form['specialite']);
$medecin->setClinique($form['clinique']);
$em = $this->getDoctrine()->getManager();
$em->persist($medecin);
$em->flush();
}
}
Form
class MedecinType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('user',UserType::class)
->add('sexe', TextType::class)
->add('specialite',SpecialiteType::class)
->add('clinique',CliniqueType::class)
->add('quartier', TextType::class)
->add('numordre', TextType::class)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Doctix\MedecinBundle\Entity\Medecin',
'csrf_protection' => false
));
}
}
Test in Postman
After you do $form->handleRequest($request);,
$form->getData() holds the submitted values.
But, the original $medecin variable has also been updated. So non need to set all the fields again.
https://symfony.com/doc/current/forms.html#handling-form-submissions
short answer :
According to the json, user seems to be an object so to access username, you should probably write:
$form["user"]["username"];
You should apply the same logic to all elements inside user.
complete answer :
There are multiple incoherences in your code. The advantage of passing the object into the createForm() method, is that the object will automaticaly be updated once the form is submited and valid. This avoid you to go throught all the setters later as you are doing now.
So if you want the user object to be correcly updated into the medecin's object, you should set the user before creating the form :
<?php
/**
* #Route("/api/inscription/medecin")
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Method("POST")
*/
public function postDocAction(Request $request){
$medecin = new Medecin();
$user = new User();
$user->setSalt('');
$user->setRoles(['ROLE_MEDECIN']);
$medecin->setUser($user);
$form = $this->createForm('Doctix\MedecinBundle\Form\MedecinType', $medecin);
$form->submit($request->request->all()); // Validation des données
if ($form->isValid()) {
$encoder = $this->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encoded);
$em = $this->getDoctrine()->getManager();
$em->persist($user); // Safety, as i don't know how you configured your entities
$em->persist($medecin);
$em->flush();
}
}

Access form data dynamically in symfony 4

I have created following simple form in symfony 4.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
->add('message',TextareaType::class)
;
}
I access these data from a controller method like following:
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
$formdata = $form->getData();
$concatenatedData = implode (",", array("Name: ".$formdata['name'], "E-mail: ".$formdata['email'], "Message: ".$formdata['message']));
Now i need to add more fields in the form. In that case, I need to loop through the $formdata and get those values in $concatenatedData. I am new in symfony. Can anyone give me any hints how to do that dynamically in symfony 4 ?
Many thanks in advance.
create a class that you need after defining in form class
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('price');
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Content::class,
));
}
}
Follow
$content = new Content();
$form = $this->createForm(ContactType::class, $content);
$form->handleRequest($request);
$formdata = $form->getData();
$content->getName();
$content->getOther();
...

The best practies for upload file in Symfony 3

I learned Symfony 3 and I want create form class to upload File, so i created ImageType, cutom form type to handle image uploaded in NewsType (form with some description and this field):
class ImageType extends AbstractType
{
private $path;
public function __construct($path)
{
$this->path = $path;
}
public function getParent()
{
return FileType::class;
}
public function getName()
{
return 'image';
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'image_name' => ''
));
}
/**
* #param FormView $view
* #param FormInterface $form
* #param array $options
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['image_name'] = $options['image_name'];
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAttribute('image_name', $options['image_name'])
->addModelTransformer(new ImageTransformer($this->path))
}
}
I use ImageTransformer to transform file name like 124324235342.jpg to instance File class. Form work fine when i created and saved date to database, but how manage entity in edit mode ?
public function editAction(Request $request, News $news)
{
$path = $this->getParameter('upload_directory') . $news->getImage();
$image = $news->getImage();
$form = $this->createForm(NewsType::class, $news, ['image_name' => $image]);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
$this->get('app.image_uploader')->uploadNews($news, $image);
$em = $this->getDoctrine()->getManager();
$em->persist($news);
$em->flush();
return $this->redirectToRoute('admin_news_index');
}
return $this->render('admin/news/form.html.twig', [
'form' => $form->createView(),
'news' => $news
]);
}
I want handle case to use same form to edit database entity. I populated form, but when user not upload image I don't want change this field and live old value. How accomplish this ?
The simplest method for your code:
In setter of your News type:
function setImage($image) {
if(strlen($image)) {
$this->image = $image;
}
}
This allow you to do not worry about case of lacking image, when user edits other fields. In this case $this->fileName in News will be not overwritten.
Then in service app.image_uploader you should check if file with given name exist. If not then you should not overwrite this file.
But there are some other poroblems:
1) You should validate extension of file.
2) You should use unique names for your files in your server different than names from users. Yo can use both names, your unique for string files in hard drive, and name form user in user interface, but you should not use name of file form user to store file in your hard drive.
I recommend to read about these problems in docs:
https://symfony.com/doc/current/controller/upload_file.html
Or on stack overflow:
Symfony2 file upload step by step

How to generate a 'collection' form in Symfony, generated by each object within an entity?

Having read through the Symfony forms collection/entity types I'm trying to generate a form that only involves these two attributes of an entity (Person) but uses all instances of Person in the database. The purpose of the form is to provide a activation tickbox for every person on a single page so that multiple status' can be flushed to the database on form submission. Eg, the form should look something like:
☑ John Smith
☐ Jane Doe
☑ ...etc
☑ ...etc
My attempts below are not working as they just return an empty page, although I can see that $allpersons is populated
My Person entity:
class Person
{
/**
* #ORM\COLUMN(type="boolean")
*/
protected $active = true;
/**
* #ORM\COLUMN(type="string", length=100)
*/
protected $fullname ;
/* ...many other attributes... */
}
My Controller:
class DefaultController extends BaseController {
public function ​activePersonsAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$persons = $em->getRepository('AppBundle:Person')->findAll();
$form = $this->createForm(AllPersonsType::class, $persons);
$form->handleRequest($request);
if ($form->isSubmitted() && ($form->isValid())) {
$em = $this->getDoctrine()->getManager();
$persons = $form->getData();
foreach ($persons as $person) {
$em->persist($person);
}
$em->flush();
return $this->redirectToRoute('home_user');
}
return $this->render('activatePersons.html.twig', array(
'page_title' => 'Active Persons',
'form' => $form->createView(),
));
}
}
My FormTypes:
class AllPersonsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('persons', CollectionType::class, array(
'entry_type' => ActivatePersonType::class
));
}
public function getName()
{
return 'person';
}
}
class ActivatePersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('active',CheckboxType::class)
->add('fullname', TextType::class);
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Person',
));
}
public function getName()
{
return 'person';
}
}
You pass $persons collection as form data to AllPersonsType, while the type expects that you pass an array with persons key and persons collection as value.
$form = $this->createForm(AllPersonsType::class, ['persons' => $persons]);

Symfony2: How call the repository of an entity in the FormType

I tried to call the repository of my entity Category in the class form of my entity BonCommande, but this error ocuured:
Notice: Undefined property: Application\VehiculeBundle\Form\BonCommandeType::$em in C:\wamp\www\Symfony_test\src\Application\VehiculeBundle\Form\BonCommandeType.php line 74
This is my code:
The class BonCommandeType.php:
namespace Application\VehiculeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Application\VehiculeBundle\Entity\Category;
class BonCommandeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
// Name of the user
$builder->add('observation', 'text');
/* Add additional fields... */
$builder->add('save', 'submit');
// Add listeners
$builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
$builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
}
protected function addElements(FormInterface $form, Category $categorie = null) {
// Remove the submit button, we will place this at the end of the form later
$submit = $form->get('save');
$form->remove('save');
// Add the province element
$form->add('categorie', 'entity', array(
'data' => $categorie,
'empty_value' => '-- Choose --',
'class' => 'ApplicationVehiculeBundle:Category',
'property' => 'intitule',
'mapped' => false)
);
// Cities are empty, unless we actually supplied a province
$vehicules = array();
if ($categorie) {
// Fetch the cities from specified province
$repo = $this->em->getRepository('ApplicationVehiculeBundle:Vehicule');
$cities = $repo->findByCategory($categorie);
}
// Add the city element
$form->add('vehicule', 'entity', array(
'empty_value' => '-- Select a categorie first --',
'class' => 'ApplicationVehiculeBundle:Vehicule',
'choices' => $vehicules,
));
// Add submit button again, this time, it's back at the end of the form
$form->add($submit);
}
function onPreSubmit(FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
// Note that the data is not yet hydrated into the entity.
$categorie = $this->em->getRepository('ApplicationVehiculeBundle:Category')->find($data['categorie']);
$this->addElements($form, $categorie);
}
function onPreSetData(FormEvent $event) {
$account = $event->getData();
$form = $event->getForm();
// We might have an empty account (when we insert a new account, for instance)
$categorie = $account->getVehicule() ? $account->getVehicule()->getCategorie() : null;
$this->addElements($form, $categorie);
}
...
}
This is the instruction that causes the error:
$categorie = $this->em->getRepository('ApplicationVehiculeBundle:Category')->find($data['categorie']);
FormComponent is an independent component and it doesn't provide any entityManager to use. You have to inject it or pass it by $options if you want to use it..
In your case it would be correct if you directly pass it to the type's __construct or pass by $options array or declare your type as a service and inject entity manager to it:
class BonCommandeType extends AbstractType
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
...
}
or
$this->createForm(TYPE, DATA, ['em' => $em]);
From your code I assume you are missing this:
//Somewhere at the begging of your BonCommandeType
protected $em;
...
public function __construct(EntityManager $em)
{
$this->em = $em;
}
Keep in mind that when you create a new form object you should use smth like :
BonCommandeType($this->getDoctrine()->getManager()) // if inside a controller