Symfony-关联字段的“实体”类型的期望值改为“字符串”

时间:2019-07-11 09:18:51

标签: symfony symfony4

我有一个 UserEntity ,其中包含用户的电子邮件地址和密码。然后,一个 UserInstanceEntity 包含用户的电话号码以及 PreferredContactEntity 上的ManyToOne关系,该关系允许用户选择自己喜欢的联系方式。

我希望当用户更改个人资料时,他也可以修改他的电话号码和首选的联系方式。因此,在控制器中,我插入了 UserType UserInstanceType

当我发送表格时,出现错误:

  

关联的类型为“ App \ Entity \ PreferredContact”的期望值   字段“ App \ Entity \ UserInstance#$ preferredContact”中,获得了“字符串”   代替。

UserEntity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Validator\Constraints as AssertPerso;
use DateTime;
use DateTimeInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="app_user")
 * @ORM\HasLifecycleCallbacks()
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @AssertPerso\Email
     */
    private $email;

    /**
     * @ORM\Column(type="array")
     */
    private $roles = [];

    /**
     * @var string plain password
     */
    private $plainPassword;

    /**
     * @ORM\Column(type="boolean")
     */
    private $enabled;

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;
...

UserInstanceEntity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserInstanceRepository")
 * @ORM\Table(name="app_user_instance")
 */
class UserInstance
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    /**
     * @var string
     *
     * @ORM\Column(type="string")
     */
    private $contactNumber;

    /**
     * @var string
     *
     * @ORM\Column(type="string", nullable=true)
     */
    private $directContactNumber;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\PreferredContact")
     * @ORM\JoinColumn(nullable=false)
     */
    private $preferredContact;

PreferredContactEntity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PreferredContactRepository")
 * @ORM\Table(name="app_user_preferred_contact")
 */
class PreferredContact
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $contact;

表PreferredContact:

id    contact
1      Mail
2      Phone
3      Webex Teams

UserController:

public function editProfil(Request $request): Response
{
    $user = $this->getUser();
    $userInstance = new UserInstance();

    $form = $this->createForm(EditProfilType::class, $user);
    $formUserInstance = $this->createForm(UserInstanceType::class, $userInstance);

    $form->handleRequest($request);
    $formUserInstance->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid() && $formUserInstance->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($userInstance);
        $entityManager->flush();

        $this->addFlash('success', 'Informations mises à jour avec succès !');

        return $this->redirectToRoute('user_editprofil');
    }

    return $this->render($this->ticketingTemplates['edit_profil'], [
        'user' => $user,
        'form' => $form->createView(),
        'formUserInstance' => $formUserInstance->createView(),
    ]);
}

UserType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
        $builder
            ->add('email', null, array(
                    'label'    => 'Email',
                    'required' => true)
            )
            ->add('plainPassword',PasswordType::class,  array(
                    'label'    => 'Mot de passe',
                    'required' => true,
                    'constraints' => [
                        new Length([
                            'min' => 6,
                            'minMessage' => '{{ limit }} caractères minimum',
                            'max' => 4096,
                        ]),
                    ],
                    )
            )
            ->add('roles', RolesType::class);

UserInstanceType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

         ->add('contactNumber', null, array(
             'label'    => 'Numéro de téléphone portable',
             'required' => true,
         ))

        ->add('directContactNumber', null, array(
            'label'    => 'Numéro de ligne direct'), [
            'required'   => false,
            'help'     => 'Facultatif',
        ])

       ->add('preferredContact', EntityType::class, [
           'class' => PreferredContact::class,
           'label' => 'Méthode de contact préférée',
       ]);

editprofil.html.twig:

<form method="post" >
    <fieldset>
        <legend><i class="fa fa-lock" aria-hidden="true"></i> {{ 'Votre compte' }}</legend>
        {{ form_start(form) }}
        {{ form_widget(form) }}
        {{ form_start(formUserInstance) }}
        {{ form_widget(formUserInstance) }}
        {{ form_end(formUserInstance) }}
        <button type="submit" class="btn btn-primary">
            <i class="fa fa-save" aria-hidden="true"></i> {{ 'Enregistrer' }}
        </button>
        <a href="{{ path('user_change_password') }}" class="btn btn-danger">
            <i class="fa fa-lock" aria-hidden="true"></i> {{ 'Modifier le mot de passe' }}
        </a>
        {{ form_end(form) }}

    </fieldset>
</form>

您知道此错误来自何处吗?谢谢


编辑:

EditProfilType:

class EditProfilType extends AbstractType
{
    private $securityChecker;
    private $token;

    public function __construct(AuthorizationCheckerInterface $securityChecker, TokenStorageInterface $token)
    {
        $this->securityChecker = $securityChecker;
        $this->token = $token;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
            $builder
                ->add('email', null, array(
                        'label'    => 'Email  ',
                        'required' => true
                    )
                )
                ->add('firstName', null, array(
                        'label'    => 'Prénom',
                        'required' => true)
                )
                ->add('lastName', null, array(
                        'label'    => 'Nom',
                        'required' => true)
                );

    }

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

0 个答案:

没有答案