Home » Php » php – generating dynamic form to display in the admin view

php – generating dynamic form to display in the admin view

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am on a component where I want the user add their own fields as options for another record.

For example I have a view Product (administrator/components/com_myproducts/views/product/…). This view will get their title, alias and description of its form (administrator/components/com_myproducts/models/forms/product.xml). The form xml is static but I want users to add product attributes by themselves.

So I am adding another view Attributes where users can add records with a name and a field type.

Now I want these attributes to be added to the Product form. So it is basically fetching the Attributes from the database, loading the form XML, appending the attributes to the XML and feeding the modified XML to a JForm object to return it in the Product models getForm().

In the Product model this would look something like this:


    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;
    }

How can I update the form with the modified xml or should I approach this another way?

How to&Answers:

I kind of found a workaround for the problem by creating a new instance of the form.

    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;
    }

I am not satisfied with this solution but it does what I want.