当表单构建器尝试填充 select 语句时,我在尝试填充选择框时遇到了一个简单的问题,因为它输出一个数组而不是单个字符串。我相信我可能做错了,但是我到处找过,找不到解决本质的方法。
表单生成器类:
<?php
namespace Test'TesterBundle'Form'Type;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
use Symfony'Component'OptionsResolver'OptionsResolverInterface;
use Test'TesterBundle'Model'CategoryQuery;
use Test'TesterBundle'Model'CategoryPeer;
class ProductsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('ProductName')
->add('ProductDescription', 'textarea', array("required"=> false))
->add('ShortDescription', null)
->add('SKU', null)
->add('UnitWeight', null)
->add('UnitPrice', null)
->add('UnitLength', null)
->add('UnitHeight', null)
->add('UnitDepth', null)
->add('URL', null)
->add('MetaTitle', null)
->add('MetaDescription', null)
->add('MetaKeywords', null)
->add('ProductID', 'model', array(
'class' => 'Test'TesterBundle'Model'Productcategory',
'required' => false,
'multiple' => true,
'expanded' => false,
'label' => "Select form the below",
'query' => CategoryQuery::create()->select(array("CategoryName"))->orderByCategoryName(),
))
->add('save', 'submit')
->getForm();
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'validation_groups' => array('newProducts'),
'data_class' => 'Test'TesterBundle'Model'Products'
));
}
public function getName(){
return "Products";
}
}
当它尝试填充选择区域时,它显示以下错误:
警告:get_class() 期望参数 1 是对象,字符串在 /var/www/Test/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.php 256路
这是它显示的堆栈跟踪的一部分:
} elseif (method_exists($choice, '__toString')) {
$labels[$i] = (string) $choice;
} else {
throw new StringCastException(sprintf('A "__toString()" method was not found on the objects of type "%s" passed to the choice field. To read a custom getter instead, set the argument $labelPath to the desired property path.', get_class($choice)));
}
}
}
有谁知道我哪里出错了?我想选择一列并使用列名称的结果填充选择。如果我将查询更改为:
'query' => CategoryQuery::create()->orderByCategoryName(),
它用最后一条记录的所有列填充其中一个字段。谁能建议或指出我正确的方向?
构建
表单时,您似乎缺少 property
属性。如果没有它,构建器将尝试找到一个__toString()
函数,以便能够正确地将模型集合(通常是实体)抽象为列表。像这样:
function __toString() {
return $this->getName(); // Assuming $this->getName() exists
}
应该足够了。祝你好运!