Questions tagged as ['forms']

Use it for questions about the Form API. Don't use it for entity or entity field forms.
Score: 1
Can't save value of custom datetime field
in flag

I'm reaching out because I just can't find out why my custom datetime field isn't saving its value after I submit.


I've created a field containing two datetime fields. I will use it to add or remove events from an event list, depending on whether they have passed or not (for example if a festival is scheduled from the 12 to the 14 of December, the event will be removed after the 14th).

Events in  ...

Score: 0
Amine avatar
Time spent with custom module
us flag

Can anyone help me with this, I want to activate time spent module on my custom form module, and store the time spent on a field on my form. I think that I could do it on the file timespent.module here.

function time_spent_init() {
  //if user has a role who is going to be tracked, add javascript code
  if (time_spent_user_has_role()) {
    $timer = variable_get('time_spent_timer', TIME_SPENT_TIMER);
Score: 0
Amine avatar
Vertical tabs custom form Drupal7
us flag

I have a question to discuss about Vertical tabs on Drupal7 when we use it on custom module to make a form.

Can we use a vertical tabs on a another vertical tabs?

I know how we do to make a one vertical tabs but with one on another i think maybe one day we need it.

Score: 3
Baud avatar
How to not split select list by content type
sa flag

This is about the regular select widget that you can choose in the Manage form display page.

If this widget is linked to an entity_reference field allowing several bundles to be selected; then you end up with an #options populated as follow:

_none -> "None"
Bundle label 1 ->
  id1 -> "label of ID 1"
  id3 -> "label of ID 3"
  id4 -> "label of ID 4"
Bundle label 1 ->
  id5 -> "la ...
Score: 2
Baud avatar
How to alter the view behind a select widget in a regular node edit form
sa flag

I have an entity_reference field in a content type: field_node_ref

In the field definition, it can reference all the nodes of a given type.

The widget used for this field is a select widget

Depending the context, in the node edit form, I would like to use different views to populate the #options of the select widget.


Context A --> View A will be used

Context B --> View B will be used

The cont ...

Score: 1
Adding an "Accept Terms" checkbox on User Registration form
in flag

I need to add an "Accept terms and conditions" checkbox onto a user registration form. What is the best way to do this?

Also, it seems odd to me that there is no easy way to use radio buttons nor checkboxes on the User Registration form at admin/config/people/accounts/fields. Select lists are awkward, especially for multi-select lists on a mobile device.

Is there a way to output the list fields as ...

Score: 0
Amine avatar
custom module form radios fields & ajax problem
us flag

I have a custom form, that iI develop on a custom module to get some fields from a content type with an entity reference.

All is good, I can get all information, and I can save the chosen value on a field of content type.

My problem is: why is it that the first input radio doesn't save and show me the max, but I have 0 on the field like a value.

My code to create the field of form:

'#type' =&gt ...
Score: 0
Altering user_admin_account and user_register_form
ro flag

I'm pretty new to Drupal and I'm trying to build a Drupal 7 custom module to alter the user listings table in admin/people. I would like to display the first and last names of the users. I've already added the text fields to the user registration form in admin/config/people/account-settings/manage-fields and I've managed to store the user input in my database table. I've added the extra fields to the us ...

Score: 0
Jorn Reed avatar
Validation for radio inputs don't work for me
il flag

I'm building a form with the drupal forms api. Validation works well for all my other fields. But I've started to try and work with radio buttons too now. It doesn't matter if I click on a radio option, the validation returns always 'color is required'.

// Form build method code
$form['birthdate'] = [
  '#type' => 'date',
  '#title' => $this->t('Your date of birth'),
  '#date_date_format'  ...
Score: -1
Jorn Reed avatar
Formatting date field with the Form API
il flag

Hi there I'm using drupal 9.x and the forms api to generate a dynamic form. Altough I'm living in the Netherlands where the date format standard is 'dd/mm/yyyy'. I've looked around on the internet for recent ways to modify that format in the html input. But all ways seems to be deprecated cause they don't seem to work for me. I've tried stuff like:

$form['birthdate'] = [
  '#type' => 'date',
  ' ...
Score: 2
New To 'C' avatar
Block Settings inside Form
in flag

Please I need help with my code. I have a form and a block created programmatically. The block embeds the form to show it on the frontend. The block also has some settings (form preffix text). I want to load the block settings inside my buildForm in my Form.php to get the preffix text and show it in the form markup field. But I can't seem to find a way to pass on the $block_id to the buildForm() so it c ...

Score: 1
Bohus Ulrych avatar
Place field in "Url Alias" advanced group section (path-0)
jp flag

I'm trying to place my node field to the Advanced group - URL alias section. I'm doing it in custom hook_form_BASE_FORM_ID_alter(), where I'm trying to set custom #group like this:

$form['my_filed']['#group'] = 'path-0';

But "path-0" neither "path_0", "path" works. But if I use something else e.g. "meta", "menu" ... then my field is displayed in right place. What's the trick to place it in "Url Alias" ...

Score: 0
Use ajax to save modal / dialog form instead of page reload
kr flag

I'm looking for a way to save modal & dialog forms through ajax instead of redirecting the user after the form submit. Ajax is quite unknown territory to me.

I've found several interesting topics here already:

jQuery UI Dialog attempt to submit a form using AJAX redirects me to the actual form page instead of AJAX submitting

How to close modal after form submit?

I tried all answers shown there,  ...

Score: 0
Interlated avatar
How do I add a field to a node form?
km flag

The goal is to set a default counter, but let people override it. The counter should be the biggest value of the field plus 1.

Using an event subscriber, FORM ALTER event.

public static function getSubscribedEvents(): array {
  return [
    HookEventDispatcherInterface::FORM_ALTER => 'setDefaultCbid',
    HookEventDispatcherInterface::ENTITY_PRE_SAVE => 'checkCbiRaceCondition'

public fu ...
Score: 0
ilechcod avatar
Pager element not showing on form
in flag

I have a simple tableselect element inside my form and the tableselect rows are populated using a pager as follows:

$pagerLimit = 10; //default value if nothing is passed in
$query = $this->jobSkillStorage->getQuery();
$query->condition('type', $skillType);   
$ids = $query->execute();
$jobSkills = $this->jobSkillStorage->loadMultiple($ids);  

return ...
Score: 0
Drupal hubspot forms with Varnish
br flag

I have a Drupal 8 hubspot form built in a custom module which holds many fields among which a "Favorite Pizza" field coming from hubspot and this field is rendered as a required fieldset. The code is very long so I decided to explain to you the process instead:

  • In the Drupal buildForm function, we call an external hubspotbuildForm function
  • Inside this function, I collect the following cookie in php ...
Score: 2
liquidcms avatar
Why can't some fields be moved within details element?
us flag

I am trying to move 2 form fields to the advanced sidebar: dismissible and status. Status was already part of the meta container and setting #group='meta' on dismissable also placed it there; but these weren't in the proper order. Nothing I do seems to have any impact on:

  • dismissible
  • standard meta fields: published, author, revision log
  • status

Both dismissible and status are fields added by the

Score: 0
abelass avatar
Custom validation constraints multi value paragraphs : how to get weight value
nl flag

I am validating a multi value paragraph field using constraints.

 * Implements hook_entity_bundle_field_info_alter().
function cnfpt_internet_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($bundle === 'manifestation') {
    if (isset($fields['field_occurence'])) {
      // Add a validation.
      $fields['field_occurence'] ...
Score: 0
abelass avatar
Custom constraints validation of multi value paragraphs: highlighting missing field
nl flag

I am using constraint for the validation my multi value paragraph field.

I can correctly implement the different validation rules but I haven't found out how to highlight only the erroneous field(s).

Here is my violation declaration

       ->atPath((string) $delta . 'subform.field_modalite.0')
       ->addViolation( ...
Score: 0
Nathan Zim avatar
Build custom form with entity form field
de flag

I have a feature to migrate from Drupal 7 to Drupal 9. This allows me to build a custom form made up of static fields, which I define in the code of my module, and fields dynamically retrieved from an entity.

It worked with the "ctools_field_invoke_field function", which relies on the Chaos Tools module. This function is itself based on a native Drupal function "field_default_form".

This function wa ...

Score: 0
Using both Drupal Core Contact Form and contributed Webform module
th flag

I have a Drupal 8 site already utilizing core Contact Form. However, we now need a more complex form and thinking about installing a contributed module: Webform (

My concern is that having both Contact form and Webform enabled, will there be an issue like one impacting the other?


Score: 0
hotwebmatter avatar
Set ['#default_value'] of taxonomy term reference field via hook_form_alter()?
nr flag

Here's a different question with the same taxonomy term reference field I mentioned in my previous question.

Users with Administrator and Coach roles are granted permission to register Student users via a custom "Add student" form mode (user_add_student_form). It would be better for UX if I could set the ['#default_value'] of the select_a_school taxonomy term reference field to the same school that  ...

Score: 0
Controlling dropdown field visibility using #states API for dependent dropdown
cn flag

I have the following setup.


    '#type' => 'select',
    '#title' => $this->t('Dropdown one'),
    '#options' => $dropdownOneOptions,
    '#empty_option' => '---',
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getDropdownTwoOptions'],
      'wrapper' => 'dropdown-two',
      'progress' => [
        'type' =& ...
Score: -2
Nihal Kumbhalkar avatar
How to add anti csrf token to the forms (No Anti-CSRF tokens were found in a HTML submission form.)
cn flag

When i was testing my drupal 9 website for security i got the error as "No Anti-CSRF tokens were found in a HTML submission form." solution is given as "use anti-CSRF packages such as the OWASP CSRFGuard." but how to use these in drupal forms.

Score: 0
john Smith avatar
entity_form how to programmatically add references and update the form visually (entity_browser)
gr flag

I´m having an fieldable entity with a reference field to paragraphs field_paragraphs and a paragraph_type with a reference field to content_type event field_events.

What i am trying in the entity form is to have a button in the paragraph_type event subform which on click prefills the field_events of the paragraph_type with content. The form display of field_events uses an entity_browser to let the user  ...

Score: 0
Jeirod avatar
How to retrieve #tree values inside multiple containers?
cn flag

I am using Drupal 8 and I am creating multiple forms that are made of a #tree hierarchy.

I need to retrieving the value of the "first name" from the #tree using the below code and it doesn't get the value.

$firstName = $form_state->getValue('userBoxArea')[$count]['userBox']['nameBox']['firstName'];

This is my code:

protected static $formID;

public function getFormId() {
    if (empty(self::$form ...
Score: 2
Елин Й. avatar
How to return an XLS file to download on form submit
je flag

I am trying to create an XLS file and send it to the browser on a form submit but I cannot figure out how to do it. I am using XLS Serialization module but I'm open to all other suggestions. With this module I successfully created some views with XLS Export feature. But now I have a form and the excel file should be created on form submit depending on the submitted data.

I created the following c ...

Score: 0
Jeirod avatar
How to retrieve #tree values inside a form?
cn flag

I am new at Drupal 8 and I am creating a module that has a #tree form. I chose #tree form to create multiple forms which has the same textfields and button.

I came across one document in drupal about #tree.
I have made a researched about it and can't find any documentation, post or blog on how to get a specific value from #tree.

I have implemente ...

Score: 1
Jean da Silva avatar
Render responsive image inside form fields programmatically
cn flag

I am trying to figure out how to render a responsive image programmatically inside a form field. I am doing maintenance in a code on my current job, and sometimes there are form fields using the '#markup' property. Now I need to change all images to be responsive.

The code example:

$form['markup1'] = [
     '#markup' => '<div class="rating_reminder"><img src="'.file_create_url($order->c ...