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

时间:2015-11-11 13:06:51

标签: php symfony doctrine-orm symfony-forms

我在提交包含有效数据的表单后尝试在数据库中保存记录,但我收到了下一个错误:

  

关联字段“AppBundle \ Entity \ Usuario#$ gender”类型“AppBundle \ Entity \ Gender”的预期值,取而代之的是“string”。

我想在Usuario表中保存一条记录,但我不明白为什么它不能像这样工作。

我的实体是:

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;
}
}

我的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));
}

我的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 个答案:

答案 0 :(得分:2)

UsuarioSignUpType类的代码是什么。您是否定义了性别字段以使用您的性别实体?

如果不是,你应该做这样的事情

$builder->add(
  'gender',
  'entity',
  array(
  'class' => 'AppBundle:Gender',
  'property' => 'name',
  'empty_value' => 'Choose your gender'
  )