Saving value-data-pairs to database and retrieve them correctly

Permalink
Hi Concrete5 community,

I´m currently working on a block where the user gets data from an external API (cars) and show them on his site. Works fine. Now the user should be able to sort this cars (on block adding or editing).

My approach is to show the ID+title of the car and show a input box next to each car to put in some sorting value (1, 2, 3, 4). I´m filling that sortingHidden field with text values from JS (getting the ID and the sorting value of each row on block save submission -> and save that to db):

echo "<table id='sorting' class='table-striped' style='width:100%'>";
foreach($cars as $car){
  echo "<tr>";
    echo "<td>".$car->Id."</td>";
    echo "<td>".$car->TypeNameFull."</td>";
    echo "<td>".
    $form->text('sort', $sort, array('style' => 'width: 100%;'))
    ."</td>";
  echo "</tr>";
}
echo '</table>';
echo $form->hidden('sortingHidden', $sorting, array('style' => 'width: 100%;'));


But I´m sure that this is not the right approach. The sorting values should get saved in the database and retrieved again at block editing.

Has someone already done something like this and could be back on the right track?

Cheers
micrdy

micrdy
View Replies: View Best Answer
hutman replied on at Permalink Best Answer Reply
hutman
Instead of doing this with numeric boxes you could make them sortable and then just store the ID in a hidden field in the first TD, then when you save just do json_encode() on that variable.

Like this:

<?php if(count($cars) > 0 ){ ?>
   <table id="car_sorting" class="table-striped" style="width:100%;">
      <tbody>
         <?php foreach($cars as $car){ ?>
            <tr>
               <td>
                  <input type="hidden" name="carID[]" value="<?php echo $car->Id; ?>" />
                  <?php echo $car->Id; ?>
               </td>
               <td><?php echo $car->TypeNameFull; ?></td>
            </tr>
         <?php } ?>
      </tbody>
   </table>
<php } ?>


Then in your controller when you go to save it you just do

function save($args){
   $args['carID'] = json_encode($args['carID']);
   parent::save($args);
}


This will store your carIDs in the sorted order in the database. You can do the same thing with the car name if needed/