Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 PST on 31 March 2024, to get $100 off your ticket.
By aruntvla on
Hi,
I am trying to pass a drupal8 form to Twig template. For this I have created a Twig Extension and call the function from Twig Template. The issue I am facing was the form elements not rendering in Twig template. Also I have directly paste the form html code to Twig file this method also not working. Anyone please help me to resolve this issue.
Following are the code snippets I am using in my custom module.
My Twig Extension function:-
/**
* The php function to load a given block
*/
public function get_post_reply_form($cfeedid) {
// You can hard code configuration or you load from settings.
$form = \Drupal::formBuilder()->getForm('Drupal\example_feeds\Form\ExampleFeedsReplyPost');
$build = [
'#theme' => 'feed_post_reply_form',
'#form' => $form,
'#cfeedid' => $cfeedid
];
return $build;
}
My hook_theme implementation:-
function example_theme($existing, $type, $theme, $path) {
return array(
'feed_post_reply_form' => array(
'template' => 'feed_post_reply_form',
'render element' => 'form',
'variables' => array(
'cfeedid' => NULL,
'form' => NULL
),
),
);
}
My Drupal8 Form:-
public function buildForm(array $form, FormStateInterface $form_state, $cfeedid = NULL) {
$config = \Drupal::service('config.factory')->getEditable('example_feeds.settings');
$post_link = $config->get('example_feeds_post_link_text');
$custom_prompt_text = $config->get('example_feeds_custom_prompt_text');
$form['#attributes'] = array('class' => 'editForm editForm-thread');
//$form['#theme'] = ['feed_post_reply_form'];
$form['postfeed_reply_Message'] = array(
'#type' => 'textarea',
'#title' => t(''),
'#required' => TRUE,
'#attributes' => array('placeholder' => $custom_prompt_text )
);
$form['comment_id'] = array(
'#type' => 'hidden',
'#value' => $cfeedid
);
$form['submit_reply'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#attributes' => array('class' => 'btn btn-primary example-btn')
);
return $form;
}
My Twig Template code:-
{{ form.postfeed_reply_Message }}
{{ form.comment_id }}
{{ form.submit_reply }}
{{ cfeedid }}
Thanks,
Arun Chandran