dphdh395195 2015-11-11 13:06
浏览 28
已采纳

Symfony 2将数据持久化到具有关系的一个表

I'm trying to save a record in the database after submitting a form with valid data but I´m getting the next error:

Expected value of type "AppBundle\Entity\Gender" for association field "AppBundle\Entity\Usuario#$gender", got "string" instead.

I want to save a record in Usuario table but I don´t understand why it doesn't work like this.

My entities are:

Usuario.php

<?php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;

/**
* @ORM\Entity
* @ORM\Table(name="usuario")
*/
class Usuario implements UserInterface, \Serializable
{
/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(name="name", type="string")
 * @Assert\NotBlank()
 */
protected $name;

/**
 * @ORM\Column(name="lastName", type="string")
 * @Assert\NotBlank()
 */
protected $lastName;

/**
 * @ORM\Column(name="email", type="string", unique=true)
 * @Assert\Email()
 * @Assert\NotBlank()
 */
protected $email;

/**
 * @ORM\Column(name="password", type="string")
 * @Assert\NotBlank()
 */
protected $password;

/**
 * @ORM\Column(name="playingLevel", type="integer")
 * @Assert\NotBlank(message = "Choose a valid level.")
 */
protected $playingLevel;

/**
 * @ORM\ManyToOne(targetEntity="Gender", inversedBy="users")
 * @ORM\JoinColumn(name="gender", referencedColumnName="code")
 * @Assert\NotBlank(message = "Choose a valid gender.")
 */
protected $gender;

/**
 * @ORM\ManyToOne(targetEntity="Country", inversedBy="users")
 * @ORM\JoinColumn(name="country", referencedColumnName="code")
 * 
 * @Assert\Country()
 */
protected $country;

/**
 * @ORM\Column(name="city", type="string")
 * @Assert\NotBlank()
 */
protected $city;

/**
 * @ORM\Column(name="status", type="string")
 */
 protected $status;

public function getUserName()
{
    return $this->email;
}

public function getSalt()
{
    return null;
}

public function getRoles()
{
    return array('ROLE_USER');
}

public function eraseCredentials()
{

}

public function serialize()
{
    return serialize(array(
        $this->id,
        $this->email,
        $this->password,
        //$this->salt
    ));
}

public function unserialize($serialized)
{
    list(
        $this->id,
        $this->email,
        $this->password,
        //$this->salt
    )= unserialize($serialized);
}

/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return Usuario
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Set lastName
 *
 * @param string $lastName
 *
 * @return Usuario
 */
public function setLastName($lastName)
{
    $this->lastName = $lastName;

    return $this;
}

/**
 * Get lastName
 *
 * @return string
 */
public function getLastName()
{
    return $this->lastName;
}

/**
 * Set email
 *
 * @param string $email
 *
 * @return Usuario
 */
public function setEmail($email)
{
    $this->email = $email;

    return $this;
}

/**
 * Get email
 *
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * Set password
 *
 * @param string $password
 *
 * @return Usuario
 */
public function setPassword($password)
{
    $this->password = $password;

    return $this;
}

/**
 * Get password
 *
 * @return string
 */
public function getPassword()
{
    return $this->password;
}

/**
 * Set playingLevel
 *
 * @param integer $playingLevel
 *
 * @return Usuario
 */
public function setPlayingLevel($playingLevel)
{
    $this->playingLevel = $playingLevel;

    return $this;
}

/**
 * Get playingLevel
 *
 * @return integer
 */
public function getPlayingLevel()
{
    return $this->playingLevel;
}

/**
 * Set gender
 *
 * @param string $gender
 *
 * @return Usuario
 */
public function setGender($gender)
{
    $this->gender = $gender;

    return $this;
}

/**
 * Get gender
 *
 * @return string
 */
public function getGender()
{
    return $this->gender;
}

/**
 * Set country
 *
 * @param string $country
 *
 * @return Usuario
 */
public function setCountry($country)
{
    $this->country = $country;

    return $this;
}

/**
 * Get country
 *
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

/**
 * Set city
 *
 * @param string $city
 *
 * @return Usuario
 */
public function setCity($city)
{
    $this->city = $city;

    return $this;
}

/**
 * Get city
 *
 * @return string
 */
public function getCity()
{
    return $this->city;
}

/**
 * Set status
 *
 * @param string $status
 *
 * @return Usuario
 */
public function setStatus($status)
{
    $this->status = $status;

    return $this;
}

/**
 * Get status
 *
 * @return string
 */
public function getStatus()
{
    return $this->status;
}
}

Gender.php

<?php  
namespace AppBundle\Entity;

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

/**
* @ORM\Entity
*/

