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

Checkbox in a model bound form

I'm having trouble figuring out how to correctly use checkboxes with model bound forms. Here's basically what I have:

class MyModel extends Model {
    public $is_sent; // bool in MySQL
}

class MyModelForm extends Form {
    public function initialize() {
        $this->add(new Check('is_sent'));   
    }   
}

class MyController extends Controller {
    public function myAction($id) {
        $model = MyModel::findFirst($id);
        $form = new MyModelForm($model, $_POST);

        if ($this->request->isPost()) {
            if ($form->isValid($_POST, $model)) {
                $model->save(); 
            }
        }

        $this->view->form = $form;
    }   
}

Rendering this to HTML surely creates a checkbox which is either checked or unchecked according to the $is_sent value in the model.

But also the value of the checkbox changes; it's "1" for true/checked and "0" for false/unchecked. So checking the checkbox doesn't actually change the model value since it's posted as "0". A dirty fix for this is to force the value to "1":

class MyModelForm extends Form {
    public function initialize() {
        $this->add(new Check('is_sent', array('value' => 1));
    }   
}

So this fixes the problem of changing the value from unchecked to checked. But the other way round doesn't work. When I uncheck the checkbox, it's not included in $_POST and the value on the model isn't changed. Another dirty fix does the trick:

class MyController extends Controller {
    public function myAction($id) {
        $model = MyModel::findFirst($id);
        $form = new MyModelForm($model, $_POST);

        if ($this->request->isPost()) {
            if (!$this->request->hasPost('is_sent')) $_POST['is_sent'] = 0;

            if ($form->isValid($_POST, $model)) {
                $model->save(); 
            }
        }

        $this->view->form = $form;
    }   
}

Am I doing something wrong or is the model-form buggy and the only solution is these dirty kludges?



514

Hi,

I suggest to check the above posted solution:

https://github.com/phalcon/cphalcon/issues/2890