Symfony 3.3加载个人资料页时出现TransformationFailedException异常
解决Symfony 3.3中Profile页面的TransformationFailedException错误
咱们来拆解下你遇到的问题:你看到的TransformationFailedException提示“Expected a numeric”,但你的UserProfile实体里postalcode明明定义的是string类型,数据库里存的还是带字母的34125abc,这矛盾点其实出在表单类型的配置上。
问题根源
大概率是你在构建个人资料的表单时,把postalcode字段的表单类型设置成了NumberType或者IntegerType——但实体属性是字符串,且数据库里的值包含非数字字符,Symfony表单在加载数据时会尝试把字符串转换成数字,自然就触发转换失败的异常了。
解决方案
修改你的表单配置(不管是独立的表单类还是控制器里的表单构建代码),把postalcode的表单类型改成TextType,这样就能兼容包含字母的邮政编码了:
如果是用独立表单类:
use Symfony\Component\Form\Extension\Core\Type\TextType; // ... $builder->add('postalcode', TextType::class, [ 'label' => 'Postal Code', // 其他你需要的配置项 ]);
如果是直接在ProfileController里构建表单:
// 控制器内的表单构建部分 $form = $this->createFormBuilder($userProfile) ->add('postalcode', TextType::class) // 其他字段配置 ->getForm();
额外优化建议
如果后续需要对邮政编码做格式限制(比如只允许字母数字组合),可以给实体属性添加验证注解,避免不符合要求的值存入数据库:
// 在UserProfile实体的postalcode属性上添加 use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Column(type="string") * @Assert\Regex( * pattern="/^[0-9a-zA-Z]+$/", * message="Postal code can only contain letters and numbers." * ) */ private $postalcode;
内容的提问来源于stack exchange,提问作者MagicKnife
相关产品推荐
相关产品推荐

