Error when trying to store the id of the multiple checkbox in database in yii

68 Views Asked by At

I had multiple check box to view the Hobby names from database, and it's working. But i need to store the selected id of the hobby names in the database. But when i select any hobby name it stores only 0 in my database table.

I had one Hobbies table and i created one model for that also. Please anybody help.

This is in views/sample/register.php file

<?php
/* @var $this SampleController */
/* @var $model Sample */
/* @var $form CActiveForm */
?>

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
 'id'=>'sample-register-form',
'htmlOptions' => array(
    'enctype' => 'multipart/form-data',
),
'enableClientValidation'=>true,
'clientOptions'=>array(
    'validateOnSubmit'=>true,)
)); ?>

<p class="note">Fields with <span class="required">*</span> are required.</p>

<?php echo $form->errorSummary($model); ?>

<div class="row">
    <?php echo $form->labelEx($model,'username');
    echo $form->textField($model,'username');
    echo $form->error($model,'username'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'email');
    echo $form->textField($model,'email');
    echo $form->error($model,'email'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'password');
    echo $form->passwordField($model,'password');
    echo $form->error($model,'password'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'confirm password');
    echo $form->passwordField($model,'password');
    echo $form->error($model,'password'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'address');
    echo $form->textArea($model,'address',array('rows'=>6, 'cols'=>22));
    echo $form->error($model,'address'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'country');
    $opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
    echo $form->dropDownList($model,'country_id',$opts,
        array(
                'prompt'=>'Select Country',
                'ajax' => array(
                'type'=>'POST',
                'url'=>CController::createUrl('Sample/Substate'),
                'update'=>'#state_name',
                'data'=>array('country_id'=>'js:this.value'),
                 )));
    echo $form->error($model,'country_id'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'state_id');
    echo CHtml::dropDownList('state_name','', array('prompt'=>'Select Country First'),
        array(
            'ajax'=>array(
            'type'=>'POST',
            'url'=>CController::createUrl('Sample/Subcity'),
            'update'=>'#city_name',
            'data'=>array('state_id'=>'js:this.value' ))));
    echo $form->error($model,'state_id'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'city_id');
    echo CHtml::dropDownList('city_name','', array('prompt'=>'Select State First'));
    echo $form->error($model,'city_id'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'url');
    echo CHtml::activeFileField($model, 'url');   // by this we can upload image
    echo $form->error($model,'url'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'hobby');
    //echo $form->checkBoxList($model,'hobby',CHtml::listData(Hobbies::model()->findAll(),'hobby_id','hobby_name'));
    $data = Hobbies::model()->findAll();
    foreach($data as $button)
    {
        //echo $button->course_name;
        echo $form->checkBox($model,'hobby');
        echo $button->hobby_name .'<br>';
    }
    echo $form->error($model,'hobby'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'gender');
    echo $form->radioButtonList($model,'gender',array('Male'=>'Male','Female'=>'Female'),array('labelOptions'=>array('style'=>'display:inline'), // add this code
        'separator'=>' ',
) );
    echo $form->error($model,'gender'); ?>
</div>

<div class="row">
    <?php echo $form->labelEx($model,'dob');

    $form->widget('zii.widgets.jui.CJuiDatePicker', array(
   'model'=>$model,
   'attribute'=>'dob',
   'name'=>$model->dob,
   'value'=>$model->dob,
   'options'=>array('dateFormat'=>'yy-mm-dd',
                   'altFormat'=>'yy-mm-dd',
                   'changeMonth'=>'true',
                   'changeYear'=>'true',
                   'yearRange'=>'1600:3000',
                  // which shows for both textfield and button
                   //'showOn'=>'both',
                 //  'buttonText'=>'choose date'
                   ),
   'htmlOptions'=>array('size'=>'10')
 ));
    echo $form->error($model,'dob');
?>
</div>

<div class="row buttons">
    <?php echo CHtml::submitButton('Register'); ?>
</div>

<?php $this->endWidget(); ?>

This is in controller/SampleController.php file

public function actionRegister()
{
    $model=new Sample;

        if(isset($_POST['Sample']))
        {
            $model->attributes=$_POST['Sample'];
            if($model->validate())
            {
                $model->hobby = implode(",",$model->hobby);
                    if($model->save())
                    {
                        $this->redirect(array('site/login'));
                    }
                return;
            }
        }
        $this->render('register',array('model'=>$model));
}
1

There are 1 best solutions below

3
topher On

If you view the html generated by your foreach loop you will see that all your checkboxes have the same name and id. As such only one of them will be present in the $_POST array since the name is used as the key.

To fix this change the name to an array:

echo $form->checkBox($model, 'hobby[]');

Alternatively you can use CActiveForm::checkBoxList as in your commented code and use template to style it:

template: string, specifies how each checkbox is rendered. Defaults to "{input} {label}", where "{input}" will be replaced by the generated check box input tag while "{label}" will be replaced by the corresponding check box label.

echo $form->checkBoxList(
    $model, 
    'hobby', 
    CHtml::listData(Hobbies::model()->findAll(), 'hobby_id', 'hobby_name'), 
    array('template' => '{input}{label}<br/>')
);