How to get checkbox value (on table) into the controller?

in my view I did this and $checked doesnt exist on my controller.

View ->
foreach($payamentSlips as $payamentSlip) {

echo $this->Form->control('flag',[ 'type' => 'checkbox', 'data-payable-id' => $payamentSlip->id, 'checked' => in_array($payamentSlip,$checked)]); } ->Controller $test = $this->request->getData('checked'); dump($test);

$test returns null, why?

update: I replaced postButton to submit and got a array “flag” but only with the “0” as value

There are several fundamental things wrong here.

This is questionable:

'checked' => in_array($payamentSlip, $checked)

in_array( $value-to-look-for, $array-to-look-in ) is the proper construction.

docs for in_array

Your code places (what appears to be) an Entity object in the value position and an undefined variable in the array position. I’m not sure what your intention is here but it’s hard to imagine $checked is an array of entities.

Another problem: Your form control will be made for flag and that is the index you will get back on the data array in your controller. Your expectation for the data return is wrong.

//$this->request->getData() produces
[
	'flag' => '1'
]
// or 
[
	'flag' => '0'
]

Also: When you loop through $paymentSlips you will reset the value for flag again and again.

You need to look at the documentation for the Form helper to understand how the field name you provide the helper creates the name attribute in your HTML and how that translates into the post data array.

This may help some,
https://book.cakephp.org/3/en/views/helpers/form.html#field-naming-conventions

I’ve cleaned up the code in case someone else wants to provide better input than I have:

       //View ->
       foreach($payamentSlips as $payamentSlip) {
           echo $this->Form->control(
               'flag',
               [
                   'type' => 'checkbox',
                   'data-payable-id' => $payamentSlip->id,
                   'checked' => in_array($payamentSlip, $checked)
               ]
           ); 
       }
       //->Controller
       $test = $this->request->getData('checked');
       dump($test);

Best of luck with your project.

1 Like

Thanks. to explain what I want to achieve with that code, is to get all Payamentslip->id and save into the array $checked when you click in the checkbox.
Look at my project ->

I have a download button for every row, but I want to select which rows I want to download so all I have to do is get their ID and search into database and pass the data to the download function ( that I did with pdftohtml)

Something like this will get you back an array of the record ids and an indication of checked/not checked. You should be able to work from that in your controller.

echo $this->Form->create(null);
foreach ($paymentSlips as $slip) {
    echo $this->Form->control("flag.{$slip->id}", [ 'type' => 'checkbox' , label = '']);

}
echo $this->Form->submit();
echo $this->Form->end();

$this->request->getData() will return:

[
	'flag' => [
		(int) 3 => '1',
		(int) 19 => '0',
		(int) 20 => '1',
		(int) 50 => '0',
		(int) 74 => '0'
	]
]
1 Like

Thanks for your answer, but the result Im getting is a single array with the first flag selected. I’m not getting all selected checkboxes

without seeing code there’s not much to say about that

