Search code examples
phpformshookmodx-revolutionformit

set select field option tags with prehook in MODX


In a MODX Revo site, I have a FormIt form, with a select field which should look like:

<select name="arrangement" id="arrangement">
<option value="0" [[!+fi.arrangement:FormItIsSelected=`0`]]>Arrangement 0</option>
<option value="1" [[!+fi.arrangement:FormItIsSelected=`1`]]>Arrangement 1</option>
<option value="2" [[!+fi.arrangement:FormItIsSelected=`2`]]>Arrangement 2</option>

I would like to set the options with a FormIt prehook, called 'getArrangements'.

The prehook is called in the FormIt form definition before the form tags:

[[!FormIt?
   &preHooks=`getMaxYear,getArrangements` 

I succeeded to set the value of a simple input field with the first called prehook 'getMaxYear', it is clear to me how that works, but with the select field things are less clear. According to the MODX RTFM it should be done by json-encoding an array, like:

$hook->setValue('hobbies',json_encode(array('music','films','books')));

I removed the option tags from the select HTML and created a snippet named 'getArrangements':

<?php
$arrangements = array(  '0' => 'Arrangement 0', 
                        '1' => 'Arrangement 1', 
                        '2' => 'Arrangement 2'); 
$hook->setValue('arrangement',json_encode($arrangements));
return true;

This doesn't generate errors, but it leaves me with an empty select field.

I must be overlooking something here, I can imagine that the way I'm trying to do this doesn't work. But I'm stuck right now.

Could someone point me in the right direction to accomplish this?


Solution

  • FormItIsSelected wants a numeric array and you use an associative array. Use the following code to select option 0.

    <?php
    $arrangements = array('0'); 
    $hook->setValue('arrangement',json_encode($arrangements));
    return true;