FormHelper::check_box
In release 0.2.1 of Medick, the check_box control from FormHelper was broken.
As a temporary fix, you have to explicitly check if the check_box was submitted or not in your controllers.
Let’s see a small sample.
I will assume that we have an article model with a status defined as INT (1) in the database. This status describes the article state: PUBLISHED or DRAFT.
The article model
class Article extends ActiveRecord { const PUBLISHED= 1; const DRAFT= 0; [...] }
On the controller side, I will define 2 methods: add, witch will print the form for adding an article and create that will save the article in the database.
class ArticleController extends ApplicationController { // prints the form, and assign article template variable public function add() { $this->article = new Article(); } // saves the article in the database public function create() { $this->article= new Article($this->request->getParameter('article')); // explicit check: if (!isset($this->params['article']['status'])) { // the check box is not checked, so we define the // default value for this case: $this->article->status= Article::DRAFT; } else { // checked check-box :) // default value for this case: $this->article->status= Article::PUBLISHED; } // do actions on article, like save and the redirect if succes or render // the form again if it`s a failure. [...] } }
In the add view, we can use the FormHelper to create the check box entry for us:
[...] <?=FormHelper::check_box($article,'status');?> [...]
translated in HTML:
<input type="checkbox" id="article_status" name="article[status]" />
As I said, this is just a temporary solution untill I will have another ideea.
This includes adding a hidden field with the same name on the form, or anything else that will do.
Why this checkbox is causing all this troubles?
Because if is not checked, the article that we create at this line:
$this->request->getParameter('article');
will not receive the status as a request parameter.
The real pain it will be when one will need more than a simple checkbox, and I’m thinking about a use case where an article has_many categories and a checkbox control will be used for selecting in what categories the article fits.
While I mark this problem as fixed, I’m still open to improvements on how can I do this better.