gpt4 book ai didi

symfony - 如何从symfony表单处理程序中的表单中删除空值字段

转载 作者:行者123 更新时间:2023-12-04 23:55:23 24 4
gpt4 key购买 nike

我想在两种情况下更新数据:

  • 当用户输入表单中的所有字段时(姓名、电子邮件、密码)
  • 当用户不输入密码时(我只需要更新姓名和电子邮件)。

  • 我有以下 formHandler方法。
    public function process(UserInterface $user)
    {
    $this->form->setData($user);

    if ('POST' === $this->request->getMethod()) {

    $password = trim($this->request->get('fos_user_profile_form')['password']) ;
    // Checked where password is empty
    // But when I remove the password field, it doesn't update anything.
    if(empty($password))
    {
    $this->form->remove('password');
    }

    $this->form->bind($this->request);

    if ($this->form->isValid()) {
    $this->onSuccess($user);

    return true;
    }

    // Reloads the user to reset its username. This is needed when the
    // username or password have been changed to avoid issues with the
    // security layer.
    $this->userManager->reloadUser($user);
    }

    最佳答案

    解决您的问题的一个简单方法是禁用密码字段的映射并手动将其值复制到您的模型中,除非它为空。示例代码:

    $form = $this->createFormBuilder()
    ->add('name', 'text')
    ->add('email', 'repeated', array('type' => 'email'))
    ->add('password', 'repeated', array('type' => 'password', 'mapped' => false))
    // ...
    ->getForm();

    // Symfony 2.3+
    $form->handleRequest($request);

    // Symfony < 2.3
    if ('POST' === $request->getMethod()) {
    $form->bind($request);
    }

    // all versions
    if ($form->isValid()) {
    $user = $form->getData();

    if (null !== $form->get('password')->getData()) {
    $user->setPassword($form->get('password')->getData());
    }

    // persist $user
    }

    如果您希望保持 Controller 清洁,您还可以将此逻辑添加到表单类型中:
    $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormInterface $form) {
    $form = $event->getForm();
    $user = $form->getData();

    if (null !== $form->get('password')->getData()) {
    $user->setPassword($form->get('password')->getData());
    }
    });

    关于symfony - 如何从symfony表单处理程序中的表单中删除空值字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219760/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com