Symfony 4更新具有关系的学说实体

问题描述 投票:0回答:1

我在更新应用程序中的Doctrine实体时遇到问题。

这是我的代码

public function put(Request $request, $id)
{
    $data = json_decode(
        $request->getContent(),
        true
    );

    /** @var Product $entity */
    $entity = $this->findOneById($id);

    $this->denyAccessUnlessGranted(BaseVoter::EDIT, $entity);

    $form = $this->createForm($this->formType, $entity);

    $form->submit($data);

    if (false === $form->isValid()) {
        return new JsonResponse(
            [
                'status' => 'error',
                'errors' => $this->formErrorSerializer->convertFormToArray($form),
            ],
            JsonResponse::HTTP_BAD_REQUEST
        );
    }

    /** @var Product $product */
    $product = $form->getData();
    $this->entityManager->persist($product);

我的问题来自表单处理数据提交的方式。一旦运行$form->submit()方法,我的持久实体也会更新,因此我只有新值,无法取消旧关系。

由于在submit过程中该实体似乎已经被保留(以一种隐藏的方式),即使我尝试再次从Doctrine中获取它,我仍然仅获得新值。

是否有很好的方法?

php forms symfony doctrine entity
1个回答
0
投票

我不知道您为什么要使用表单组件来执行此操作。这是一种更具API精神的替代方法,可让您对正在发生的事情有更多的控制权:

public function put(Request $request, $id)
{
    $data = json_decode(
        $request->getContent(),
        true
    );

    /** @var Product $entity */
    $entity = $this->findOneById($id);
    if (null === $entity) {
        throw new NotFoundHttpException();
    }

    $this->denyAccessUnlessGranted(BaseVoter::EDIT, $entity);

    foreach ($data as $property => $value) {
        try {
            $this->propertyAccessor->setValue($entity, $property, $value);
        } catch (\Exception $e) {
            // Handle bad property name, etc..
        }
    }

    $constraintsViolations = $this->validator->validate($entity);
    if (count($constraintsViolations) > 0) {
        return new JsonResponse(
            [
                'status' => 'error',
                'errors' => $constraintsViolations,
            ],
            JsonResponse::HTTP_BAD_REQUEST
        );
    }

    $this->entityManager->persist($entity);
    $this->entityManager->flush();

    return new JsonResponse(...);
}

这里我使用了另外两个组件,它们由form组件本身在引擎盖下使用:

  • 具有Symfony \ Component \ PropertyAccess \ PropertyAccessorInterface]的属性访问器>
  • 具有Symfony \ Component \ Validator \ Validator \ ValidatorInterface]的验证器]
  • 您将不得不从控制器构造函数中注入它。

    我希望它将对您有帮助!

此示例还不完整,您将不得不改进错误处理和响应。

© www.soinside.com 2019 - 2024. All rights reserved.