我正在尝试使用Silex创建一个Web应用程序。 对于我的应用程序,我有两个对象:Project()和Credential()。 项目()一:
protected function buildDomainObject($row)
{
$credential = new Credential();
$credential->setIdCred($row['idCred']);
$credential->setNameCred($row['nameCred']);
$credential->setToken($row['token']);
$project = new Project();
$project->setId($row['id']);
$project->setName($row['name']);
$project->setBranch($row['branch']);
$project->setCredential($credential);
$project->setComment($row['comment']);
$project->setAlive($row['alive']);
$project->setNumberTaskList($row['numberTaskList']);
return $project;
}
凭证一:
protected function buildDomainObject($row)
{
$credential = new Credential();
$credential->setIdCred($row['idCred']);
$credential->setNameCred($row['nameCred']);
$credential->setToken($row['token']);
return $credential;
}
如您所见,Project()在值凭据中包含Credential()。 将新的Project()对象传递给FormBuilder时没有问题。
public function addProjectAction(Request $request, Application $app)
{
$credentials = $app['credential_repository']->findAllAsArray();
$project = new Project();
$projectForm = $app['form.factory']->create(new ProjectType(), $project, ['credentialChoices' => $credentials]);
$projectForm->handleRequest($request);
if ($projectForm->isSubmitted() && $projectForm->isValid()) {
$app['project_repository']->save($project);
}
return $app['twig']->render('projectList_form.html.twig', array(
'title' => 'New project',
'legend' => 'New project',
'projectForm' => $projectForm->createView(),
)
);
}
当我尝试从数据库中获取Project()并将其传递给FormBuilder时,会出现问题。
$credentials = $app['credential_repository']->findAllAsArray();
$project = $app['project_repository']->find($id);
$projectForm = $app['form.factory']->create(new ProjectType(), $project, ['credentialChoices' => $credentials]);
我有以下错误:
“object”类型的值无法转换为有效的数组键。
我认为我的问题来自于Project()对象有一个包含Credential()对象的属性。
答案 0 :(得分:1)
我能够通过在buildForm方法中使用object属性来重新创建异常。
InvalidArgumentException in ArrayKeyChoiceList.php line 71: The value of type "object" cannot be converted to a valid array key.
您无法在credential
表单字段中使用choice
属性。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('credential', 'choice', array(
'choices' => $choices,
'multiple' => false,
'expanded' => false
))
->add('submit', 'submit')
;
}
您可以尝试将凭据ID属性添加到Project()。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('credentialId', 'choice', array(
'choices' => $choices,
'multiple' => false,
'expanded' => false
))
->add('submit', 'submit')
;
}
或者您可能需要按照此stackoverflow question
中的说明设置实体字段类型