$emailForm = $this->get('form.factory')->createNamedBuilder('form', 'email_form')
->add('email', 'email')
->add('subject', 'text')
->add('body', 'textarea')
->getForm();
$request = $this->get('request');
if ($request->getMethod() == 'POST' && $request->request->has('email_form')) {
$emailForm->bindRequest($request);
if ($emailForm->isValid()) {
// do stuff ...
$this->get('session')->setFlash('email_sent', "Woey, mail sent successfully!");
// Redirect on the same url to prevent double posts
return $this->redirect($this->generateUrl($this->getRequest()->attributes->get('_route')));
}
}
return $this->render('Bundle:Form:index.html.twig', array('email_form' => $emailForm->createView()));
템플릿
{% if app.session.getFlash('email_sent') %}
<p>{{ app.session.getFlash('email_sent') }}</p>
{% endif %}
<form action="{{ path(app.request.attributes.get('_route')) }}" method="post" {{ form_enctype(email_form) }}>
{{ form_widget(email_form) }}
<p><input type="submit" class="submit" value="Send" /></p>
</form>
튜토리얼과 거의 같은 표준 Symfony2 형식입니다.
나 자신을 반복하지 않고 (여러 컨트롤러 동작에서) 여러 페이지에서 효율적으로 사용할 수있는 방법을 생각할 수 없습니다. 지금까지 내가 시도 :
- 기본 컨트롤러,이 양식을 갖고 싶은 모든 컨트롤러에 대한 부모있는 로직을 가하고. 이 접근 방식에는 2 가지 문제가있었습니다.
- 동일한 페이지로 올바르게 리디렉션하는 방법을 파악할 수 없었습니다.
- 모든 작업에서 부모로부터 메소드를 호출해야했지만 실제로는 문제가되지 않았습니다.
- 렌더링 컨트롤러 (나뭇 가지에서 embedded controllers 사용). 그러나, 나는 how to redirect properly을 추측 할 수 없었다.
그런데 이러한 양식에 대한 일반적인 접근 방식은 무엇입니까?
편집 :
스크립트없는 솔루션을 찾고 있습니다.
이 블로그 게시물은 유사한 문제를 다룰 때 도움이됩니다. https://phpcoderblog.wordpress.com/2014/06/26/symfony2-using-same-form-for-all-pages-symfony2-put- symfony2-use-all-pages-symfony2-same-form-on-every-page-symfony2-how-to-use-contact-form-on-each-page-symfony2-how-to-use- contact-form-on-al/ – Sam