【发布时间】:2018-04-26 10:40:46
【问题描述】:
我正在使用 Symfony 3.3,当我加载我的个人资料页面时,我收到了这个 TransformationFailedException 错误:
无法转换属性路径“邮政编码”的值:应为数字。
该用户在数据库中的邮政编码值为:
'34125abc'
UserProfile 实体中定义的邮政编码属性:
/**
* @ORM\Column(type="string")
*/
private $postalcode;
我的个人资料控制器:
class ProfileController extends Controller{
/**
* @Route("/edit_profile", name="edit_profile")
*/
public function profileAction(Request $request){
$profile = $this->getDoctrine()->getManager()->getRepository('AppBundle:UserProfile')->findOneBy(['user_id' => $this->getUser()->getUserId()]);
// If no UserProfile exists, create a UserProfile Object to insert it into database after POST
if(null === $profile){
$profile = new UserProfile();
$profile->setUserId($this->getUser()->getUserId());
}
$form = $this->createForm(EditProfileFormType::class);
$form->setData($profile);
// only handles data on POST
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$result = $this->forward('AppBundle:API\User\Profile:update_profile', array(
'profile' => $profile
));
if(200 === $result->getStatusCode()){
$this->addFlash('success', "Profile successfully created!");
}
}
return $this->render(':User/Profile:edit_profile.html.twig', [
'EditProfileForm' => $form->createView(),
]);
}
}
我的 EditProfileFormType:
class EditProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', ChoiceType::class, array(
'choices' => array(
'Mr' => 'Mr',
'Mrs' => 'Mrs'
)
))
->add('firstName')
->add('lastName')
->add('street')
->add('postalcode', NumberType::class)
->add('city')
->add('telephone')
->add('mobile')
->add('company')
->add('birthday' , BirthdayType::class)
->add('callback', CheckboxType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\UserProfile',
'validation_groups' => array('edit_profile')
]);
}
public function getBlockPrefix()
{
return 'app_bundle_edit_profile_form_type';
}
}
所以这里的问题似乎是数据库中的非数字字符串值
'34125abc'
它存储在$profile实体对象中,由$form->setData($profile);传递给表单所以在设置数据时,由于->add('postalcode', NumberType::class)这一行中的Numbertype而抛出错误。有没有办法在提交表单时将邮政编码值传递给表单,即使它不是数字并且只检查 Numbertype ?因为我不需要验证,所以当我将数据传递给表单时。就在什么时候,它被提交了。
【问题讨论】:
-
您可以在控制器中验证邮政编码,并从表单类型类中删除限制。
-
我必须验证每个控制器中的所有表单字段。那不值得。难道没有别的办法了吗?我想在模型而不是表单中进行限制。但是我得到了同样的错误。在这样的模型中:
/** * @ORM\Column(type="string") * @Assert\Type( * type="numeric", * groups={"edit_profile"} * ) */ private $postalcode;
标签: php forms symfony validation entity