Yii Framework Forum: checkboxList array index - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

checkboxList array index

#1 User is offline   GSTAR 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,058
  • Joined: 30-October 09

Posted 22 December 2017 - 06:22 PM

Is it possible to customise the array index generated by checkboxList()? For example:

<?php
$interests = [
    [
        'id' => 1,
        'title' => 'title1',
        'value' => 'value1',
    ],
    [
        'id' => 2,
        'title' => 'title2',
        'value' => 'value2',
    ],
];
?>

<?php echo $form->field($model, 'interests')->checkboxList($interests, [
    'item' => function($index, $label, $name, $checked, $value) {
        $return = '<div class="option">';
        $return .= Html::checkbox($name, $checked, ['value' => $label['value'], 'id' => 'option-' . $label['id']]);
        $return .= Html::label($label['title'], 'option-' . $label['id']);
        $return .= '</div>';
    },
]); ?>


The checkbox is generated as follows:

<input type="checkbox" name="Form[interests][]" value="1">


I want the following:

<input type="checkbox" name="Form[interests][title1]" value="1">


In other words, I want the array index to contain a value, rather than a zero-based numerical index.
0

#2 User is offline   alrazi 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,533
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 23 December 2017 - 02:35 PM

why don't you generate the name manually here is your example modified


'item' => function($index, $label, $name, $checked, $value) {
		$key = $interests[$index]['title'];
        $return = '<div class="option">';
        $return .= Html::checkbox("Form[interests][{$key}]", $checked, ['value' => $label['value'], 'id' => 'option-' . $label['id']]);
        $return .= Html::label($label['title'], 'option-' . $label['id']);
        $return .= '</div>';
    }

0

#3 User is offline   GSTAR 

  • Master Member
  • PipPipPipPip
  • Yii
  • Group: Members
  • Posts: 1,058
  • Joined: 30-October 09

Posted 29 December 2017 - 06:15 AM

@alrazi I was hoping for a more "elegant" way of doing it, but I suppose this will do for now. Thanks.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users