I'm rendering a form programmatically. The following code works:
$addressForm = \Drupal::entityTypeManager()
->getStorage('profile')
->create(array('type' => 'customer', 'uid' => $uid));
$finalform = $this->entityFormBuilder()->getForm($addressForm);
However, it is rendering the form before hook_form_alter()
has been called.
For example, in hook_form_alter()
we added a #after_build
callback method and custom validations, but the changes made in these functions are not reflected in $finalform
.
How do I ensure hook_form_alter()
changes are made to the rendered output?
.module file
function custom_profile_form_profile_customer_add_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
$form['formtitle'] = array(
'#type' => 'markup',
'#weight' => -100,
'#markup' => '<h2>Old Address Form</h2>',
);
/* ....
.... */
}
function custom_profile_module_implements_alter(&$implementations, $hook) {
if ($hook == 'form_FORM_ID_alter') {
$group = $implementations['custom_profile'];
unset($implementations['custom_profile']);
$implementations['custom_profile'] = $group;
}
}
.routing.yml
I have created a new route for the Address page in /modules/custom/custom_profile/custom_profile.routing.yml,
commerce_add_address.get:
path: '/checkout/{uid}/customer/add'
defaults:
_controller: '\Drupal\custom_profile\Controller\newAddressBook::commerce_add_address'
options:
parameters:
uid:
type: integer
methods: [GET,POST]
requirements:
_permission: 'access content'
Controller
in src/Controller/newAddressBook.php file
public function commerce_add_address($uid) {
//To get profile Add Address form
$addressForm = \Drupal::entityTypeManager()
->getStorage('profile')
->create(array(
'type' => 'customer',
'uid' => $uid
));
$finalform = $this->entityFormBuilder()->getForm($addressForm);
$build['#theme'] = 'usernewaddress';
$build['#data'] = array();
$build['#data']['form'] = $finalform;
return $build;
hook_module_implements_alter()
code to your question.