我有一个名为User的实体和注册新用户的表单。我遇到的问题是我的实体在其构造函数中有参数,因此我无法实例化一个没有数据的新空用户并将其传递给控制器中的表单构建器。当我在表单上使用默认选项时,我会收到错误消息
警告:缺少用户\ User :: __ construct()的参数1,在/mnt/project/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/Type/FormType.php中调用136并定义
我不想允许在没有电子邮件或名称等强制性内容的情况下构建User对象。这里有什么解决方案?
表格:
class UserRegisterForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', TextType::class)
->add('password', PasswordType::class)
->add('firstName', TextType::class)
->add('lastName', TextType::class)
->add('save', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => User::class
));
}
}
我的实体:
/**
* @ORM\Entity
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
* @Assert\Email(
* message = "The email '{{ value }}' is not a valid email.",
* checkMX = true
* )
*/
protected $email;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
* @Assert\Length(min=3)
*/
protected $password;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
*/
protected $firstName;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
*/
protected $lastName;
public function __construct($email, $firstName, $lastName)
{
$this->email = $email;
$this->firstName = $firstName;
$this->lastName = $lastName;
}
}
和控制器
public function registerView(Request $request)
{
$form = $this->formFactory
->createBuilder(UserRegisterForm::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
die("Valid form, the user entity is going to be saved here");
}
return $this->render("User/register.html.twig", ["form" => $form->createView()]);
}
更新 找到了这个 - Symfony2 Forms - How to use parametrized constructors in form builders。但它并没有解决问题,因为我不想将任何虚拟数据传递给构造函数。不将对象传递给表单构建器会导致它自动绕过整个验证。