class Gender
{

/**
* @ORM\Id
* @ORM\Column(type="string")
*/
private $code;

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

/**
* @ORM\OneToMany(targetEntity="Usuario", mappedBy="gender")
*/
private $users;

/**
 * Constructor
 */
public function __construct()
{
    $this->users = new \Doctrine\Common\Collections\ArrayCollection();
}

/**
 * Set code
 *
 * @param string $code
 *
 * @return Gender
 */
public function setCode($code)
{
    $this->code = $code;

    return $this;
}

/**
 * Get code
 *
 * @return string
 */
public function getCode()
{
    return $this->code;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return Gender
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

/**
 * Add user
 *
 * @param \AppBundle\Entity\Usuario $user
 *
 * @return Gender
 */
public function addUser(\AppBundle\Entity\Usuario $user)
{
    $this->users[] = $user;

    return $this;
}

/**
 * Remove user
 *
 * @param \AppBundle\Entity\Usuario $user
 */
public function removeUser(\AppBundle\Entity\Usuario $user)
{
    $this->users->removeElement($user);
}

/**
 * Get users
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getUsers()
{
    return $this->users;
}
}

Country.php

<?php  
namespace AppBundle\Entity;

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

/**
* @ORM\Entity
*/

class Country
{
/**
* @ORM\Column(type="string")
* @ORM\Id
*/
protected $code;

/**
* @ORM\Column(name="name", type="string")
*/
protected $name;

/**
* @ORM\OneToMany(targetEntity="Usuario", mappedBy="country")
*/
protected $users;

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

/**
 * Set code
 *
 * @param string $code
 *
 * @return Country
 */
public function setCode($code)
{
    $this->code = $code;

    return $this;
}

/**
 * Get code
 *
 * @return string
 */
public function getCode()
{
    return $this->code;
}

/**
 * Set name
 *
 * @param string $name
 *
 * @return Country
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}


/**
 * Add user
 *
 * @param \AppBundle\Entity\Usuario $user
 *
 * @return Country
 */
public function addUser(\AppBundle\Entity\Usuario $user)
{
    $this->users[] = $user;

    return $this;
}

/**
 * Remove user
 *
 * @param \AppBundle\Entity\Usuario $user
 */
public function removeUser(\AppBundle\Entity\Usuario $user)
{
    $this->users->removeElement($user);
}

/**
 * Get users
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getUsers()
{
    return $this->users;
}
}

And the controller in my UserController.php

public function playerSignUpAction(Request $request)
{
    $user = new Usuario();
    //$gender = new Gender();



    $form = $this->createForm(new UsuarioSignUpType(), $user);

    $form->handleRequest($request);

    if($form->isValid())
    {
        //Encoding User Password
        $plainPassword = $request->request->get('UsuarioSignUp')['password'];
        $encoder = $this->container->get('security.password_encoder');
        $encoded = $encoder->encodePassword($user, $plainPassword);

        $user->setPassword($encoded);
        $user->setStatus("ROLE_USER");
        //$user->setGender($gender);

        try {
            //Saving User in the DataBase
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            $this->addFlash(
                'notice',
                'Well done! you completed your registration correctly. Welcome to Squash Connection!'
                );

            return $this->render('default/submitted_registration.html.twig');

        } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
            $this->addFlash(
                'error',
                'Something went wrong! It seems that someone is already using that email.'
                );

            return $this->render('default/submitted_registration.html.twig');

        }


    }

    return $this->render('user/user_registration.html.twig', array('form' => $form->createView(), 'request' => $request));
}

My UsuarioSingUpType.php

<?php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;

class UsuarioSignUpType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', 'text')
        ->add('lastName', 'text')
        ->add('email', 'email')
        ->add('password', 'password')
        ->add('playingLevel', 'rating', array(
            'label' => 'Playing Level',
            'stars' => 5))
        ->add('gender', 'choice', array(
            'choices' => array('m' => 'Male', 'f' => 'Female'), 
            'expanded' => 'true',
            ))
        ->add('country', 'country')
    ;



    $builder
        ->add('city', 'text')
        ->add('send', 'submit') 
    ;

}

public function getName()
{
    return 'UsuarioSignUp';
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Usuario'
    ));
}
}
?>
  • 写回答

1条回答 默认 最新

  • doukongpao0903 2015-11-11 13:20
    关注

    What is the code of your UsuarioSignUpType class. Did you define your gender field to use your Gender entity ?

    If not you should do something like this

    $builder->add(
      'gender',
      'entity',
      array(
      'class' => 'AppBundle:Gender',
      'property' => 'name',
      'empty_value' => 'Choose your gender'
      )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