We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Element::setLabel is an empty string, but Element::label returns non empty label text

Hello, everyone!

In a controller I set up a label for a button as an empty string:

$form = new Form();
$submit = new Submit('submit', array('value' => 'Next'));
$submit->setLabel('');

getLabel() returns an empty string which is expected by me:

$submit->getLabel() // returns an empty string

But label() returns <label for="submit">submit</label> which is unexpected by me:

$submit->label() // returns '<label for="submit">submit</label>'

Here is my In my .phtml file:

<form action="" method="POST">
    <?php
    foreach ($form as $element) {
        $messages = $form->getMessagesFor($element->getName());
        if (count($messages)) {
            foreach ($messages as $message) {
            ?>
                <div class="message"><?= $message ?></div>
            <?php
            }
        }
        echo $element->render();
        echo $element->label();
    }
    ?>
</form>

Here is the output: <input value="Next" type="submit" /><label for="submit">submit</label>

So, to prevent rendering the label with an empty text I added the extra condition:

echo $element->render();
if($element->getLabel() != '') {
    echo $element->label();
}

I think $submit->label() should return an empty label <label for="submit"></label> (or an empty string?) instead of <label for="submit">submit</label>. Does anybody agree?

Looks like in the documentation the ::label method actually generates the label for the element and doesn't return it. So if you have the element defined, as you do, ::label will generate the label.

public Phalcon\Forms\ElementInterface setLabel (string $label)

Sets the element label

public string getLabel ()

Returns the element’s label

public string label (unknown $attributes)

Generate the HTML to label the element

https://docs.phalcon.io/en/latest/api/Phalcon_Forms_Element.html



643

Hello.

It confused me a bit. When I call this

$submit->setLabel('');

I expect this to return somthing like this(no label text) <label for="submit"></label>

$submit->label();

but it returns <label for="submit">submit</label>

I checked my phalcon version and it says 1.2.5 I will upgrade to 2.0



4.7k
Accepted
answer

If you just want to render the label with no label text you need to initiate the submit with

$submit = new Submit('', array('value' => 'Next'));

The ::label method is independent of the getLabel and setLabel methods.



643

Thank you. Now it's clear.