Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How to setup checkbox property to accept 0 or 1 for values
  • Trying to setup a checkbox field for a boolean property that is a tinyint of 0 or 1.  Not really following how checkbox's are done with the fieldset and propery definitions.

    I came across this post:

    http://fuelphp.com/forums/discussion/8807

    It didnt seem to do the trick on my end. Not fully understanding why there is an example like this in the docs:

    <i><span class="comment">    // Example Checkbox</span>
    <span class="variable"> $ops</span> = <span class="keyword">array</span>(<span class="string">'male'</span>, <span class="string">'female'</span>);
    <span class="variable"> $form</span>-&gt;add(<span class="string">'gender'</span>, <span class="string">''</span>, <span class="keyword">array</span>(<span class="string">'options'</span> =&gt; <span class="variable">$ops</span>, <span class="string">'type'</span> =&gt; <span class="string">'checkbox'</span>, <span class="string">'value'</span> =&gt; <span class="string">'true'</span>));
    </i><br>When it appears to just render multiple checkboxes?<br><br>Anyone have any examples/references where I can achieve a normal single checkbox with value=1 if checked, else its unchecked?<br>

  • HarroHarro
    Accepted Answer
    For the fieldset, to be able to determine if it's checked or not, you'll need to defined the 'checked' value in the properties:

     'form'          => array(
        'type'        => 'checkbox',
        'value'    => 1,
    ),

    This is for a property that uses values 0 and 1. In other words, if the column contains the value defined here, it will be checked. If not, it will not be checked.
  • awesome, that is simple, thanks for the tip
  • Just noticing that my boolean checkbox fields (values of 0 and 1) are not properly saving.  When the checkbox is unchecked no value is passed, and looks like the model just keeps the old value.

    Typically I setup my checkbox fields with a hidden field of the same name preceding, that way browser will pass back the value in the hidden field if non is set for checkbox value.

    Other thing I expected/tried is setting the 'default' value on the model property to 0 thinking it would get set when populated in my fieldset handling, but that didnt seem to do anything.


  • That's unfortunately not something we can do anything about.

    The input tag type "checkbox" is designed so that it's not present in the posted data when not checked. If would have been a lot easier if you would have been able to define a selected/not-selected value pair.

    The only thing you can do is check for the absence of the value, and set it to 0 manually. Which is what I do.

    This is a snippet from one of my controllers that has a checkbox:
    // do we have input?
    if (\Input::post())
    {
        // validate the input
        $form->validation()->run();

        // if validated, save the updates
        if ( ! $form->validation()->error())
        {
            // get the validated data, and get rid of null values
            $data = array_filter($form->validated(), function($item){ return $item !== null; });

            // do something about invalid or missing values
            empty($data['birthdate']) and $data['birthdate'] = null;
            empty($data['dyslectic']) and $data['dyslectic'] = 0;

            // update the person record
            $people->from_array($data);

            // and save it
            if ($people->save())
            {
                \Messages::success(sprintf(__('people.updated'), $people->surname.', '.$people->initials.' '.$people->prefix));
                \Pagelink::redirect_back($people) or \Response::redirect('module/people/'.$people->type);
            }
            else
            {
                \Messages::error(__('people.updated-failed'));
            }
        }
        else
        {
            // inform the user validation failed
            \Messages::error(__('people.form.errors'));
        }

        // repopulate the form from the posted data
        $form->repopulate();
    }
    The 'default' value in the ORM property definition is only used when you forge a new model instance, and you don't pass the field in the data array. It won't reset columns to a default value. If you don't pass a value on update, the ORM assumes (rightly) that you don't want to alter that columns value.
  • I have a similar problem.
    I use the Validation class, and in DB i save 0 for unchecked, and 1 for checked.

    When I create the form, what should I wrote, in order to show the checkbox element checked or not based on what I have in the DB?

    Just this,doesn't work ;
    echo Form::checkbox('coaching', Input::post('coaching', 1));

    It's important to note that if I submit the form, and the user didn't insert a value to another mandatory field (let's name it field 1), even if he checked the checkbox (let's name it field 2), this one (field 2), is not checked keeping in mind that he selected before the validation...

    So what should I do, in order to have the value from POST if is the case, else the value from DB (0 or 1) ? How the correct line should look ?
  • See http://docs.fuelphp.com/classes/form.html#/method_checkbox, you need to pass true as third parameter to check the checkbox, or pass the same value as the fields set value:

    echo Form::checkbox('coaching', 1, Input::post('coaching', 1));

    which will check the box if the post() method returns 1.

  • Hi,
    In your example,

    echo Form::checkbox('coaching', 1, Input::post('coaching', 1));

    you pass as value, by default 1, or I'm wrong ?

    From what I understand, it creates a checkbox element, with the name 'coaching', with value 1, and if is nothing in POST regarding this variable, the default will be 1, so the box will be checked. Correct ?

    So I don't have to check in the DB to see if is checked or not, in order to know what to show if isn't a POST case ?

    Because
    normally, after the user filled some data, and I save everything in the
    DB, when he wants to edit, I display the form, and the info should be
    there as he save it, so I would say :

    if(isset($field) && $field == 1)
    {
      $checked = 'checked';
      $value = 1;
    }
    else
    {
    $checked = false;
    $value = 0;
    }
    Form::checkbox('coaching', Input::post('coaching', $value), array( 'checked' => $checked) );

    or how, do I show the checkbox checked, if in the DB I have 1, and how do I show it unchecked if in the DB i have 0 ?

    I have to cover both cases (If I have a post, because the user submitted, keep this value in mind, else, if I have something in the DB for this field show what I have there, else show the box un-checked).

  • Correct.

    If you create the form element manually (using Form::checkbox), you will have to deal with the DB value manually as well, for example to use that as the default for Input::post (i.e. if no posted value is present, use the DB value).

    Something like: Form::checkbox('coaching', 1, Input::post('coaching', $db['coaching]));

    assuming the $db array contains your database record. This will check the box if either $_POST['coaching'] is present AND its value is 1, or if the contents of $db['coaching'] is 1.

    If you use ORM and fieldsets, this will all happen automatically.
  • everything is clear now. I've created a hepler function, to check if isChecked, and it returns me the result.

    For others I did it like this :

    public static function isChecked($object, $property, $withValue = null)
        {
            $repsonse = array();
           
            $checked  = false;
            $value    = false;

            if (Input::method() == 'POST')
            {   
                // take the POST value
                if(Input::post($property))
                {
                    $checked = 'checked';
                    $value   = 1;
                }
            }
            else
            {
                // take the DB value
                if (isset($object->$property) && $object->$property == 1)
                {
                    $checked = 'checked';
                    $value   = $object->$property;
                }
            }

            if ($withValue)
            {
                $response['checked'] = $checked;
                $response['value']   = $value;

                return $response;
            }
           
            return $checked;
        }

    and in the View I use it like this :
    $chk = Helper::isChecked($myObject, $desiredProperty) : false;

    Form::checkbox($desiredProperty, Input::post($desiredProperty, 1), array('checked' => $chk));

    and it seems to do the job.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion