-1

How to render custom form's $form['#action'] property in the controller's template when it actually contains some random string like form_id_66dbsfds ?

3
  • You ask "Does anyone know how to get this thing done?" What do you mean by "thing"? You also ask "How should I get form action path?" Do you want to change the form action path? This is not recommended because you would need to replicate all the form handling that Drupal gives you in order to be secure. Can you clarify what you are trying to do?
    – mradcliffe
    Commented Mar 14, 2016 at 19:26
  • Yes, there is no need to change the #action path.
    – Kevin
    Commented Mar 14, 2016 at 19:53
  • People, I was just making a form more customized by rendering fileds separately. When I tried to get action path from the form object I got that strange id string, but not the path. This is the problem. Solved by using current url, but I think there should be a way of getting form action from the form object. Just didn't manage to find out. Commented Mar 14, 2016 at 21:46

2 Answers 2

3

I tried below code to render form in my controller class and it is working fine

$form = \Drupal::formBuilder()->getForm('Drupal\hollywood\Form\Hollywood');
$form = \Drupal::service('renderer')->renderRoot($form);

$content['exposed_filter'] = array(
  '#markup' => $form,
);

return $content;

Drupal\hollywood\Form\Hollywood is a namespace of the class.

3
  • Yes, this works pretty great, but what if you want to customize form template and rendering fields separately from the form object. For example: <div>{{ form.name }}</div><div>{{ form.message }}</div> How to generate a form tag, with a proper action attribute ? Commented Mar 14, 2016 at 21:54
  • @EvgeniyMonakov did you ever find a solution to this? I would like to know how to do this as well.
    – user5013
    Commented Sep 3, 2017 at 19:39
  • I wrote a twig extension function for it. See the answer beneath. Commented Sep 6, 2017 at 11:51
1

Previous answer is not an answer for my question. 1. {{ form['#action'] }} returns a string, which is not a url string, this is some kind of a route, but url generator does not recognize it. 2. If there's a need to render a form separately by the fields in a template - never use #markup, always use #theme and variables. 3. I did this like that:

    $request = $this->getRequest();
    $route = $request->attributes->get('_route');
    $routeParams = $request->attributes->get('_raw_variables')->all();
    $currentPath = $this->get('url_generator')->generate($route, $routeParams);

To get a current url. And then:

<form id="{{ form['#id'] }}" accept-charset="UTF-8" method="{{ form['#method'] }}" action="{{ currentPath }}">

The question was - how to get a proper action string from the form object.

Not the answer you're looking for? Browse other questions tagged or ask your own question.