0
votes

I have an issue with EntityType form field.

Entity "Freelancer" is in relation ManyToMany with entity "Sapsubdomain". In Form on FreelancerType I added "sapsubdomains" as EntityType.

When I save my form all fields are saved correctly to database exepting "sapsubdomains".

I expect to have relation table between "Freelancer" and "Sapsubdomain" updated but nothing happen. I have no error message ...

Thanks for your help !

"Freelancer" Entity:

<?php

namespace App\Entity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FreelancerRepository")
 */
class Freelancer
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $about;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\User", cascade={"persist", "remove"})
     */
    private $Userid;


    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Sapsubdomain", mappedBy="freelancer")
     */
    private $sapsubdomains;

    public function __construct()
  {
    $this->sapsubdomains = new ArrayCollection();
  }


    /**
     * @return Collection|Sapsubdomain[]
     */
    public function getSapsubdomains(): Collection
    {
        return $this->sapsubdomains;
    }

    public function addSapsubdomain(Sapsubdomain $sapsubdomain): self
    {
        if (!$this->sapsubdomains->contains($sapsubdomain)) {
            $this->sapsubdomains[] = $sapsubdomain;
            $sapsubdomain->addFreelancer($this);
        }

        return $this;
    }

    public function removeSapsubdomain(Sapsubdomain $sapsubdomain): self
    {
        if ($this->sapsubdomains->contains($sapsubdomain)) {
            $this->sapsubdomains->removeElement($sapsubdomain);
            $sapsubdomain->removeFreelancer($this);
        }

        return $this;
    }




}

"Sapsubdomain" Entity:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\SapsubdomainRepository")
 */
class Sapsubdomain
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $subdomain;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Sapdomain", inversedBy="sapsubdomains")
     * @ORM\JoinColumn(nullable=false)
     */
    private $domain;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\freelancer", inversedBy="sapsubdomains")
     */
    private $freelancer;

    public function __construct()
    {
        $this->freelancer = new ArrayCollection();
    }


    public function getId(): ?int
    {
        return $this->id;
    }

    public function getSubdomain(): ?string
    {
        return $this->subdomain;
    }

    public function setSubdomain(?string $subdomain): self
    {
        $this->subdomain = $subdomain;

        return $this;
    }

    public function getDomain(): ?sapdomain
    {
        return $this->domain;
    }

    public function setDomain(?sapdomain $domain): self
    {
        $this->domain = $domain;

        return $this;
    }

    /**
     * @return Collection|freelancer[]
     */
    public function getFreelancer(): Collection
    {
        return $this->freelancer;
    }

    public function addFreelancer(freelancer $freelancer): self
    {
        if (!$this->freelancer->contains($freelancer)) {
            $this->freelancer[] = $freelancer;
        }

        return $this;
    }

    public function removeFreelancer(freelancer $freelancer): self
    {
        if ($this->freelancer->contains($freelancer)) {
            $this->freelancer->removeElement($freelancer);
        }

        return $this;
    }

}

Form FreelancerType:

<?php

namespace App\Form;

use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;


class FreelancerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

            ->add('sapsubdomains', EntityType::class, array(
                'class' => Sapsubdomain::class,
                'choice_label' => 'subdomain',
                'required' => false,
                'multiple' => true,
                 ))

FreelancerController:

<?php

namespace App\Controller;

/**
* @Route("/freelancer", name="freelancer")
* @Security("is_granted('ROLE_FREELANCER')")
*/
class FreelancerController extends AbstractController
{
    /**
    * @Route("/settings/", name="freelancer_settings")
    */
    public function modifyfreelancesettings(Request $request, FileUploader $fileUploader)
    {
        //On récupére l'utilisateur
        $user = $this->getUser();

        //On recherche le profil freelance du user
        $freelancer = $this->getDoctrine()
        ->getRepository(Freelancer::class)
        ->findOneBy(array('Userid'=>$user));

        // Si le profil freelance n'existe pas pour le user on appel la fonction de création du profil
        if (!$freelancer) {
            $this->createfreelancesettings($request);
        }

        //Sinon on met à jour le profil du freelance
        $form = $this->createForm(FreelancerType::class, $freelancer);
        $form->handleRequest($request);

        //On des données du freelance pour éventuellement les envoyer à TWIG
        $tjm = $form->get('dailyrate')->getData();
        $curr = $form->get('ratecurrency')->getData();

        // On vérifie que le formulaire est soumis

        if ($form->isSubmitted() && $form->isValid()) {


            $freelancer->setUpdateDate(new \DateTime('now'));


            /** @var UploadedFile $pictureFile */
            $pictureFile  = $form['picture']->getData();

                if ($pictureFile ) {
                    $pictureFileName  = $fileUploader->upload($pictureFile);
                    $freelancer->setProfilePicture($pictureFileName);
                }

            //Mise à jour des relations
            $sapsubdomains  = $form['sapsubdomains']->getData();    

            $em = $this->getDoctrine()->getManager();
            $em -> flush();

            $this->addFlash('notice',
                        'Your SAP Profile has been saved !'
                        );

                            return $this->redirect($request->getUri());


        }

        return $this->render('freelancer/settings.html.twig', array(
            'picture' => $freelancer,
            'curr' => $curr,
            'freelancer'=> $form->createView(),
        ));

    }

In the template for this field I have only:

{{ form_widget(freelancer.sapsubdomains) }}

EDIT: I added this to the controller:

$subdomaintexts  = $form['sapsubdomains']->getData();

            $sapsubdomains = $this->getDoctrine()
            ->getRepository(Sapsubdomain::class)
            ->findBy(array('subdomain'=>$subdomaintexts));

            $freelancer->addSapsubdomain($sapsubdomains);

But now I have this error message:

An exception occurred while executing 'SELECT t0.id AS id_1, t0.subdomain AS subdomain_2, t0.domain_id AS domain_id_3 FROM sapsubdomain t0 WHERE t0.subdomain = ?' with params [{}]:

Object of class Doctrine\ORM\PersistentCollection could not be converted to string

1
could you show both the controller code and the template where this is rendered? the form itself and the entity look fine afaict. - Jakumi
I updated my message with controller and template. - Alex G
$form['sapsubdomains'] should contain entities and not just the labels you chose to display. it also fetches the list in there from the freelancer entity, that's why it's a PersistentCollection (Which obviously can't be converted to a string, which your query implies it to be). That being said, aside from your added code it should work, and I don't see why it doesn't. is it possible that the relation is added? how do you check? use dump($form['sapsubdomains']->getData()) to see if the form sets the entities correctly (inside the if( ... $form->isValid()) { // here }. -> check profiler! - Jakumi
if ($form->isSubmitted() && $form->isValid()) { dump($form['sapsubdomains']->getData()); There is no error in profiler but relation table sapsubdomain_freelancer is still empty. - Alex G
there shouldn't be an error, but you should look if the debug section in the profiler contains the entities you selected. - Jakumi

1 Answers

0
votes

What you are trying to do is to save collection of Sapsubdomain to your Freelancer type Entity. Right way to embed collections to forms is to use Symfony\Component\Form\Extension\Core\Type\CollectionType::class so that symfony process the colelction properly.

<?php

class FreelancerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** Other Fields **/

        $builder->add('sapsubdomains', CollectionType::class, [
            'entry_type' => SapsubdomainType::class,
            'entry_options' => ['label' => false],
             /** Other Options **/
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Freelancer::class,
        ]);
    }
}

Whole example code is found at Symfony Docs : Using Form Collections