facebook twitter hatena line email

Php/Symfony/Symfony2/form

提供: 初心者エンジニアの簡易メモ
2017年1月17日 (火) 16:25時点におけるAdmin (トーク | 投稿記録)による版 (form(create))

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

form追加

-src/Acme/HelloBundle/Resources/config/routing.yml

blog_create:
   path:     /blog/create
   defaults: { _controller: AcmeHelloBundle:Blog:create }
   methods:  [GET]
blog_store:
   path:     /blog/create
   defaults: { _controller: AcmeHelloBundle:Blog:store }
   methods:  [POST]

form(create)

src/Acme/HelloBundle/Controller/BlogController.php

   /**
    * Blog form
    * @Route("/create", name="blog_create")
    * @Method("GET")
    * @Template()
    */
   public function createAction(Request $request)
   {
       $blog = new Blog();
       $form = $this->createFormBuilder($blog)
           ->add('name', 'text')
           ->add('description', 'text')
           ->getForm();
       return array(
            'form' => $form->createView(),
       );
   }
   /**
    * Blog form post
    * @Route("/store", name="blog_store")
    * @Method("POST")
    * @Template()
    */
   public function storeAction(Request $request)
   {
       if ($request->getMethod() == 'POST') {
       $blog = new Blog();
       $form = $this->createFormBuilder($blog)
           ->add('name', 'text')
           ->add('description', 'text')
           ->getForm();
           $form->bindRequest($request);
           if ($form->isValid()) {
               // データベースへの保存など、何らかのアクションを実行する
               // return $this->redirect($this->generateUrl('store_success'));
           }
       }
   }

-Resources/views/Blog/create.html.twig

{% extends '::base.html.twig' %}
{% block body -%}
    <h1>Blog</h1>
        <form action="{{ path('blog_store') }}" method="post" {{ form_enctype(form) }}>
            {{ form_errors(form) }}
            {{ form_row(form.name) }}
            {{ form_row(form.description) }}
            {{ form_rest(form) }}
            <input type="submit" />
        </form>
        <a href="{{ path('blog') }}">
            Back to the list
        </a>
{% endblock %}

-src/Acme/HelloBundle/Resources/config/validation.yml

Acme\HelloBundle\Entity\Blog:
   properties:
       name:
           - NotBlank: ~
       description:
           - NotBlank: ~