Symfony原则从表单中保存数据

时间:2015-10-27 11:08:12

标签: 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 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';
    }
}

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

谢谢

1 个答案:

答案 0 :(得分: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