How to set form action in Symfony2? (2.8 LTS) - symfony

So I've been playing around with Symfony forms and I want to change the form action.
I've followed this guide but I don't understand what it means by "target_route". As such, I was getting an error message (see below)
I have the code below and I'm pretty sure the route I used in setAction is valid since I can browse it using my browser.
Any ideas? Thank you
my code:
<?php
// src/AppBundle/Controller/DirectoryController.php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class DirectoryController extends Controller {
/**
* #Route("/directory/form")
*/
public function formAction() {
$form = $this->get("form.factory")
->createNamedBuilder("form", "form")
->setAction($this->generateUrl("/directory/search"))
->setMethod("get")
->add("search", "submit", array("label" => "Search"))
->add("reset", "reset", array("label" => "Reset"))
->getForm();
return $this->render(
"directory/form.html.twig",
array("form" => $form->createView()
,
)
);
}
/**
* #Route("/directory/search")
*/
public function searchAction() {
return $this->render(
"directory/view.html.twig"
);
}
}
error message:
Unable to generate a URL for the named route "/directory/search" as such route does not exist.

In the example, target_route is the name of a route, not its url. For example, you might define an action like this:
/**
* #Route("/directory/search", name="directory_search")
*/
public function searchAction() {
In that case, your route would have a name of directory_search. You would then use $this->generateUrl('directory_search') to have the router turn the name into a url.
The reason you do it this way (as opposed to using urls directly) is that this allows you to change a url without having to change every place in your code that references it.
->setAction($this->generateUrl("/directory/search"))
setAction() expects a url. So you while you can give it '/directory/search', best practice would be to it $this->generateUrl('directory_search').

Related

Symfony EventSubscriber: The Page isn't redirecting properly

I have been recently researching EventListeners for the kernal for Symfony4 and I thought I had grasped the basic concept of it but I seem to get a page isn't redirecting properly issue with my EventSubscriber.
Essentially I'd like to do the following logic:
if file_exists $file
redirect to file
else
carry on as normal
Which is how I originally came to kernel.response. Here is my current code:
<?php
namespace App\EventSubscriber;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class MaintenanceSubscriber implements EventSubscriberInterface
{
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if (file_exists('maintenance.flag')) {
$response = new RedirectResponse('maintenance');
$event->setResponse($response);
}
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => 'onKernelResponse'
);
}
}
this does my logic more or less perfectly, when maintenance.flag doesn't exist it carries on the project as expected, but when I touch maintenance.flag it gets the infamous Firefox page of Page isn't redirecting properly.
I'm not sure if I'm missing something?
I've set up my route:
maintenance:
path: /maintenance
controller: App\Controller\Maintenance\FlagController::flag
which is just a render function - I have a feeling that this could be causing the issue (an endless loop of redirect to flag() which then performs the before action?) but I'm not sure how to render my template from the setResponse() method
Even with the routing conf commented out, I still get the error. So not 100% sure anymore that it's the flag() endless loop theory
I was right indeed about the endless loop being the issue, adding this conditional to exclude the /maintenance url got it to work:
if (strpos($event->getRequest()->getRequestUri(), 'maintenance') !== false) {
return;
}

How to create a form using block module in drupal 8?

