Search code examples
phpmodxmodx-revolutionmodx-resources

Trying to create multiple Modx resources from a form


I have a form that is within a table that looks similar to the below, I have a Modx snippet that runs when this is submitted that should create multiple new resources, based on the input arrays send through.

<table class="table responsive-table">
           <thead>

               <th>pagetitle</th>
               <th>longtitle</th>
           </thead>
           <tbody>
               <tr>

               <td><input type="text" name="pagetitle[]" value="" /></td>
               <td><input type="text" name="longtitle[]" value=""/></td>    
               </tr>
               <tr>
               <td><input type="text" name="pagetitle[]" value="" /></td>
               <td><input type="text" name="longtitle[]" value=""/></td>    
               </tr>
           </tbody>

       </table>

What is happening when the below runs is, it creates the new resources as expected however all the fields are set to "Array". and not the value of the array.

<?php
$allFormFields = $hook->getValues(); 


foreach ($allFormFields as $key => $value)
{
    $doc = $modx->newObject('modResource');
    $doc->set('createdby', $modx->user->get('id'));
    $doc->set('pagetitle', $value['pagetitle']);
    $doc->set('longtitle', $value['longtitle']);
    $doc->save();
}

return true;

Solution

  • print_r() on $allFormFields will very likely give you something like this:

    // dump of form values
    Array (
        [pagetitle] => Array (
            [0] => 'pagetitle1'
            [1] => 'pagetitle2'
        ),
        [longtitle] => Array (
            [0] => 'longtitle1'
            [1] => 'longtitle2'
        ),
    )
    

    That's why you're getting 'Array' when you try to set your resource fields to $allFormFields['pagetitle'].

    I'm not entirely sure what you're doing, but it would probably be better to construct your form like this instead:

    <input type="text" name="resource[0][pagetitle]" value="" />
    <input type="text" name="resource[0][longtitle]" value="" />    
    
    <input type="text" name="resource[1][pagetitle]" value="" />
    <input type="text" name="resource[1][longtitle]" value="" />
    

    Then you can loop through the form fields for each resource like this:

    <?php
    $allFormFields = $hook->getValues();
    $userId = $modx->user->get('id');
    
    foreach ($allFormFields['resource'] as $fields) {
        $doc = $modx->newObject('modResource');
        $doc->set('createdby', $userId);
        $doc->set('pagetitle', $fields['pagetitle']);
        $doc->set('longtitle', $fields['longtitle']);
        $doc->save();
    }