0

Consider the following (newly created) form:

  • field_country (option select)
  • field_phonenumber number (multivalue text field)

When the user chooses from field_country, then the user can add unlimited instances of field_phonenumber fields, which should be pre-populated with the selected country code.

I was able to prepopulate the first instance of field_phonenumber with AJAX, but not the additional instances.

$form_state->getValue(field_country) was empty for the additional instances of field_phonenumber.

Any thoughts are much appreciated.

Edit: the code I tried so far:

function testmodule_entity_type_alter(array &$entity_types) {
  $handlers = $entity_types['node']->get('handlers');
  $handlers['form']['edit']     = 
    'Drupal\testmodule\Form\CompanyContactInfoForm';
  $handlers['form']['default']  = 
    'Drupal\testmodule\Form\CompanyContactInfoForm';
  $entity_types['node']->set('handlers', $handlers);
}

namespace Drupal\testmodule\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeForm;

/**
 * @ingroup testmodule
 */
class CompanyContactInfoForm extends NodeForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form = parent::buildForm($form, $form_state);

    $form['#attributes']['id'] = 'form-fixed-id';

    $form['field_country']["widget"]['#ajax'] = array(
      'callback' => '::addCountryCode',
      'wrapper' => $form['#attributes']['id'],
      'event' => 'change',
      'method' => 'replace',
      'progress' => ['type' => 'throbber', 'message' => t('Adding country calling code..')],
    );

    return $form;
  }

  public function addCountryCode (array $form, FormStateInterface $form_state){
    foreach (array_keys($form['field_phonenumber']['widget']) as $key) {
        if (is_numeric($key)) {
            $form['field_phonenumber']['widget'][$key]['value']['#value'] = static::getCountryCode($form_state->getValue('field_country')[0]['value']);
        }
    }
    return $form;
  }

  public static function getCountryCode ($country) {
    $codes = array(
        "Belgium"     => "+32",
        "France"      => "+33",
        "Greece"      => "+30"
    );
    return $codes[$country];
  }
}
2
  • Can you please post what have you tried so far, how did you repopulate the first item?
    – berramou
    Feb 19, 2019 at 23:17
  • @berramou I added the code.
    – Orion
    Feb 20, 2019 at 2:28

0

This site is temporarily in read-only mode and not accepting new answers.

Browse other questions tagged .