2

I've a custom module that alters the MenuLinkContent entity by adding a field. My field is defined as follow.

/**
 * Implements hook_entity_base_field_info().
 */
function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['hide_label'] = BaseFieldDefinition::create('boolean')
    ->setLabel(t('Hide label'))
    ->setDescription(t('Display only the icon.'))
    ->setDisplayOptions('form', array(
      'type' => 'checkbox',
      'weight' => 0
    ));

  return $fields;
}

By default the checkbox is saved in the DB with a value of 0 if unchecked, and with a value of 1 if checked. To Drupal there's always a value for that field, that's why it prevent me to uninstall the module with the message There is data for the field hide_label on entity type Custom menu link.

How should I manage this situation? Should I save a value of NULL if unchecked in some way, or should I have to do something when uninstalling my custom module?

4
  • duplicate here (w/o accepted anser thoe ..) drupal.stackexchange.com/questions/176927/…
    – rémy
    Commented Mar 10, 2017 at 13:29
  • The linked solution suggests to delete the entity where the field is attached. In my case that means delete all menu links added by users, and it's not a viable solution to me. Commented Mar 10, 2017 at 14:33
  • yes - sorry. so loop all menu entites and set the field value to NULL, like suggested, in hook_uninstall
    – rémy
    Commented Mar 10, 2017 at 14:48
  • It seems not work... I think Drupal runs uninstall validators before calling hook_uninstall() and hook_module_preuninstall(). Commented Mar 10, 2017 at 16:07

1 Answer 1

1

You could create a custom form and set all the field values to NULL in the submit handler.

For example:

<?php

namespace Drupal\mymodule\Form;

use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

class TestForm extends FormBase {

  public function getFormId() {
    return 'test_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [
      'test' => [
        '#type' => 'submit',
        '#value' => 'Clear field values',
      ],
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $query = Drupal::entityQuery('node');
    $query->condition('type', 'menu_link_content');
    $result = $query->execute();

    $nodes = Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

    foreach ($nodes as $node) {
      if ($node instanceof Node) {
        $node->set('your_field', NULL);
        $node->save();
      }
    }
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.