【问题标题】:Custom attributes on Yii CHtml::checkboxListYii CHtml::checkboxList 上的自定义属性
【发布时间】:2015-09-24 12:55:33
【问题描述】:

是否可以在 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));

【问题讨论】:

  • 它应该可以工作...您是否希望该列表的每个复选框输入的 data-input-x 值为 3?
  • 不,该值只是一个示例。该值需要是动态的
  • 啊,这样不行。无论您在 checkboxList 函数中为 data-input-x 设置什么值,都会为创建的每个复选框设置。
  • 不确定你的 $dataList 的格式,但也许一个 foreach 循环使用 CHtml::checkBox 创建复选框并以这种方式动态设置 data-input-x 对你有用。
  • 您可以使用 $model->somevalue 代替 3。当然,这对于编辑来说是有意义的。您可以在 $model->getSomevalue() 函数中发送默认值,或者使用三元 if ((!empty( $model->somevalue): $model->somevalue:'3'))

标签: php html checkbox yii


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以像这样扩展 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);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-21
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      相关资源
      最近更新 更多