Saving multiselect values using API

Permalink
Hi all

I'm creating a custom attribute which uses the inbuild form helper and select widget, like this:

echo $form->select($fieldPostName, $options, $fieldValue, array('multiple'=>'multiple'));
print_r($fieldValue);


This renders fine, but the values aren't passed through to the controller -- only the last selected value is saved. I think this is because the Select's value needs to be an array in order to store multiple values, but if I force that (by putting `[]` at the end of its name) c5 doesn't like it because it expects only a string to be passed.

Do I need to have some javascript processing the data into a string before it gets saved? I thought the API would handle this.

melat0nin
 
Mainio replied on at Permalink Reply
Mainio
Which concrete5 version are you running?

Where does this error appear, in block controller or where?

If it happens in the block's controller, you can just override the save() method in your own controller and pre-format the passed values to be in correct desired format.
melat0nin replied on at Permalink Best Answer Reply
melat0nin
Thanks for your reply!

I got there in the end simply by serialising the data in the controller before it's saved to the database. To do that I needed to create a separate saveForm() method in the controller:

public function saveForm($data){
         $string = serialize($data);
         $this->saveValue($string);
      }


The name of the select field also needs `[]` appended to it so the selected values are passed as an array, otherwise only the last-selected option will be passed. I also had to reconstruct the select field outside of the API, but that's simple enough:

in form.php

<select name="<?=$fieldPostName?>[]" multiple="multiple" class="ccm-input-select">
<?php
   foreach ($options as $key=>$option) {
      $selected = '';
      if ( in_array($key, $selected_ids)) $selected = ' selected';
        }
?>
...


That seems to work well.