我尝试从 CategoryType 表单中设置字段“作者”的值。我希望它是使用 FOS 包登录的当前用户的用户 ID。
我的 CategoryType 表格:
namespace My\CategoryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CategoryType extends AbstractType
{
private $userId;
public function __construct(array $userId)
{
$this->userId = $userId;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('author')
->add('content')
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\CategoryBundle\Entity\Category',
'auteur' => $this->userId
));
}
/**
* @return string
*/
public function getName()
{
return 'my_categorybundle_category';
}
}
我的控制器动作:
public function addAction()
{
$category = new Category;
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
$form = $this->get('form.factory')->create(new CategoryType(), array( 'author' => $userId));
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
return $this->redirect($this->generateUrl('mycategory_voir',
array('id' => $category->getId())));
}
}
return $this->render('MyCategoryBundle:Category:add.html.twig',
array(
'form' => $form->createView(),
));
}
我在运行操作时发现了这个错误:
可捕获的致命错误:传递给 My\CategoryBundle\Form\CategoryType::__construct() 的参数 1 必须是一个数组,没有给出,在第 55 行的 /My/CategoryBundle/Controller/CategoryController.php 中调用并在 /My/CategoryBundle 中定义/Form/CategoryType.php 第 13 行
我传递给表单的不是已经是一个数组吗?