加载配置文件表单时出现Symfony错误

时间:2017-08-18 17:47:41

标签: symfony-forms symfony-3.3

我在尝试加载个人资料实体的编辑表单时遇到此错误。

The form's view data is expected to be an instance of class AppBundle\Entity\Profile, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of AppBundle\Entity\Profile.

我想知道是否有人知道如何适应这一点。我正在使用配置文件控制器,用户和配置文件之间具有OneToOne关系。

这是我的配置文件控制器的代码,用于加载该表单

/**
 * @Route("/profile/edit", name="profile_edit")
 */
public function editAction(Request $request)
{

    $em = $this->getDoctrine()->getManager();
    $profileRepository = $em->getRepository(Profile::class);

    $user = $this->getUser();

    $profile = $profileRepository->getProfileByUserId($user->getId());

    $form = $this->createForm(ProfileType::class, $profile);

    $form->handlerequest($request);

    if( $form_.isSubmitted() && $form->isValid()) {

        $firstname = $form->get('firstname')->getData();
        $lastname = $form->get('lastname')->getData();

        $description = $form->get('description')->getData();

        $profile->setFirstname($firstname);
        $profile->setLastName($lastname);
        $profile->setDescription($description);

        $em->persist($profile);
        $em->flush();

        $this->addFlash('flash-profileeditted', 'You\'ve successfully updated your profile.');
        $this->redirectToRoute('profile_page');
    }

    return $this->render('profile/edit.html.twig', ['form' => createForm(), 'profile' => $profile]);
}

这是我的ProfileType :: class

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add('firstname', TextType::class, [ 'label' => 'Firstname', 'attr' => ['class' => 'form-control']])
    ->add('lastname', TextType::class, ['label' => 'Lastname', 'attr' => ['class' => 'form-control']])
    ->add('description', TextareaType::class, ['label' => 'In Your Own Words', 'attr' => ['class' => 'form-control']])
    ->add('user')
    ->add('submit', SubmitType::class, ['label' => 'Edit Profile', 'attr' => ['class' => 'btn btn-info']]);
}

/**
 * {@inheritdoc}
 */
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Profile'
    ));
}

/**
 * {@inheritdoc}
 */
public function getBlockPrefix()
{
    return 'appbundle_profile';
}

不确定此处还包含哪些内容,希望一切正常,并且可以在此代码中找到解决方案。

我还应该指出我正在使用FOSUserBundle。

提前致谢,

1 个答案:

答案 0 :(得分:0)

确定。我终于知道发生了什么。我使用Profile Repository按用户ID查找用户,但是返回了一个数组。所以我要做的就是使用这段代码:

  $profile = $profileRepository->findOneByUser($user->getId());

这实际上将Object作为AppBundle \ Entity \ Profile对象返回,然后可以使用它来填充表单。