3
votes

This may seem obvious to some of you, but I really am struggling to find a straight answer. I've generally googled, as well as read both the CakePHP manual and the API for an answer to the following question:

When creating an input, the following code creates the following outputs:

// in the view
echo $this->Form->input('notes');

// resultant html
<div class="input textarea">
    <label for="notes">Notes</label>
    <textarea id="notes" rows="5" name="notes"></textarea>
</div>

Note: this is consistent across most input types; and because it's consistent it's great for formatting.

However, with a checkbox:

//In the view
echo $this->Form->input('ticket_required', 
    ['type' => 'checkbox']
);

// resultant HTML
<div class="input checkbox">
    <input type="hidden" value="0" name="ticket_required">
    <label for="ticket-required">
    <input id="ticket-required" type="checkbox" value="1" name="ticket_required">
    Ticket Required</label>
</div>

[Note: I understand the need/desire for the hidden field]

Now.. surely it can't be an uncommon requirement to simply want the same format approach as every other standard input?

My question - how do I make CakePHP create a checkbox element as follows:

// desired HTML
<div class="input checkbox">
    <input type="hidden" value="0" name="ticket_required">
    <label for="ticket-required">
    Ticket Required</label>
    <input id="ticket-required" type="checkbox" value="1" name="ticket_required">
</div>

To be clear: the order of visible elements is the same as other generated elements (label before input, and all encased in the wrapping div).

Please note.. i have tried the 'nestedInput' => false option. This actually gets rid of the checkbox input entirely from the div.

I can't understand why this isn't done that way... but even if it was, I can't fathom why this isn't an obvious question for the documentation.

Oh well.. hopefully someone can help me here.

Thanks in advance.

Rick

1
I think this is what you are looking for: stackoverflow.com/a/5394069/3144159Inigo Flores
This doesn't work on CakePHP 3.xelb98rm

1 Answers

4
votes

I would have thought the nestedInput would work but even if it did, you don't want to add that to every input you create throughout the website.

CakePHP 3 uses string templates to build form controls. You can modify them to suit your needs.

By default the checkbox is using the nestingLabel template so if you want to stop all inputs from being nested you can change the template.

// src/View/AppView.php

$this->loadView('Form', [
    templates => [
        'nestingLabel' => '<label{{attrs}}>{{text}}</label>{{hidden}}{{input}}'
    ],
    // [More helper default config overrides][2]..
])

For more control over your helpers you can create your own that extends one of the core helpers.