Use a field of other entity in form ( Symfony 5 )

I use Symfony 5 and I want to create a form. I use database connecting with doctrine. I want create a for my form and options of this select is columns in other table of database.

I have two entity:

// src/Entity/MagPosts.php

<?php

namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositoryMagPostsRepository")
 */
class MagPosts
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="text")
     */
    private $title;

    /**
     * @ORMColumn(type="string", length=4000000000)
     */
    private $content;

    /**
     * @ORMColumn(type="datetime")
     */
    private $date;

    /**
     * @ORMColumn(type="string", length=255, nullable=true)
     */
    private $status;

    /**
     * @ORMColumn(type="datetime")
     */
    private $modified;

    /**
     * @ORMColumn(type="bigint", nullable=true)
     */
    private $comment_count = 0;

    /**
     * @ORMColumn(type="string")
     */
    private $imageFilename;

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getContent(): ?string
    {
        return $this->content;
    }

    public function setContent(string $content): self
    {
        $this->content = $content;

        return $this;
    }

    public function getDate(): ?DateTimeInterface
    {
        return $this->date;
    }

    public function setDate(DateTimeInterface $date): self
    {
        $this->date = $date;

        return $this;
    }

    public function getStatus(): ?string
    {
        return $this->status;
    }

    public function setStatus(string $status): self
    {
        $this->status = $status;

        return $this;
    }

    public function getModified(): ?DateTimeInterface
    {
        return $this->modified;
    }

    public function setModified(DateTimeInterface $modified): self
    {
        $this->modified = $modified;

        return $this;
    }

    public function getCommentCount(): ?string
    {
        return $this->comment_count;
    }

    public function setCommentCount(?string $comment_count): self
    {
        $this->comment_count = $comment_count;

        return $this;
    }

    public function getImageFilename(): ?string
    {
        return $this->imageFilename;
    }

    public function setImageFilename(string $imageFilename): self
    {
        $this->imageFilename = $imageFilename;

        return $this;
    }
}

And:

// src/Entity/MagPosts.php

<?php

namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositoryMagTermTaxonomyRepository")
 */
class MagTermTaxonomy
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $name;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $taxonomy;

    /**
     * @ORMColumn(type="string", length=1000)
     */
    private $slug;

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getTaxonomy(): ?string
    {
        return $this->taxonomy;
    }

    public function setTaxonomy(string $taxonomy): self
    {
        $this->taxonomy = $taxonomy;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }
}

Now I create a form:

// src/Form/MagNewPostType.php

<?php

namespace AppForm;

use AppEntityMagPosts;
use AppEntityMagTermTaxonomy;
use DoctrineORMEntityRepository;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypeFileType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeTextareaType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsFile;

class MagNewPostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                'label' => false
            ])
            ->add('imageFile', FileType::class, [
                'label' => false,
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'image/jpeg',
                            'image/png',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid image file',
                    ])
                ],
            ])
            ->add('content', TextareaType::class, [
                'label' => false
            ])
            ->add('name', EntityType::class, [
                'class' => MagTermTaxonomy::class,
                'query_builder' => function(EntityRepository $entityRepository){
                    return $entityRepository->createQueryBuilder('u')
                    ->orderBy('u.name', 'ASC');
                },
                'mapped' => false
            ])
            ->add('slug', EntityType::class, [
                'class' => MagTermTaxonomy::class,
                'query_builder' => function(EntityRepository $entityRepository){
                    return $entityRepository->createQueryBuilder('u')
                    ->orderBy('u.slug', 'ASC');
                },
                'mapped' => false
            ])
            ->add('tags', TextType::class, [
                'mapped' => false
            ])
            ->add('status', CheckboxType::class, [
                'label' => 'Status',
                'required' => false
            ])
            ->add('save', SubmitType::class, ['label' => 'save'])
        ;
    }

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

And my controller is:

/**
 * @Route("/newPost", name="new_post")
 */
public function magNew(EntityManagerInterface $entityManager, Request $request)
{
    $magPosts = new MagPosts();
    $form = $this->createForm(MagNewPostType::class, $magPosts);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()){
        $magPosts = $form->getData();
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($magPosts);
        $entityManager->flush();
        return $this->redirectToRoute('home_page');
    }
    return $this->render('post/newpost.html.twig', [
        'newPostForm' => $form->createView()
    ]);
}

Now when I go to new post page, this error display:

Catchable Fatal Error: Object of class AppEntityMagTermTaxonomy
could not be converted to string

How can I fix this problem?

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *