我只是想在下面的未映射字段中添加一个电子邮件约束,并且由于某种原因,在控制器操作中它没有提取它。我还需要做些什么吗?
表格类
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name', null, [
'label' => false,
'attr' => ['placeholder' => 'Name*']
]);
$builder->add('email', null, [
'mapped' => false,
'label' => false,
'attr' => ['placeholder' => 'Email*'],
'constraints' => [
new Email(["message" => "Please enter a valid Email Address"])
]
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Test\AppBundle\Entity\Feedback',
'cascade_validation' => true,
'validation_groups' => function(Form $form)
{
$feedback = $form->getData(); /** @var Feedback $feedback */
if ($feedback->getType() == Feedback::Type_Feedback)
return Feedback::ValidationGroup_Feedback;
else if ($feedback->getType() == Feedback::Type_Link)
return Feedback::ValidationGroup_Link;
throw new \Exception("Couldn't generate a valid Validation Group for FeedbackForm.php");
},
));
}
/**
* @return string
*/
public function getName()
{
return 'site_feedback_form';
}
控制器操作
public function feedbackSiteSubmitAction(Request $request)
{
// The form award
$feedback = new Feedback();
// Create the form so we can bind send form values to it
$form = $this->createNewFeedbackForm($feedback);
// Bind form values
$form->handleRequest($request);
// Save
if ($form->isValid())
{
// Add the submission to a member
$email = $form->get('email')->getData();
$email = strtolower($email);
$member = $this->getMemberRepository()->loadByEmail($email);
if (!$member)
$member = $this->generateNewPersistedMember($email);
// Update the mail property
$member->setReceiveEmail(!$form->get('dontReceiveAlerts')->getData());
// Add the feedback to the member
$feedback->setMember($member);
// Persist the Feedback
$this->getEntityManager()->persist($feedback);
// Commit
$this->getEntityManager()->flush();
// Response
return $this->jsonSuccess([
'html' => $this->renderView('TestAppBundle:Site/partials:feedback_form_success.html.twig', [
'typeString' => $feedback->getType() == Feedback::Type_Feedback ? "Feedback" : "Resource suggestion"
])
]);
}
// Return errors
return $this->jsonError($this->getAllFormErrors($form));
}
答案 0 :(得分:-1)
在Symfony 2.8中,您可以执行以下操作:
$builder->add('email', Symfony\Component\Form\Extension\Core\Type\EmailType::class);
使用之前的版本:
$builder->add('email', 'email');
然后,通过Feedback
课程中的注释添加所有验证条件。请参阅EmailType
here的选项。