0

I've created a field dynamically based on a checkbox title I just clicked before, here the code :

$form['myfield']['widget']['#ajax'] = [
 'callback' => 'myCallback',
 'event' => 'change',
 'wrapper' => 'my-container'
];

Callback :

function myCallback(array &$form, FormStateInterface $form_state)
{
  $fieldName = "field_desc_" . strtolower(str_replace(' ', '_', $form_state->getTriggeringElement()['#title']));
  $field_storage = FieldStorageConfig::loadByName('node', $fieldName);
  $field = FieldConfig::loadByName('node', 'content_type', $fieldName);

  if (0 !== $form_state->getTriggeringElement()['#value']) {
    $field_storage = FieldStorageConfig::create(
      array('entity_type' => 'node', 'field_name' => $fieldName, 'type' => 'string'));
    $field_storage->save();
    $field = FieldConfig::create(
      array('entity_type' => 'node', 'field_name' => $fieldName, 'bundle' => 'industry', 'settings' => array('handler' => 'default', 'handler_settings' => array())));
    $field->save();
    $form_state
      ->get('form_display')->setComponent(
        $fieldName, [
          'type' => 'string_textfield',
        ])
      ->save();
  } else {
    if ($field_storage && $field) {
      $field_storage->delete();
      $field->delete();
    }
  }
  $form_state->setRebuild(TRUE);
  return $form[$fieldName];
} 

It seems to not work. I have to refresh the page to see my new field appears. My question is : How can I see my field I just created instantly displayed when the event "change" is triggered ?

Thanks :)

1
  • You can't as explained in this answer. You'll have to show/hide field A or field B based on what's selected. – No Sssweat Oct 27 '20 at 10:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.