dpjpo746884 2014-11-23 19:23
浏览 19
已采纳

如何从ZF2中的现有元素实例中提取工厂友好的表单元素配置数组?

I have a Zend\Form\Element instance and I need to extract all configuration as array from this instance, serialize & persist somewhere and re-use later in a form element factory to generate a similar instance again.

Is there any programatic way exists to get full configuration signature from an already instantiated form element object in zend framework 2?

  • 写回答

1条回答 默认 最新

  • dongtan2017 2014-11-23 23:53
    关注

    The short answer is no; you will have to roll your own.

    You could create a independent class that can take any element and return the correct array by reading it's public methods; this is effectively reversing the functionality of the FormFactory.

    A very brief example

    class FormElementSerializer
    {
        public function toArray(ElementInterface $element)
        {
            $spec = $this->getElementSpec($element);
    
            if ($element instanceof FieldsetInterface) {
                $spec = $this->getFieldsetSpec($element, $spec);
            }
    
            if ($element instanceof Form) {
                $spec = $this->getFormSpec($element, $spec);
            }
    
            return $spec;
        }
    
        protected function getElementSpec(ElementInterface $element)
        {
            $spec = array(
                'type' => $this->getElementType($element),
                'name' => $element->getName(),
                'options' => $element->getOptions(),
                'attributes' => $element->getAttributes(),
            );
            return $spec;
        }
    
        protected function getFieldsetSpec(FieldsetInterface $fieldset, array $spec)
        {
            foreach($fieldset->getElements() as $element) {
                $spec['elements'][] = $this->getElementSpec($element);
            }
            return $spec;
        }
    
        // deals with hydrators, fieldsets etc
        protected function getFormSpec(FormInterface $form, array $spec);
    
        // could be as simple as returning the class name
        protected function getElementType(ElementInterface $element);
    } 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起