【问题标题】:Symfony doctrine save data from formSymfony 教义从表单中保存数据
【发布时间】:2015-10-27 11:08:12
【问题描述】:

我正在尝试保存从表单获取的数据。

这是我的 UploadController.php

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Photo;

class UploadController extends Controller
{
    public function indexAction(Request $request)
    {
    $em = $this->getDoctrine()->getEntityManager();
    $authChecker = $this->get('security.authorization_checker');

    if(!$authChecker->isGranted('ROLE_USER')) {
        return $this->redirectToRoute('fos_user_security_login');
    }

    $form = $this->createForm('app_photo_upload', new Photo());

    $form->handleRequest($request);

    if($form->isValid()) {
       //save data
    }

    return $this->render('AppBundle::upload.html.twig', array('form' => $form->createView()));
    }
}

上传表单类型

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class UploadFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
    $builder->add('name', 'file', array('data_class' => null));
    $builder->add('title', 'text');
    $builder->add('description', 'text');
    }

    public function getName()
    {
        return 'app_photo_upload';
    }
}

如果表单有效,我应该保存表单中的数据。我应该使用哪些功能来保存表单中的数据?

谢谢

【问题讨论】:

标签: php forms symfony doctrine-orm


【解决方案1】:

这是标准的 addAction。

 public function addAction(Request $request) {

         $news = new News();

         $form = $this->createFormBuilder($news)
            ->add('title', 'text')
            ->add('body', 'text')
            ->add('save', 'submit')
            ->getForm();

         $form->handleRequest($request);    
         if ($form->isValid()) {
           $em = $this->getDoctrine()->getManager();
           $em->persist($news);
           $em->flush();
           return new Response('News added successfuly');
         }

         $build['form'] = $form->createView();
         return $this->render('FooNewsBundle:Default:news_add.html.twig', $build);
     }

因此,在您的情况下,您需要将表单创建更改为:

$photo = new Photo();
$form = $this->createForm('app_photo_upload', $photo);

然后:

if ($form->isValid()) {
  $em->persist($photo);
  $em->flush();
}

我强烈建议您使用 CRUD 生成器,然后研究它创建的标准操作: http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html

【讨论】:

  • 第一次改没必要,当前代码也是这样
  • 如您所见,您可以跳过第一个更改。直到现在我还不确定。感谢 Carlos Granados 明确表示。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
相关资源
最近更新 更多