Score:0

How to replace default value of field?

cn flag

I have a custom module.

enter image description here This is form_alter function:

 $form['article'] = [
    '#type' => 'textfield',
    '#weight' => -1,
    '#title' => t('Search Product from Magento: '),
    '#autocomplete_route_name' => 'magento_drupal.autocomplete',
    '#ajax' => [
      'callback' => '_select_ajax_form',
      // 'wrapper' => 'my_unique_id',
    ],
  ];

In the _select_ajax_form function, how can I automatically fill in the data for the field 'price' and 'sku'?

price is Number (integer) and sku is Text (plain, long).

Score:0
in flag

If you don't have a huge backend logic for the auto-fillins, you may do it with much more simple javascript in the "#attributes" value. Here's a sample of my code:

$form['laufzeit_in_monaten'] = [
      '#type' => 'number',
      '#title' => $this->t('Laufzeit in Monaten ('.$produkt->get('min_stk')->value.' - '.$produkt->get('max_stk')->value.')'),
      '#default_value' => floor($produkt->get('max_stk')->value/2.0),
      '#attributes' => array('onchange' =>
        'document.getElementById("vollpreis").innerHTML = (document.getElementById("edit-laufzeit-in-monaten").value * document.getElementById("pprc").value).toFixed(2)'),
    ];

But this is only frontend. You obviously need to validate the input later in your backend.

Dong Pham avatar
cn flag
Thank you for your suggestion. But I have a huge backend logic, so I can't use js.
Dong Pham avatar
cn flag
I try #9 in [link]https://www.drupal.org/project/drupal/issues/1024962#comment-13261018 , but not working. I don't understand ['und'] and can't set value for $form['field_name]['und']
Rainer Feike avatar
in flag
I think #9 is for D7...
Rainer Feike avatar
in flag
But you could set up a rest service for your huge backend logic and still use JS in the frontend.
Dong Pham avatar
cn flag
I did it. I used "wrapper" and "container". But drupal has to be updated to version 9.1.8. Versions below 9.1.8 is not working.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.