duanhuo0577 2016-10-09 20:16
浏览 129
已采纳

Symfony2 Forms&Doctrine:将带有多个地址的EmailType保存到simple_array中

It looks like there is no direct way to save the outcome of <input type="email" multiple> into Doctrine's simple_array field, through Symfony 2 forms.

Details:

Now, when I enter two email addresses in the form (comma-separated, as expected by HTML5), the entity receives a comma-separated string.

However, when persisting into the simple_array field, Doctrine expects an array, onto which it calls implode().

So the error message I get is: Warning: implode(): Invalid arguments passed

Reason: Symfony doesn't explode the comma-separated string into an array, before handing it over to Doctrine.

Solution: Do it manually:
$entity->setEmails(explode(',', $entity->getEmails()));

So finally my question is: Is there an easier way for this?

  • 写回答

3条回答 默认 最新

  • doushi3454 2016-10-10 11:44
    关注

    After the answers of @Max P. and @jeremy:

    Both methods work in principle! However, they break validation (see comments).

    So here's what I finally came up with to enable validation:

    Following http://symfony.com/doc/current/validation/custom_constraint.html

    // src/AppBundle/Validator/Constraints/Array255Validator.php 
    class Array255Validator extends ConstraintValidator
    {
        public function validate($value, Constraint $constraint)
        {
            $string = implode(',', $value);
            if (strlen($string) > 255) {
                $this->context->buildViolation($constraint->message)
                    ->setParameter('%string%', $string) // use $string here, since $value is an array!
                    ->addViolation();
            }
        }
    }
    

    You can even apply validation to each array element, by using the All constraint: http://symfony.com/doc/current/reference/constraints/All.html

    properties:
        email:
            - AppBundle\Validator\Constraints\Array255: ~
            - All:
                - NotBlank:  ~
                - Length:
                    min: 5
                - Email:
                    checkMX: true
                    message: "Some message for {{ value }}"
    

    Thanks!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?