Help assigning values to JForm fields ?

32 views
Skip to first unread message

David Byrne

unread,
Dec 11, 2017, 9:00:28 AM12/11/17
to Joomla! General Development
Hi,

I'm writing a component for my Joomla 3.8.2 site, and having great difficulty assigning values to fields in a JForm. The field labels and the input fields are all printed correctly, but they're empty. I can't see what I'm doing wrong, and I'd really appreciate any advice. I've read dozens of pages over the last few days but no progress - it's probably something embarrassingly obvious :)

My code looks like this:

form.xml:

<pre>
<?xml version="1.0" encoding="utf-8"?>
<form>
<fields name="projectfields">
<fieldset name="fielddefs">
<field
type="text"
name="title"
id="title"
label="PROJECT_TITLE_LABEL"
description="PROJECT_TITLE_DESC"
size="80"
maxLength="255" />
<field
type="textarea"
name="description"
id="description"
label="PROJECT_DESCRIPTION_LABEL"
description="PROJECT_DESCRIPTION_DESC"
rows="5"
cols="200"/>
</fieldset>
</fields>
</form>
</pre>

default.php:

<pre>
[snip]
$values = array(
'title' => "My first project",
'description' => "This is my first project"
);

$form = &JForm::getInstance('addprojectform', JPATH_ROOT . "/components/com_project/views/projects/tmpl/form.xml");

if (!$form->bind($values))
throw new RuntimeException($form->getError());

foreach ($form->getFieldsets('projectfields') as $fieldsets => $fieldset)
foreach ($form->getFieldset($fieldset->name) as $field)
echo $field->label . ": " . $field->input . "<br />";
[snip]</pre>

I've also tried $form->setValue('title', null, 'My first project'); with the same results - the label and field type are displayed fine, but the value isn't assigned.

Thanks for any help !

David

David Byrne

unread,
Dec 11, 2017, 12:20:11 PM12/11/17
to Joomla! General Development
In case it helps anyone in future ...

I spent some more hours digging around and trying to understand how this JForm works. Finally I did the following and it works now:

1. stripped out the <fields name='projectfields'> tags and 
2. changed " foreach ($form->getFieldsets('projectfields') as $fieldsets => $fieldset)" to " foreach ($form->getFieldsets() as $fieldsets => $fieldset)"

Two other by-products - the fields are rendered with the correct names (esp. important for the hidden fields) so "option" instead of "projectfields[option]", and also $form->getInput('title'), $form->getLabel('title') and $form->getValue('title') all work now. Previously getInput worked but neither of the other two functions.

I don't know what the <fields> group is for - something to do with control groups - but I'm not bothered. The documentation for this is truly abysmal :)
Reply all
Reply to author
Forward
0 new messages