oh sorry.
View:

 foreach ($payamentSlips as $payamentSlip) {
<?php
                                        echo $this->Form->control("flag.{$payamentSlip->nosso_numero}", [
                                            'type' => 'checkbox',
                                            'label' => false,
                                            'data-payable-id' => $payamentSlip->id,

                                        ]);
                                        // dump($checked);
                                        ?>
                                </td>

Controller

public function gerarPdfSelecionados()
{
// dump($checked);
if ($this->request->is(‘post’)) {
$boletosel = ;
$data = ;
$session = $this->request->session();

        $data = $session->read('boletosel');
        $session = 2;
        // dump($data);
        // $checked = $this->request->getData('inpute.checked');
        if ($data) {
            $this->Flash->Error('Por favor selecione ao menos um boleto ');
            $this->setAction('index');
        } else {
            $this->Flash->Error('Não existe ');
            // dump($data);
        }
        $texto =  $this->request->getData();
        dump($texto);

        // $this->set('checked', $boletosel);
    }
}

result from $texto
array:1 [▼
“flag” => array:1 [▼
“00012931” => “0”
]
]

only show the first selected item.

One explanation for your result would be if each line in your table was in a separate form or if all but one was outside your form.

An important detail of my example is that all 5 checkboxes are wrapped in a single form and so, they all post together.

You would have to do something like this:

<form method="post" action="/gerarPdfSelecionados">
   <table>
      <tr><td> <input ... name="form[111]" > </td></tr>
      <tr><td> <input ... name="form[222]" > </td></tr>
      <tr><td> <input ... name="form[333]" > </td></tr>
   </table>
   <input type="submit">
</form>

<input name="form[444]" > // this input would not be returned with the form data

This form would return

['form' => 
   [
      '111' => 0,
      '222' => 0,
      '333' => 0,
   ]
]
//input 'form[444]' would be lost

Its not clear from your code if this is what is being produced.

Within the form, each input will have a ‘name’ attribute and that ‘name’ will match the structure of the array that will post.

Just like with any array, two matching entries will cancel, but it looks like that isn’t a problem here as long as nosso_numero are unique values.

Your browser probably has developers tools that will let you look at the html.

the Form->postbutton have the same function as Form create?
Because I only have one Form Create on my view

After I removed the postbutton(with different action) I got the full array but they do not change between 0 and 1(checked and unchecked

I want to send action with a variable to another action thats why I’m using postbutton, how I can replace for soemthing compatible with the Form I’m using?

postButton makes its own form. That was surly causing problems.

You can have as many forms on your page as you want. Just make sure the inputs for each falls inside the opening and closing tag for the form.

AND each form must have a unique id attribute.

<form id='111' >
   <input name='xxx' >
</form>

<form id='222' >
   <input name='yyy' >  
  <input name='rrrr' >  
  <input name='sss' >
</form>

form 111 would post [‘xxx’ => ‘value’]

form 222 would post an array with 3 elements.

1 Like

how to set a form id to the postbutton? because I need it to put inside a form tag but not connecting to that form

You can’t nest one form inside of another.

1 Like

You can have multiple submit buttons in your single form. And they can send the form data to different actions:

https://www.w3schools.com/tags/att_button_formaction.asp

With this technique you could include the input that is currently part of the postbutton in the general set of inputs in your form. Just make sure each one gets a unique name attribute you can target with your controller logic.

Then your one form will have ALL inputs and many submit buttons. All buttons will post all the inputs. One button will submit the form to do your download process. The other buttons will go to another destination that looks for one entry of the many in the post, and takes action on that value.

Each one of the second class of buttons will have to pass a second parameter in the action url to identify which one was activated. This will give the action a key to use when extracting the post datum.

   <button type="submit" formaction="/action.php/9">Submit to another page</button>

or

   <button type="submit" formaction="/action.php?id=9">Submit to another page</button>

Or you could use javascript the handle things.

1 Like

Thanks! I thought i saw some similar on stackoverflow but wasnt sure that would fit for cake php 3.8

It worked!

But I still have the problem of all getting all arrays => 0 (unchecked) but I checked them… What could be the possible issues for this?

I can’t think of anything that would cause that…

Is there any javascript running on the page?

If you post more code snippets, please use ```php on a line by itself just before your code.

and ``` on a line by itself just after your code to format it in the message. It will make things much easier to read.

1 Like

Seeing the entire block of code, from where you start the form to where you close it, would be very helpful. What you originally posted wasn’t sufficient, and is surely quite a bit different from what you’re working with now anyway.

2 Likes

Thanks, on the specifc view there’s no javascript that are messing with Forms
Here’s the code!

  <script>
    $(document).ready(function() {

        $("input:checkbox").iCheck({
            checkboxClass: 'icheckbox_flat-blue',
            radioClass: 'iradio_flat',
            increaseArea: '20%'
        });
    });
</script>

<?php

use App\Controller\ShowPayamentSlipController;

$this->Breadcrumbs->add([
    ['title' => $this->Html->tag('i', '', ['class' => 'fa fa-home']), 'url' => ['controller' => 'Home', 'action' => 'index']],
    ['title' => 'Impressão de boletos']
]);
echo $this->Breadcrumbs->render();
$checked = array();
?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col">
                        <h3>IMPRESSÃO DE BOLETOS</h3>
                        <?= $this->Form->create('user', ['url' => ['action' => 'gerarPdfSelecionados']]); ?>
                        <?= $this->Form->submit(
                            'BAIXAR BOLETOS SELECIONADOS',

                            ['action' => 'gerarPdfSelecionados'],
                            ['confirm' => 'Deseja Imprimir Todos os Boletos Selecionados?', 'class' => 'btn btn-outline-primary statement']



                        )
                        ?>
                        <br>
      
                    
                    </div>
                    <div class="col-md-12 col-sm-12">
                        <table class="table table-hover extra-slim-row">

                            <tr>
                               
                                <th>SELECIONAR</th>
                                <th> Nosso Numero </th>
                                <th><?= $this->Paginator->sort('data_vencimento', 'Data Vencimento') ?></th>


                                <th><?= $this->Paginator->sort('valor', 'Valor') ?></th>


                                <th>Data Emissão</th>
                                <th>Ação</th>
                            </tr>
                            <?php

                            foreach ($payamentSlips as $payamentSlip) {
                              
                            ?>

                                <tr<?= $payamentSlip->boleto_emitido ? ' style="background-color: lightgray"' : '' ?>>
                                    <td style="text-align: center">
                                        <?php

                                        echo $this->Form->control("flag.{$payamentSlip->nosso_numero}", [
                                            'type' => 'checkbox',
                                            'label' => false,
                                            'data-payable-id' => $payamentSlip->id,

                                        ]);
                                        ?>
                                    </td>

                                    <td><?= $payamentSlip->nosso_numero ?></td>
                                    <?php $dataf = $payamentSlip->data_vencimento ?>
                                    <td><?= $dataf; ?></td>

                                    <?php $numero_formatado = substr($payamentSlip->valor_cobrado, 0, 15) . "." . substr($payamentSlip->valor_cobrado, 15); ?>


                                    <td style=" " text-align: right"><?= $this->Number->currency(number_format($numero_formatado, 2, '.', '')) ?></td>


                                    <td><?= $payamentSlip->data_emissao ?></td>
                                    <td>

                                        <?=
                                            $this->Form->button('DOWNLOAD DO BOLETO', array('type' => 'submit', 'formaction' => ['gerarPdf/', $payamentSlip->id]));

                                        ?>


                                    </td>
                                    </tr>
                                <?php
                            }
                            echo $this->Form->end();
                                ?>

                                <?php if ($payamentSlips->count() > 0) {
                                } else {
                                ?>
                                    <tr>
                                        <td colspan="10" class="no-data-found">Nenhum registro encontrado</td>
                                    </tr>
                                <?php
                                }
                                ?>
                                <?php  ?>

                        </table>
                        <?= $this->element('paginator', ['paginator' => $this->Paginator]) ?>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

I’ll look at this in more detail later.

One problem I see right now, the tag opens before the

tag but closes before it.

This is another case where you are not understanding proper DOM structure. This is an area that you’re going to need to look into or you will continue to trip yourself up with avoidable php problems.

Not to mention the chaos that might come from whatever the various browsers try to do with invalid HTML.

Also, It will be helpful if you clean some of the dead code out of your pasted code.

1 Like

Thanks I cleaned the code above!
I will look into the tags

I put checked = “true” on all checkboxes, and still got 0 value, strange? why