3
votes

I am creating a form using Phalcon that has a checkbox on it. I use this code to create the checkbox in my PagesForm.php file

$this->add(new Check('usesLayout'));

and then in my view I have

{{ form.render("usesLayout") }}

However, if the checkbox is unchecked then Phalcon complains about usesLayout is required.

The html code produced by the view is

<input type="checkbox" id="usesLayout" name="usesLayout" value="1" checked="checked" />

What is the correct way to create a Phalcon form with a checkbox so that it accepts it both checked and unchecked?

Desired outcome

After looking back at a form made when using CakePHP the html output is

<input type="hidden" name="usesLayout" id="usesLayout_" value="0" />
<input type="checkbox" name="usesLayout" id="usesLayout" value="1" checked="checked" />

This works fine, so I am looking for something similar to this.

Current Workaround

After modifying the code in the final response to this question I have this workaround currently (I use this instead of Phalcon\Forms\Element\Check)

namespace Armaware\InBrowserDev\Forms\Element;

use Phalcon\Forms\Element\Check as PhalconCheck;

class Check extends PhalconCheck
{
    /**
     * Renders the element widget returning html
     *
     * @param array|null $attributes Element attributes
     *
     * @return string
     */
    public function render($attributes = null)
    {
        $attrs = array();

        if (!is_null($attributes)) {
            foreach ($attributes as $attrName => $attrVal) {
                if (is_numeric($attrName) || in_array($attrName, array('id', 'name', 'placeholder'))) {
                    continue;
                }

                $attrs[] = $attrName .'="'. $attrVal .'"';
            }
        }

        $attrs = ' '. implode(' ', $attrs);

        $id      = $this->getAttribute('id', $this->getName());
        $name    = $this->getName();
        $checked = '';

        if ($this->getValue()) {
            $checked = ' checked';
        }

        return <<<HTML
<input type="hidden" id="{$id}_" name="{$name}" value="0" />
<input type="checkbox" id="{$id}" name="{$name}" value="1"{$attrs}{$checked} />
HTML;
    }
}
1

1 Answers

1
votes

public Phalcon\Forms\ElementInterface setDefault (unknown $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

Source.

Looks like your declaration of form can look like this:

$controls[] = (new Check('usesLayout', ['value' => '1']))
    ->setLabel('Should I use layout?')
    ->setDefault('0') // or `false` in case it's not filtered
    ->addFilter('bool'); // filtering to boolean value

Not tested, but probably will do. You can always try to make this trick with handling this in beforeValidation() method of form, but have no space to test it right now and am not risking on failurable solution here.