Php Symfony原则从表单保存数据

Php Symfony原则从表单保存数据,php,forms,symfony,doctrine-orm,Php,Forms,Symfony,Doctrine Orm,我试图保存从表单中获取的数据 这是我的UploadController.php <?php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use

我试图保存从表单中获取的数据

这是我的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()));
    }
}
如果表单有效,我应该保存表单中的数据。我应该使用哪些函数来保存表单中的数据


谢谢

这是标准的添加操作

 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生成器,然后研究它创建的标准操作:

您是否阅读过Symfony书中关于“条令与数据库”和“表格”的章节?就这些,你可能想读这篇文章:第一次更改是没有必要的,当前代码正在做同样的事情。当你看到OP时,你可以跳过第一次更改。我到现在还不确定。感谢卡洛斯·格拉纳多斯(Carlos Granados)的澄清。:)
if ($form->isValid()) {
  $em->persist($photo);
  $em->flush();
}