I want build a form using a block module in Drupal 8. I am aware of building the forms in Drupal 7 but the same seems to be different in Drupal 8.
Request anyone who has worked on drupal8 custom forms as block to help me.
Your question is very vague, as I don't know how much you already know about modules, forms and blocks in Drupal 8. So here is a small guide what to do, further information on how to do stuff in detail would be overkill for this answer.
1. Create a new module and enable it
Look here: Naming and placing your Drupal 8 module.
Basically you create the module folder and the module info yml file to let Drupal know about the module. Then you enable it using drush or the admin area in Drupal.
2. Create the form
Look here: Introduction to Form API.
under your_module/src/Form you create the form. More details in the link above.
3. Create the block and render the form
Look here: Create a custom block.
under your_module/src/Plugin/Block/ you create the block which will render the form.
The idea is basically (code updated with suggestion from Henrik):
$builtForm = \Drupal::formBuilder()->getForm('Drupal\your_module\Form\Your‌​Form');
$renderArray['form'] = $builtForm;
return $renderArray;
Note: You don't need to wrap the $builtForm with the $renderArray, you can return just the $builtForm and be fine. I just personally like to do it that way, because often times I need to add something else to the final render array like some markup, cache settings or a library etc.
4. Place the block
Place the block in the desired region(s). Done.
To build a form using block module, you can easily use Webform module where you can add a form and display as a block.
If you mean to create a form programatically in the custom block, you can achieve that by creating two files shown below:
Form file (src/Form/DemoForm.php):
<?php
/**
* #file
* Contains \Drupal\demo\Form\DemoForm.
*/
namespace Drupal\demo\Form;
use Drupal\Core\Form\FormBase;
class DemoForm extends FormBase {
/**
* {#inheritdoc}.
*/
public function getFormId() {
return 'demo_form';
}
/**
* {#inheritdoc}.
*/
public function buildForm(array $form, array &$form_state) {
$form['email'] = array(
'#type' => 'email',
'#title' => $this->t('Your .com email address.')
);
$form['show'] = array(
'#type' => 'submit',
'#value' => $this->t('Submit'),
);
return $form;
}
/**
* {#inheritdoc}
*/
public function validateForm(array &$form, array &$form_state) {
$values = $form_state->getValues();
if (strpos($values['email'], '.com') === FALSE ) {
$form_state->setErrorByName('email', t('This is not a .com email address.'));
}
}
/**
* {#inheritdoc}
*/
public function submitForm(array &$form, array &$form_state) {
drupal_set_message($this->t('Your email address is #email', array('#email' => $form_state['values']['email'])));
}
}
Source: Building a Drupal 8 Module: Blocks and Forms.
Block file (src/Plugin/Block/HelloBlock.php):
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'Hello' Block.
*
* #Block(
* id = "form_block",
* admin_label = #Translation("My form"),
* category = #Translation("My Category"),
* )
*/
class HelloBlock extends BlockBase {
/**
* {#inheritdoc}
*/
public function build() {
$form = \Drupal::formBuilder()->getForm('\Drupal\mymodule\Form\HelloBlock');
//$form['#attached']['js'][] = drupal_get_path('module', 'example') . '/js/example.js';
//$form['#markup'] = $this->t('Custom text');
return $form;
}
}
Source: Create a custom block.
To add a form to the Block Configuration, see: Add a Form to the Block Configuration.
Here is a detailed summary of how to go about this:-
https://www.sitepoint.com/building-drupal-8-module-blocks-forms/
Following the above guide, you would add the completed form to the block build function, e.g.
class DemoBlock extends BlockBase {
/**
* {#inheritdoc}
*/
public function build() {
$form = \Drupal::formBuilder()->getForm('Drupal\demo\Form\DemoForm');
return $form;
}
}
Some more useful docs if you are new to Drupal 8 or need to dust off your knowledge:
https://www.drupal.org/docs/8/creating-custom-modules
https://www.drupal.org/docs/8/api/block-api
https://www.drupal.org/docs/8/api/form-api

How can I render a controller action within a twig extension?

I do have a twig extension which has a method that uses another method from a different controller to render a json output via dependency jsonResponse.
How can I render a controller within a twig extension?
The following code below doesn't seem to work, because render() needs a view file instead of a controller. And I am now referencing to a controller.
class AreaExtension extends \Twig_Extension {
public function add()
{
$outputJson = $this->container->get('templating')->render(new ControllerReference('CMSCoreBundle:Area:index'));
}
}
$ref = new ControllerReference('CMSCoreBundle:Area:index');
$this->handler->render( $ref, 'inline', $options );
Where $this->handler is the fragment.handler service.
In your case:
$outputJson = $this->container->get('fragment.handler')->render(new ControllerReference('CMSCoreBundle:Area:index'));
You can find a full example in this symfony twig extension, see:
https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php#L28
and
https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php#L41

Global values: Define as service or define abstract Controller class?

