Hide input field with parent div

Hello,

oftentimes, we need to hide both the input field and its corresponding label based on certain conditions, but CakePHP 4.x doesn’t offer a built-in option to hide the whole div, label and the input field directly in the $this->Form->control() method. Is that right?

Cheers,
Marc

Thats up 2 you to implement since CakePHP doesn’t offer any JS specific functionality. We are a purely serverside framework.

okay, but why i can hide the input field with that ‘hidden’ option?

I need to generate a hidden control and my javascript show it, depending on another fields value. Maybe I’m the only one who has this need :slight_smile:

If I solve this with JavaScript, which actually works so far, this input field is first rendered for a millisecond and then it is hidden. Do you have a hint for me?

If you are talking about

$this->Form->hidden('somefiled');

this generates

<input name="somefiled" type="hidden" />

and therefore is just a visibly hidden input field which still is being submitted (basic HTML)

But this does not do what you want (do conditionally hide/show forms depending on other forms)


If you want your form to be rendered with prefilled data which conditionally hides/shows fields you will have to replicate those conditions in your template, not only JS.

An alternative approach is to use HTMX to re-render the form whenever it changes - but I have not yet tried that. See e.g. Posts | Mark Story

i need something like this:

echo $this->Form->control('password_new', ['type' => 'password', 'label' => __('Password')]);
echo $this->Form->control('password_old', ['type' => 'password', 'required' => 'required', 'hidden' => true, 'label' => __('Old Password')]);

and the javascript part:

$(document).ready(function() {
        
        $("#password-new").change(function() {
            
            if($("#passwort-new").val().trim() !== "")
                $("#passwort-old").parent().show();
            else
                $("#passwort-old").parent().hide();
        });

    });

but in this example it is only hiding the old passwords input field, not the label.

Then, as @KevinPfeifer said, you need to change your JavaScript. Cake doesn’t offer those tools at all. Take a look at the HTML Cake is generating, and adjust your JS to match the DOM you are working with. You’ll need to have it traverse upwards to find the right container element to show or hide.