samedi 4 mars 2017

HTML Checkbox For Loop for Gallery

I'm using OctoberCMS based on Laravel.

I used Twig to generate a simple Gallery using a loop.

You can delete a Single image, or choose with a Checkbox, and click any Delete Button to submit.

is the image name in the database.

Form with Twig

<form method="POST" action="/">

    <input type="hidden" name="_handler" value="onDelete" >

    <!-- Gallery -->
    

</form>

gallery

PHP

function onDelete() {

    $path = '/var/www/mysite/images/';
    $single = $_POST['single'];
    $checkboxes = '';
    $checkboxes = isset($_POST['queued']) ? $_POST['queued'] : array();

    # Checkbox Delete
    if(isset($_POST['queued'])) {
        foreach($checkboxes as $name) { 
            File::delete("$path$name.jpg");
        }
    }

    # Single Delete
    else {
        File::delete("$path$single.jpg");
    }

}

Problem

Rendered HTML

<form>
    <img src="images/image1.jpg">
    <input type="hidden" name="single" value="image1" >
    <input type="checkbox" name="queued[]" value="image1" />

    <img src="images/image2.jpg">
    <input type="hidden" name="single" value="image2" >
    <input type="checkbox" name="queued[]" value="image2" />

    <img src="images/image3.jpg">
    <input type="hidden" name="single" value="image3" >
    <input type="checkbox" name="queued[]" value="image3" />
</form>

The Checkbox Delete runs the for loop and works.

But Single Delete always deletes the last name="single" on the form, image3.

I tried setting $_POST['single'] to an array name="single[]" but it deleted all files, because they are not type="checkbox" and are always isset and added to the array.

How can I solve this and have Checkbox Delete and Single Delete in the same form?




Aucun commentaire:

Enregistrer un commentaire