Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

cakephp: How to set checkbox to checked?

I am using

$form->input('Model.name', array('multiple'=>'checkbox');

I am trying to base on model data to set certain checkboxes to checked.

How can i do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

cmptrgeekken's solution works for a single checkbox. I'm assuming you're generating a multiple checkboxes, for a HABTM relation or something similar.

You need to pass a array with the values of the elements that are going to be selected to the method, like this:

$options = array(1 => 'ONE', 'TWO', 'THREE');
$selected = array(1, 3);
echo $form->input('Model.name', array('multiple' => 'checkbox', 'options' => $options, 'selected' => $selected));

is going to generate this:

 <div class="input select">
      <label for="ModelName">Name</label>
      <input name="data[Model][name]" value="" type="hidden">

      <div class="checkbox">
           <input name="data[Model][name][]" checked="checked" value="1" id="ModelName1" type="checkbox">
           <label for="ModelName1" class="selected">ONE</label>
      </div>
      <div class="checkbox">
           <input name="data[Model][name][]" value="2" id="ModelName2" type="checkbox">
           <label for="ModelName2">TWO</label>
      </div>
      <div class="checkbox">
           <input name="data[Model][name][]" checked="checked" value="3" id="ModelName3" type="checkbox">
           <label for="ModelName3" class="selected">THREE</label>
      </div>
 </div>

The first and third checkbox checked.

Just remember that you're actually working with a multiple select element that is just displayed as a bunch of checkboxes (Which is IMO better because of the usability).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...