0

I need to create a custom form which generates an input / text field foreach position that is stored in the database. My Code for this field so far:

    private function buildSubForm(array $positions)
    {
        // Create a new form instance.
        // Instanz des Form-Objekts erstellen
        $form = new JForm('gameofficials');

        // Build the Form fields based on the positions
        foreach ($positions as $position)
        {
            // Create a new field instance
            $xml = new SimpleXMLElement('<field name="position-'.$position->id.'" type="text" label="'.$position->title.'" />');
            // Add the field to the form
            $form->setField($xml, $group = null, $replace = true, $fieldset = 'default');
        }

        return ''; // will be replaced by the form
    }

So far it's quite simple but i'm getting again and again the following error:

Error: Joomla\CMS\Form\Form::Joomla\CMS\Form\Form::setField xml is not an instance of SimpleXMLElement

I've checked my code against https://docs.joomla.org/Advanced_form_guide aswell as https://www.techfry.com/joomla/working-with-joomla-forms-using-jform-class

I've also tried to simply insert an empty xml as start and add then the fields which didn't work either.

2 Answers 2

1

Unfortunately the Joomla error message is a bit misleading here. It's not complaining about your $xml element passed in, but rather than the basic <form> structure hasn't been initialised properly (which it stores in an instance variable called "xml"). You need to do this before you start adding fields to it.

To do this add the line below:

$form = new JForm('gameofficials');
$form->load('<?xml version="1.0" encoding="utf-8"?><form> </form>');

By the way, from version 4 the Joomla team prefer people getting the Form instance via the Dependency Injection Container. JForm will disappear at some point:

use Joomla\CMS\Form\FormFactoryInterface;
use Joomla\CMS\Factory;

$form = Factory::getContainer()->get(FormFactoryInterface::class)->createForm("gameofficials");
0

There are a few issues with this code:

I don't think you are using SimpleXMLElement properly. This is not an object (in the sense of Object Oriented Programming).

This is noted in the first comment on this functions page in the manual.

https://www.php.net/manual/en/class.simplexmlelement.php

What you should be doing I believe, is setting up an old fashioned loop to iterate through the xml properties.

I don't see any well defined xml in your code at all actually you might want to brush up on this. It should look something like:

<rootelement metadata="some metadata">   
 <nestedelement>
    here is some actual data   
 </nestedelement> 
</rootelement>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.