首页 > 解决方案 > 生成动态表单以显示在管理视图中

问题描述

我在一个组件上,我希望用户将自己的字段添加为另一条记录的选项。

例如,我有一个视图产品 (administrator/components/com_myproducts/views/product/...)。此视图将获得其标题、别名和表单描述 (administrator/components/com_myproducts/models/forms/product.xml)。表单 xml 是静态的,但我希望用户自己添加产品属性。

所以我添加了另一个视图属性,用户可以在其中添加带有名称和字段类型的记录。

现在我希望将这些属性添加到产品表单中。所以它基本上是从数据库中获取属性,加载表单 XML,将属性附加到 XML 并将修改后的 XML 提供给 JForm 对象以在产品模型 getForm() 中返回它。

在 Product 模型中,这看起来像这样:


    public function getForm($data = array(), $loadData = true)
    {
        // Get the form.
        $form = $this->loadForm(
            'com_myproducts.product',
            'product',
            array(
                'control' => 'jform',
                'load_data' => $loadData
            )
        );

        $xml = $form->getXML();
        $attributes = $this->getAttributes();

        $newForm = Helper::manipulateFormXML($xml, $attributes);

        /*
         * load manipulated xml into form
         * don't know what to do here
         */

        ...

        if (empty($form)) {
            return false;
        }

        return $form;
    }

如何使用修改后的 xml 更新表单,还是应该以另一种方式处理?

标签: phpjoomlajoomla3.9

解决方案


通过创建表单的新实例,我找到了解决该问题的方法。

    public function getForm($data = array(), $loadData = true)
    {
        // Get the form.
        $tmp = $this->loadForm(
            'com_myproducts.tmp',
            'product',
            array(
                'control' => 'jform',
                'load_data' => $loadData
            )
        );

        $xml = $tmp->getXML();
        $attributes = $this->getAttributes();

        $newXml = Helper::manipulateFormXML($xml, $attributes);

        // Get the form.
        $form = $this->loadForm(
            'com_myproducts.product',
            $newXml->asXML(),
            array(
                'control' => 'jform',
                'load_data' => $loadData
            )
        );

        if (empty($form)) {
            return false;
        }

        return $form;
    }

我对这个解决方案不满意,但它可以满足我的需求。


推荐阅读