0

I'm looking to add a form inside a custom template.

opacsearchmodule.routing.yml

opacsearchmodule.route1:
  path: '/form-test/object-builder'
  defaults:
    _form: '\Drupal\opacsearchmodule\Form\opacSearchForm'
  requirements:
    _access: 'TRUE'

opacsearchmodule.login:
  path: '/form-login/object-builder'
  defaults:
    _form: '\Drupal\opacsearchmodule\Form\loginForm'
  requirements:
    _access: 'TRUE'

LoginForm.php

 public function buildForm(array $form, FormStateInterface $form_state)
  {
    // TODO: Implement buildForm() method.
    $form['#theme'] = 'front_page';

    $form['user_name'] = array(
      '#type' => 'textfield',
      '#title' => t(' '),
      '#label_display' => before,
      '#attributes' => array(
        'placeholder' =>  t(''),
        'style'=>'',
        'class' => ['form-control']
      ),
      '#required' => TRUE,

    );


    $form['password'] = array(
      '#type' => 'password',
      '#title' => t(' '),
      '#label_display' => before,
      '#attributes' => array(
        'placeholder' =>  t(''),
        'style'=>'',
        'class' => ['form-control']
      ),
      '#required' => TRUE,
    );

opacsearchmodule.module

function opacsearchmodule_theme($existing, $type, $theme, $path)
{
    return array(
        'opac_search'=> array(
            'variables'=>array('branches'=>NULL,'mattypes'=>NULL,'title'=>'','searchresults'=>NULL)
        ),
        'search_results'=> array(
            'variables'=>array('branches'=>NULL,'mattypes'=>NULL,'title'=>'','searchresults'=>NULL)
        ),
        'book_details'=> array(
          'variables'=>array('branches'=>NULL,'mattypes'=>NULL,'title'=>'','searchresults'=>NULL,'id'=>NULL)
        ),
      'category_page'=> array(
            'variables'=>array()
        ),

      'front_page' => array(
        'template' =>'front_page',
        'render element' => 'form'
      ),
    );
 }

The controller contains the following code.

 public function openLoginPage(){
    $form = \Drupal::formBuilder()->getForm('Drupal\opacsearchmodule\Form\loginForm');

    return [
      '#theme' => 'front_page',
      'form' => $form,
    ];
  }

The template filename is front-page.html.twig. If I open form using path registered inside routing.yml file, it works; if I try to use it inside a custom template it doesn't work.

  • As side note, you don't translate a space, and '#label_display' => before is not correct, in PHP. – kiamlaluno Feb 12 at 7:40
  • You are using #theme front_page twice. Since this template is defined in hook_theme() to handle the form elements use it only in the form build. Does it work if you remove it from the controller? If you want a template in the controller use a different one and then put the form in a template variable '#form' => $form, – 4k4 Feb 12 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.