我是 Symfony2 的新手,无法弄清楚为什么会出现此错误。也许我的实体有问题?所以我需要一些帮助。一个错误:
EntityManager#persist() expects parameter 1 to be an entity object, array given.
500 Internal Server Error - ORMInvalidArgumentException
我有以下代码:
用户.php:
<?php
namespace Acme\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*/
class User
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $username;
/**
* @var string
*/
private $password;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
* @return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* @param string $password
* @return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
}
用户注册类型.php
<?php
namespace Acme\MainBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Length;
class UserRegType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('username', 'text', array(
'constraints'=>new Length(array('min' => 3))
));
$builder->add('password', 'repeated', array(
'first_name' => 'password',
'second_name' => 'confirm',
'type' => 'password',
'constraints' => new Length(array('min' => 5, 'max' => 8))
));
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Acme\MainBundle\Entity\User');
}
public function getName() {
return 'user';
}
}
?>
用户控制器.php:
<?php
namespace Acme\MainBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Acme\MainBundle\Form\Type\UserRegType;
class UserController extends Controller
{
public function registerAction()
{
$form = $this->createForm(new UserRegType());
return $this->render(
'AcmeMainBundle:User:register.html.twig',
array('form' => $form->createView())
);
}
public function createUserAction()
{
$em = $this->getDoctrine()->getEntityManager();
$form = $this->createForm(new UserRegType());
$form->bind($this->getRequest());
$username = $form["username"]->getData();
if ($form->isValid()) {
$reg = $form->getData();
$em->persist($reg);
$em->flush();
$session = $this->get('session');
$session->set('username', $username);
return $this->redirect($this->generateUrl('home'));
}
}
public function loginAction()
{
}
public function logoutAction()
{
}
}