【问题标题】:Processing of non-existent collection fields in SonataAdminBundle formsSonataAdminBundle 表单中不存在的集合字段的处理
【发布时间】:2014-08-28 20:06:31
【问题描述】:

我有一个实体类 ContactsPage 来存储有关电子邮件、电话等的一些信息。问题是将所有这些信息放入 ContactsPage 实体中定义的 json 格式的一个字段“联系人”中:

class ContactsPage
{
...
    /**
     * @var string
     *
     * @ORM\Column(name="contacts", type="text", nullable=true)
     */
    private $contacts;
...
}

ContactsPageAdmin 表单构建电子邮件示例:

protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('emails', 'collection', 
              array(
                  'mapped' => false, 
                  'required' => false,
                  'type' => 'text',
                  'allow_add' => true,
                  'allow_delete' => true,
              )
         );
}
  • 如何以及从何处获取此“电子邮件”数组(或集合)?
  • 在保存 ContactsPage 实体之前,我在哪里可以处理此数组以生成 json 并将其推送到“联系人”字段中?
  • 我可以在哪里以及如何处理“联系人”字段并将所有解码的 json 信息传输到编辑表单(进入“电子邮件”集合)?

谢谢。

【问题讨论】:

    标签: php json forms collections sonata-admin


    【解决方案1】:

    几乎花了一天,但我自己找到了答案。 第一个和第二个问题。 我必须在管理类中定义 prePersist 和 preUpdate 方法,并将我的实体作为参数,我可以在其中获取和处理“电子邮件”数组:

    class ContactsPageAdmin extends Admin
    {
    ...
        public function prePersist($contactsPage)
        {
            $emails = $this->getForm()->get('emails')->getData();
            $contactsPage->setContacts(json_encode($emails));
        }
        public function Update($contactsPage)
        {
            $emails = $this->getForm()->get('emails')->getData();
            $contactsPage->setContacts(json_encode($emails));
        }
    ...
    }
    

    第三个问题呢。我只需要使用 $this->getSubject() 来获取原始实体和“数据”属性来加载所需的数据:

    class ContactsPageAdmin extends Admin
    {
    ...
        protected function configureFormFields(FormMapper $formMapper)
            $entity = $this->getSubject();           // getting original Entity
            $json = $entity->getContacts();          // field with json data
            $array = json_decode($json, true);
    
            // preparing data to fulfill necessary form fields
            $array['emails'] = is_array($array['emails']) ? $array['emails'] : array();
    
            $formMapper
                ->add('emails', 'collection', 
                    array(
                        'mapped' => false, 
                        'required' => false,
                        'type' => 'text',
                        'allow_add' => true,
                        'allow_delete' => true,
                        'data' => $array['emails']    //  embeding prepared data into collection
                    )
                  );
        }
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      相关资源
      最近更新 更多