In my Symfony2 app, I want to globally fetch a value from my database on each template and don't want to call on each Controller. I know I could define that as a service and inject that service into my twig templates (by defining it as a twig global).
Is that the common and recommended way? Or should I rather create an abstract Controller class where I fetch that value in my constructor and then inherit from all my other Controllers?
Note: It is actually not a static value that is the same for all users, but it is a user specific value which is different for each user.
If this variables are used to render the same spot on your page you can render an embedded controller. Like this:
<div id="sidebar">
{{ render(controller('YourBundle:User:stats')) }}
</div>
This will inject whole output of YourBundle/UserController/statsAction to the #sidebar div. Inside this action you can extract all inforamtion that you need.
If you need to use this variables in other way maybe you should look at response event.
Are you familiar with event listeners? http://symfony.com/doc/current/cookbook/service_container/event_listener.html
An event listener can be used to inject twig globals.
class ModelEventListener extends ContainerAware implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => array(
array('doProject', -1300),
),
KernelEvents::VIEW => array(
array('doView', -2100),
),
);
}
public function doProject(FilterControllerEvent $event)
{
$project = $whatever_is_needed_to_find_the_project();
if (!$project) throw new NotFoundHttpException('Project not found ' . $projectSearch);
// Add to request
$event->getRequest()->attributes->set('project',$project);
// Give all twig templates access to project
$twig = $this->container->get('twig');
$twig->addGlobal('project',$project);
}
# services.yml
cerad_core__model__event_listener:
class: '%cerad_core__model__event_listener__class%'
calls:
- [setContainer, ['#service_container']]
tags:
- { name: kernel.event_subscriber }
If it's a user value like you said you can get app.user.XXX on every twig template you need without processing nothing ;)

How can I set the url for the form to POST using the FormBuilder in Symfony2?

I'm dynamically loading different form classes in my Controller and displaying them in my template. This works fine, except that the Symfony2 docs show adding the route for the form to POST to in the template by hand.
<form action="{{ path('task_new') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<input type="submit" />
</form>
I need to set that form action in the FormBuilder class-- the POST routes (e.g. 'task_new') are different depending on the form class I'm using. Is there a way to set the form action url in the FormBuilder class? How can we get {{ form_widget(form) }} to render the complete form, and not just the rows? Thanks!
It is possible out of the box -- http://symfony.com/doc/current/book/forms.html#changing-the-action-and-http-method
$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
I had the same problem. I was using a simple FormType class and wanted to set the action url in buildForm function. I tried different things, but couldn't do it that way.
Eventually I used a Form option called 'action'. I don't think it's documented in the Symfony Reference, I have found it by accident while reading some error report :).
You can set the option when creating the form within your controller like this:
$form = $this->createForm(new FormType(), $obj, array( 'action' => 'whatever you want'));
It's not as pretty as having it encapsulated in the form class, but it works..
I hope this helps.
It's bad practice to change submit route in form type. It not form type responsibility. If you added form from not handle form route, you can just change action url in template:
{{ form_start(yourForm,{action:path('yourSubmitRoute')}) }}
I solved this problem by injecting the router into my form type. In my application I have created a zip code search form called ZipCodeSearchType:
Form Class
use Symfony\Component\Form\AbstractType;
/*
* I'm using version 2.6. At this time 2.7 has introduced a
* new method for the Option Resolver. Refer to the documentation
* if you are using a newer version of symfony.
*/
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Routing\Router;
/**
* Class ZipCodeSearchType is the form type used to search for plans. This form type
* is injected with the container service
*
* #package TA\PublicBundle\Form
*/
class ZipCodeSearchType extends AbstractType
{
/**
* #var Router
*/
private $router;
public function __construct(Router $router)
{
//Above I have a variable just waiting to be populated with the router service...
$this->router = $router;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('zipCode', 'text', [
'required' => true,
])
/*
* Here is where leverage the router's url generator
*/
//This form should always submit to the ****** page via GET
->setAction($this->router->generate('route_name'))
->setMethod("GET")
;
}
...
}
The next step is to configure your form as a service, and let symfony know that you need the router service injected into your class:
Define Form as Service
/*
* My service is defined in app/config/services.yml and you can also add this configuration
* to your /src/BundleDir/config/services.yml
*/
services:
############
#Form Types
############
vendor_namespace.zip_search_form:
class: VENDOR\BundleNameBundle\Form\ZipCodeSearchType
arguments: [#router]
tags:
- { name: form.type, alias: zip_code_search }
Use It In Your Controller
/**
* #param Request $request
* #return Form
*/
private function searchByZipAction(Request $request)
{
...
$zipForm = $this
->createForm('zip_code_search', $dataModel)
;
...
}
I don't think it's possible out-of-box today (Mar 18 '12). You could, however, do something like this:
in your controller:
....
....
$post_route = null;
if ( $something ){
$post_route = "some_post_route";
}else if ( $something_else ){
$post_route = "some_other_post_route"
}else{
$post_route = "my_default_route";
}
....
....
return array(
'post_route' => $post_route
);
... and in you template:
<form action="{ path(post_route) }" method="post" {{ form_enctype(form) }}>
Similar approach would be to generate URL (not just route name) within your controller and pass it to template, in which case you don't need path function there.

Resources