2013-04-07 89 views
1

在我的模型属性我有属性 - 规格:传递数组从形式

class Category extends CActiveRecord 
    { 
     private $_specifications = array(); 

     public function getSpecifications() 
     { 
        return $this->_specifications; 
     } 

     public function setSpecifications($specifications) 
     { 
        $this->_specifications = implode(', ', $specifications); 
     } 

所以我想规范是一个数组。

我的视图文件:

<div id="specifications" class="row"> 
    <?php echo $form->labelEx($model,'specifications'); ?> 
    <?php echo $form->textField($model,'specifications',array('rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][0]', 'class' => 'clonedInput')); ?> 
    <?php echo $form->textField($model,'specifications',array('rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][1]', 'class' => 'clonedInput')); ?> 
    <?php echo $form->error($model,'specifications'); ?> 
</div> 

当我发送的形式我得到一个错误:

htmlspecialchars() expects parameter 1 to be string, array given 
... 
public static function encode($text) 
84  { 
85   return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset); 
86  } 

我试图禁用编码:

<?php echo $form->textField($model,'specifications',array('encode'=>false, 'rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][0]', 'class' => 'clonedInput')); ?> 
<?php echo $form->textField($model,'specifications',array('encode'=>false, 'rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][1]', 'class' => 'clonedInput')); ?> 

但在这种情况下,这是另一个错误:

Array to string conversion 
... 
2216     $html .= ' ' . $name . '="' . ($raw ? $value : self::encode($value)) . '"'; 

有人可以给一个建议,我应该怎么做才能从窗体传递数组?谢谢。

回答

1

如何将数组传递给单个文本字段?它应该显示什么?

您可以为此创建一个虚拟属性。

在模型:

private $_specifications = array(); 

public function getSpecifications() 
{ 
    return implode(', ', $this->_specifications); 
} 

视图可以保持不变。

编辑:

当然,你需要一个二传手也一样,如果你想成为能够写入的属性。

public function setSpecifications($specifications) 
{ 
    $this->_specifications = explode(', ', $specifications); 
} 

请参考http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/

+0

那么我应该在哪里调用这个函数? – 2013-04-07 18:32:01

+0

没有地方,因为我写了'视图可以保持原样'。)当你指定它们时,Yii会自动检查变量和虚拟属性(getXyz)。你也可以编写'$ model = new MyModel(); echo $ model-> specifications;' – Tim 2013-04-07 18:36:11

+0

implode():传递的参数无效 – 2013-04-07 18:43:29

0

由于您specifications属性是一个数组,你应该简单地做一个循环来显示相应输入端,例如:

foreach ($model->specifications as $s) 
{ 
    echo Chtml::textField('Category[specifications][]', $s, array('rows'=>6, 'cols'=>50, 'class' => 'clonedInput')); 
} 
0
<?php echo $form->textField($model,'specifications',array('encode'=>false, 'rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][0]', 'class' => 'clonedInput')); ?> 
<?php echo $form->textField($model,'specifications',array('encode'=>false, 'rows'=>6, 'cols'=>50, 'name'=>'Category[specifications][1]', 'class' => 'clonedInput')); ?> 

我认为规范将被显示两次。