skip to Main Content

I am trying to render form of Team entity which is attached to User with ManyToOne relationship. See below Entity Class:

<?php

namespace AppEntity;

class Team
{
    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn]
    private ?int $id = null;

    #[ORMManyToOne(inversedBy: 'teams')]
    #[ORMJoinColumn(nullable: false)]
    private ?User $owner = null;
...

Below is User entity class code:

<?php

namespace AppEntity;

Class User {

    #[ORMOneToMany(mappedBy: 'owner', targetEntity: Team::class)]
    private Collection $teams;
....

Here is the controller class code where I am rending form view:

<?php

namespace AppController;

class TeamController extends AbstractController
{
    #[Route('/new', name: 'app_team_new', methods: ['GET', 'POST'])]
    public function new(Request $request, TeamRepository $teamRepository): Response
    {
        $team = new Team();
        $form = $this->createForm(TeamType::class, $team);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $teamRepository->save($team, true);

            return $this->redirectToRoute('app_team_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('team/new.html.twig', [
            'team' => $team,
            'form' => $form,
        ]);
    }
...

And here is the TeamType form class

<?php

namespace AppForm;


class TeamType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name')
            ->add('intro')
            ->add('country')
            ->add('balance')
            ->add('created_at')
            ->add('updated_at')
            ->add('owner')
        ;
    }

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

And lastly, the team/new.html.twig

{% extends 'layouts/base.html.twig' %}

{% block title %}
    New Team
{% endblock %}

{% block body %}
    <main class="container form-signin w-100 m-auto">
        <h1>Add Team</h1>

        {{ form_start(form) }}
        {{ form_widget(form) }}
        <button class="btn">{{ button_label|default('Save') }}</button>
        {{ form_end(form) }}


        <a href="{{ path('app_team_index') }}" class="btn btn-link bi bi-arrow-left text-decoration-none">
            &nbsp; Back to all teams</a>
    </main>
{% endblock %}

I am getting an error that Object of class AppEntityUser could not be converted to string exactly near the line 'form' => $form,.

What could be a possible issue?

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution. If you want to use an entity as a form field, you need to specify the class and the choice_label options in your form type. The class option tells Symfony which entity class to use for the field, and the choice_label option tells Symfony which property or method to use as the label for each choice. To fix this, you need to configure your form type for the User field like this:

    <?php
    
    namespace AppForm;
    
    use AppEntityTeam;
    use AppEntityUser;
    use SymfonyComponentFormAbstractType;
    use SymfonyComponentFormFormBuilderInterface;
    use SymfonyComponentOptionsResolverOptionsResolver;
    use SymfonyBridgeDoctrineFormTypeEntityType;
    
    
    class TeamType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options): void
        {
            $builder
                ->add('name')
                ->add('intro')
                ->add('country')
                ->add('balance')
                ->add('created_at')
                ->add('updated_at')
                ->add('owner', EntityType::class, [
                    'class' => User::class,
                    'choice_label' => 'full_name', // or any other property or method that returns a string
                ]);
            ;
        }
    ...
    

    Hope this help someone.


  2. When doctrine tries to display relationships, in your case the Team and User classes. depending on the side of the relationship, doctrine tries to convert these classes to a string, in order to display select with option choice value in html form. You should be to implement __toString methods

    class User
    {
      //...
      public function __toString()
      {
        return (string) $this->getUserIdentifier();
      }
    }
    
    class Team
    {
      //...
      public function __toString()
      {
        return (string) $this->name;
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search