1

I 've created a custom form field type

class JFormFieldCategories extends JFormFieldList 
{

protected $type = 'categories';

public function getOptions() 
{
    $db = JFactory::getDBO();
    $categories=array();

    $sql = "select * from #__table";
    $db->setQuery( $sql );
    $results = $db->loadObjectList();
    if(count($results)>0)
    {
        foreach($results as $resc){
            $options[$resc->id] = $resc->description;
        }
    }

$options = array_merge(parent::getOptions(), $options);
            return $options;
   }
}

I have added the field to the form

<field name="discount_on_categories" type="categories" multiple="true" size="40"  />

This is a multiple select value. What shall i do to save the selected values to the database and show them when i edit the item?

  • What is currently happening when you try to save them? Are you getting any errors? Have you tried using var_dump() to see if any values are retrieved? – Lodder Nov 4 '17 at 15:15
  • If i dump the current field the result is NULL – dip Nov 4 '17 at 18:06
  • @Lodder The field displays with no issue. When click save i get the message item saved but this field doesn't Do i have to make any preprocess of the field value before saving? – dip Nov 4 '17 at 18:45
  • @Lodder I've this code on bind function and the value is saved if (isset($array['discount_on_categories']) && is_array($array['discount_on_categories'])) { $registry = new JRegistry; $registry->loadArray($array['discount_on_categories']); $array['discount_on_categories'] = (string) $registry; } – dip Nov 5 '17 at 8:38
1

I found the solution on this so i share it jsut in case someone else needs this. I've added part of code in 2 places. First on the table file, in bind function:

if (isset($array['discount_on_categories']) && is_array($array['discount_on_categories'])) {
        $registry = new JRegistry;
        $registry->loadArray($array['discount_on_categories']);
        $array['discount_on_categories'] = (string) $registry;
    }

and then in the model file:

        $registry = new JRegistry;
        $registry->loadString($item->discount_on_categories);
        $item->discount_on_categories = $registry->toArray();

The first part converts the field value to string so that to save it to the DB and the second part converts the string to an array so that to display the selected options of the field.

0

I think you're after the same thing than this question - check my answer here. I needed the same thing and after many hours come up with that solution

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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