carlmango11
carlmango11

Reputation: 525

Display boolean as radio button in CakePHP form

Does anyone know how to display two radio buttons in a form in CakePHP and have them save to a boolean field in the DB?

I can get my boolean value to display as a checkbox (default behaviour) but I need to display two radio buttons, however when I do this the changes don't get saved to the DB.

I feel like it's something very simple. Here's my code:

<h1>Edit Content</h1>

<?php
$thisVal = $this->data['LessonContent']['is_exercise'] ? "1" : "0";

$options = array(
    '0' => 'Learning Material',
    '1' => 'Exercise'
);

echo $this->Form->create('LessonContent', array('action'=>'edit'));
echo $this->Form->input('name', array('label' => 'Name'));
echo $this->Form->input('description', array('label' => 'Description'));

echo $this->Form->input('is_exercise', array(
    'type'      =>  'radio',
    'class'     =>  'radio',
    'legend'    =>  false,
    'name'      =>  'Type',
    'options'   =>  $options,
    'value'     =>  $thisVal
));

echo $this->Form->input('id', array('type'=>'hidden'));
echo $this->Form->input('lesson_id', array('type'=>'hidden'));
echo $this->Form->end('Save Content');
echo $this->Html->link('Cancel', array('controller'=>'Lessons', 'action'=>'view', $this->data['Lesson']['id']));
?>

Thanks

Upvotes: 1

Views: 2613

Answers (1)

thaJeztah
thaJeztah

Reputation: 29037

You're overriding the name of the input, therefore the value for is_excercise will be sent as Type.

Remove the name option;

echo $this->Form->input('is_exercise', array(
    'type'      =>  'radio',
    'class'     =>  'radio',
    'legend'    =>  false,
    'options'   =>  $options,
    'value'     =>  $thisVal
));

note after making this change, you probably don't even have to manually set the value of the radio-button.

debugging

In situations like this, always check/debug the posted form-data, either via FireBug or by debugging it in CakePHP, by putting this in your controller;

debug($this->request);

Even better, install the CakePHP DebugKit Plugin this plugin shows all the information (request data, queries, session variables etc.) without having to add debug-lines

Upvotes: 4

Related Questions