8.4.2 How to save/edit varuable number of inputs in block form

Permalink
I have a DB with a table of statuses with columns status_id and status (status name). The status names are set by a user, i.e. their numbers, names and IDs are variable and non-predictable.

I need to allow the user to turn ON or OFF whichever status they want to show in a block.

In a block form I can list the statuses like
<?php
if (is_array($statuses) && count($statuses) > 0) {
    foreach ($statuses as $status) {
    ?>
        <div class="checkbox">
            <label>
                <?php
                echo $form->checkbox('show_status[]', 1, $XXX ? '1' : '0');
                echo t('Show') .  ' ' . $status->getStatus();
                ?>
            </label>
        </div>
    <?php
    }
}

and save them in a controller like
$args['data'] = json_encode($args['show_status']);

What I can't get is how I can load the saved values during block edit.

If the statuses couldn't change, I'd simple decode the json and displayed it there instead of $XXX. But as any status can be deleted before editing the block and new ones can be created, the id="show_status[]" will no longer reference the correct value.

Would anyone know how to save and load the input values in that case?

Thank you.

linuxoid
 
linuxoid replied on at Permalink Reply
linuxoid
I have a number of check boxes in a view:
if (is_array($statuses) && count($statuses) > 0) {
    foreach ($statuses as $status) {
        echo $form->checkbox('show_status[' . $status->getStatusID() . ']', 1, $status->isShow() ? '1' : '0');
        echo $form->label('', t('Show') . ' ' . $status->getStatus());
        echo '<br />';
    }
}

I'm trying to save them in controller:
$show_status = $data['show_status'];
$s = implode(',', array_keys($show_status));
\Log::addInfo('Statuses: ' . $s);
if (is_array($show_status)) {
    foreach (array_keys($show_status) as $id) {
        $status = Status::getByID($id);
        if (is_object($status)) {
            $status->setShow(true);
            $status->save();
        }
    }
}

where the save() is a Status class function:
public function save()
{
    $em = \ORM::entityManager();
    $em->persist($this);
    $em->flush();
}

I can see in the log correct IDs of the selected check boxes. But the values are not saved in the Status DB table, I have this error:
Doctrine \ DBAL \ Exception \ SyntaxErrorException
An exception occurred while executing 'UPDATE Statuses SET show = ? WHERE status_id = ?' with params [1, 3]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'show = 1 WHERE status_id = 3' at line 1


What's wrong with that?
linuxoid replied on at Permalink Reply
linuxoid
Doh! 'show' is a reserved word in MySQL.