Tuesday, May 1, 2012

Joomla 2.5 Admin Component Multi View Create & Save

To create a field in the Joomla 2.5's administrator part of the component and to store it you have to do the following things:

First to create a multi select drop down field you have to add the following attribute into the xml
multiple="multiple"

like I did in the following:


<field
        name="practice_areas_ids"
        type="list"
        class="inputbox"
        default=""
        label="Practice Area(s)"
        multiple="multiple">
<option value="1">Area 1</option>
<option value="2">Area 2</option>
                        <option value="3">Area 3</option>
</field>


Now you will be able to see and select multiple fields when you click on 'New' or 'Edit' in your component however this won't save the multi selected array into your database and will store just the first value e.g. if you select Area 2 & Area 3 it will only store 2. To save comma separated all values you have to do the following:

Go to your store/bind or whichever function you are using and add an implode line, here is mine for clarity:
$practice_ids = implode(",", $_REQUEST['jform']['practice_areas_ids']);

Now this let's you select multiple fields and store their ids successfully into the database, that leaves us with our last problem which is if you open your row/entry in edit you will see that the selected Area(s) will not show as selected, that is because it is reading the field as comma separated list instead of an array so as we did implode on saving, we need to do explode on displaying. To do that follow the following:

Go to 'models'/modelName.php and look for the function 'loadFormData()'
Go inside it and after you have obtained the $data and before returning, replace the multiple select field with exploded array, like:



         protected function loadFormData() 
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_jobm.edit.italy.data', array());
if (empty($data)) 
{
$data = $this->getItem();
}
                $data->practice_areas_ids = explode(',', $data->practice_areas_ids);
return $data;
}

No comments:

Post a Comment