Yii CHtml :: checkboxList上的自定义属性

时间:2015-09-24 12:55:34

标签: php html checkbox yii

是否可以在CHtml :: checkboxList上创建自定义HTML属性?

例如,我想生成这样的输入,添加自定义属性" data-input-x":

<input class="customClass" id="Model_inputX_0" value="1" name="Model[relationX][]" type="checkbox" data-input-x="3">

我已经尝试过使用下面的代码,但是没有用:

echo $form->checkboxList($model, 'relationX', $dataList, array('class'=>'checkboxFase refeicaoFaseComum', 'data-input-x'=>3));

2 个答案:

答案 0 :(得分:0)

如果您运行代码并检查元素,您将看到Yii创建的值的值,差异。在foreach循环下的回声将很好地工作..

答案 1 :(得分:0)

您可以像这样扩展CHtml: 在文件夹“components”中,您将创建一个名为MyCHtml的新文件。在那里创建类MyCHtml并复制checkBoxList(https://github.com/yiisoft/yii/blob/1.1.16/framework/web/helpers/CHtml.php#L1123)框架的核心代码。

class MyCHtml extends CHtml {
//Final method is provided below
}

然后在$ htmlOptions = array()之后添加参数$ extraAttributes = array()。 诀窍是在每个输入的$ htmlOptions数组中添加这些属性及其值。

如果您的所有配置都正确并且您可以正常访问您的组件,则可以像这样调用新的checkBoxList函数:

<?php 
//Values can be created dynamically or statically depending on situation
//Each value corresponds to each checkbox value that you want to contain the extra attribute
$extraAttributes = array(
    'data-input-x'=>array(
        6=>'k',
        11=>'a',
        7=>'b'),
    'data-input-y'=>array(
        6=>'c',
        2=>'d'),
);
echo MyCHtml::checkboxList(($name, $select, $data, $htmlOptions, $extraAttributes); 
?>

全班如下:

<?php
class MyCHtml extends CHtml
{
    /**
    * Generates a list box.
    * ...
    * @param array $extraAttributes extra HTML attributes corresponding on each checkbox
    * ...        
    */

   public static function checkBoxList($name,$select,$data,$htmlOptions=array(), $extraAttributes=array())
    {
        $template=isset($htmlOptions['template'])?$htmlOptions['template']:'{input} {label}';
        $separator=isset($htmlOptions['separator'])?$htmlOptions['separator']:self::tag('br');
        $container=isset($htmlOptions['container'])?$htmlOptions['container']:'span';
        unset($htmlOptions['template'],$htmlOptions['separator'],$htmlOptions['container']);
        if(substr($name,-2)!=='[]')
            $name.='[]';
        if(isset($htmlOptions['checkAll']))
        {
            $checkAllLabel=$htmlOptions['checkAll'];
            $checkAllLast=isset($htmlOptions['checkAllLast']) && $htmlOptions['checkAllLast'];
        }
        unset($htmlOptions['checkAll'],$htmlOptions['checkAllLast']);
        $labelOptions=isset($htmlOptions['labelOptions'])?$htmlOptions['labelOptions']:array();
        unset($htmlOptions['labelOptions']);
        $items=array();
        $baseID=isset($htmlOptions['baseID']) ? $htmlOptions['baseID'] : self::getIdByName($name);
        unset($htmlOptions['baseID']);
        $id=0;
        $checkAll=true;             
        foreach($data as $value=>$labelTitle)
        {            
            $checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
            $checkAll=$checkAll && $checked;
            $htmlOptions['value']=$value;
            $htmlOptions['id']=$baseID.'_'.$id++;

            //********This does the trick       
            foreach($extraAttributes as $attributesKey => $attributesValue) {
                $found = false;
                foreach($attributesValue as $subAttributesKey => $subAttributesValue) {                    
                    if ($value === $subAttributesKey) {
                        $htmlOptions[$attributesKey] = $subAttributesValue;
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    $htmlOptions[$attributesKey] = '';
                }
            }
            //********All the rest is the same with core method

            $option=self::checkBox($name,$checked,$htmlOptions);            
            $beginLabel=self::openTag('label',$labelOptions);
            $label=self::label($labelTitle,$htmlOptions['id'],$labelOptions);
            $endLabel=self::closeTag('label');
            $items[]=strtr($template,array(
                '{input}'=>$option,
                '{beginLabel}'=>$beginLabel,
                '{label}'=>$label,
                '{labelTitle}'=>$labelTitle,
                '{endLabel}'=>$endLabel,
            ));
        }        
        if(isset($checkAllLabel))
        {
            $htmlOptions['value']=1;
            $htmlOptions['id']=$id=$baseID.'_all';
            $option=self::checkBox($id,$checkAll,$htmlOptions);
            $beginLabel=self::openTag('label',$labelOptions);
            $label=self::label($checkAllLabel,$id,$labelOptions);
            $endLabel=self::closeTag('label');
            $item=strtr($template,array(
                '{input}'=>$option,
                '{beginLabel}'=>$beginLabel,
                '{label}'=>$label,
                '{labelTitle}'=>$checkAllLabel,
                '{endLabel}'=>$endLabel,
            ));
            if($checkAllLast)
                $items[]=$item;
            else
                array_unshift($items,$item);
            $name=strtr($name,array('['=>'\\[',']'=>'\\]'));
            $js=<<<EOD
jQuery('#$id').click(function() {
    jQuery("input[name='$name']").prop('checked', this.checked);
});
jQuery("input[name='$name']").click(function() {
    jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
});
jQuery('#$id').prop('checked', !jQuery("input[name='$name']:not(:checked)").length);
EOD;
            $cs=Yii::app()->getClientScript();
            $cs->registerCoreScript('jquery');
            $cs->registerScript($id,$js);
        }
        if(empty($container))
            return implode($separator,$items);
        else
            return self::tag($container,array('id'=>$baseID),implode($separator,$items));
    }

    public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())
    {
        self::resolveNameID($model,$attribute,$htmlOptions);
        $selection=self::resolveValue($model,$attribute);
        if($model->hasErrors($attribute))
            self::addErrorCss($htmlOptions);
        $name=$htmlOptions['name'];
        unset($htmlOptions['name']);
        if(array_key_exists('uncheckValue',$htmlOptions))
        {
            $uncheck=$htmlOptions['uncheckValue'];
            unset($htmlOptions['uncheckValue']);
        }
        else
            $uncheck='';
        $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array('id'=>false);
        $hidden=$uncheck!==null ? self::hiddenField($name,$uncheck,$hiddenOptions) : '';
        return $hidden . self::checkBoxList($name,$selection,$data,$htmlOptions);
    }

   /**
    * Generates a push Html button that can submit the current form in POST method.
    * @param string $label the button label
    * @param mixed $url the URL for the AJAX request. If empty, it is assumed to be the current URL. See {@link normalizeUrl} for more details.
    * @param array $ajaxOptions AJAX options (see {@link ajax})
    * @param array $htmlOptions additional HTML attributes. Besides normal HTML attributes, a few special
    * attributes are also recognized (see {@link clientChange} and {@link tag} for more details.)
    * @return string the generated button
    */
   public static function ajaxSubmitHtmlButton($label,$url,$ajaxOptions=array(),$htmlOptions=array())
   {
           $ajaxOptions['type']='POST';
           $htmlOptions['type']='submit';
           return self::ajaxHtmlButton($label,$url,$ajaxOptions,$htmlOptions);
   }
}