title: How to set form data for a Joomla subform?
body: <p>I'm trying to create a Joomla (3.x) component and struggling with using subforms. There doesn't seem to be much documentation for using subforms besides e.g. <a href="https://docs.joomla.org/Subform_form_field_type" rel="nofollow noreferrer">https://docs.joomla.org/Subform_form_field_type</a></p>
  
  <p>For my component I have one parent table and some associated database rows from a child table.</p>
  
  <p>The idea is to display an edit form for that parent table using Joomla's XML syntax for forms and in that edit form also display a subform with multiple items (the associated rows from the child table).</p>
  
  <p>I would like to be able to modify the parent table fields but also in one go the associated child table rows (of course one could just edit each row associated to the parent table individually but I'm guessing that would be a terrible user experience). Or am I approaching this thing the wrong way?</p>
  
  <p>Now, I know how to implement/show a subform and also know how to show the parent table fields and populate those fields with the right data. But how do I populate or refer to the subform using the parent form?</p>
  
  <p>I have this function inside my component model (which inherits from <code>JModelAdmin</code>).</p>
  
  <pre class="lang-php prettyprint-override"><code>protected function loadFormData()
  {
    $data = JFactory::getApplication()-&gt;getUserState('com_mycomp.edit.parent.data', array());
  
    if (empty($data))
    {
      $data = $this-&gt;getItem();
      // how to refer to subform fields inside $data?
    }
  
    return $data;
  }
  </code></pre>
  
  <p>I know if a field is called <code>name</code> or <code>title</code> I can just change the <code>$data</code> object after <code>$this-&gt;getItem()</code>, e.g. <code>$this-&gt;set('name', 'John Doe')</code>.</p>
  
  <p>Let's say the field of type <code>subform</code> has a <code>name</code> attribute of <code>books</code> and I wanted to insert one or more rows, how would I refer to it? I've tried dot syntax in various forms, e.g.: <code>$data-&gt;set('books.1.childfield')</code> or <code>$data-&gt;set('books.pages1.childfield')</code>. But it doesn't seem to refer to the right form.</p>
  
  <p>There is of course <code>getForm</code> function in the same model file, however I do not think a subform should be loaded independently of the containing parent form?</p>
  
  <pre class="lang-php prettyprint-override"><code>public function getForm($data = array(), $loadData = true)
  {
    $app = JFactory::getApplication();
  
    $form = $this-&gt;loadForm('com_mycomp.parent', 'parent', array('control' =&gt; 'jform', 'load_data' =&gt; $loadData));
    if (empty($form))
    {
      return false;
    }
  
    return $form;
  }
  </code></pre>
  
  <p><strong>EDIT:</strong>
  Already answered my own question.</p>