1

I am trying to override the user registration form in Drupal 8, using the following code.

RouteSubscriber.php

namespace Drupal\registration_subscription\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Class RouteSubscriber.
 *
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
     if ($route = $collection->get('user.register')) {
        $route->setDefault('_form', '\Drupal\registration_subscription\Form\RegistrationSubscriptionForm');
      }


  }
}

RegistrationSubscriptionForm.php

namespace Drupal\registration_subscription\Form;

use Drupal\registration_subscription\Entity\Subscription;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\user\Entity\User;
use Drupal\user\RegisterForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class RegistrationSubscriptionForm.
 */
class RegistrationSubscriptionForm extends RegisterForm {

  /**
   * {@inheritdoc}
   */
  /*
    public function buildForm(array $form, FormStateInterface $form_state) {
    die();
    $form = parent :: buildForm($form, $form_state);
    //$subscriptions = $this->getSubscriptionDetails();
    $form['subscription']['#attached']['library'][] = 'registration_subscription/registration_subscription_form';
    $form['subscription']['#prefix'] = '<ul id="products" class="grid clearfix">';
    $i = 0;

    foreach ($subscriptions as $key => $value) {
    $value['duration'] = ($value['duration'] == '-1') ? 'Unlimted' : $value['duration'];
    $form['subscription'][$i] = [
    '#type' => 'checkbox',
    '#title' => $this->t('Subscription'),
    '#weight' => '0',
    '#prefix' => '<li class="clearfix">
    <section class="left">
    <h3>' . $value['title'] . '</h3>
    <span class="meta">Duration: ' . $value['duration'] . ' Day\'s</span>
    </section>',
    '#suffix' => '<section class="right">
    <span class="price">$' . $value['amount'] . '</span>
    </section>
    </li>',
    '#weight' => '99',
    ];
    $form['subscription'][$i]['#attributes']['class'][] = 'subject-list';
    $i++;
    }

    $form['subscription']['#suffix'] = '</ul>';
    $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    ];

    return $form;
    }
   */

  public function __construct(EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL, ModuleHandlerInterface $moduleHandler) {
    $this->setEntity(new User([], 'user'));
    $this->setModuleHandler($moduleHandler);
    parent::__construct($entity_manager, $language_manager, $entity_type_bundle_info, $time);    
  }

  /**
   * @inheritdoc
   */
  public static function create(ContainerInterface $container) {
    return new static(
       $container->get('entity.manager'), $container->get('language_manager'), $container->get('entity_type.bundle.info'), $container->get('datetime.time'), $container->get('module_handler')
    );
  }

  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    if (!$form_state->has('entity_form_initialized')) {
        $this->init($form_state);
    }
    $user = $this->currentUser();
    /** @var \Drupal\user\UserInterface $account */
    $account = $this->entity;
    $form['#attributes']['novalidate'] = 'novalidate';
    $subscriptions = $this->getSubscriptionDetails();
    $subscription_form['subscription']['#attached']['library'][] = 'registration_subscription/registration_subscription_form';
    $subscription_form['subscription']['#prefix'] = '<ul id="products" class="grid clearfix">';
    $i = 0;

    foreach ($subscriptions as $key => $value) {
      $value['duration'] = ($value['duration'] == '-1') ? 'Unlimted' : $value['duration'];
      $subscription_form['subscription'][$i] = [
          '#type' => 'checkbox',
          '#title' => $this->t('Subscription'),
          '#weight' => '0',
          '#prefix' => '<li class="clearfix">
              <section class="left">
              <h3>' . $value['title'] . '</h3>
              <span class="meta">Duration: ' . $value['duration'] . ' Day\'s</span>
              </section>',
          '#suffix' => '<section class="right">
              <span class="price">$' . $value['amount'] . '</span>
              </section>
              </li>',
          '#weight' => '99',
      ];
      $subscription_form['subscription'][$i]['#attributes']['class'][] = 'subject-list';
      $i++;
    }

    $subscription_form['subscription']['#suffix'] = '</ul>';

    $form['registration_subscription'] = [
        '#type' => 'details',
        '#open' => TRUE,
        '#title' => 'Subscription',
    ];
    $form['registration_subscription']['subscription'] = $subscription_form['subscription'];
    $form['registration_subscription']['#weight'] = '99';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getSubscriptionDetails() {
    $subs_details = Subscription::loadMultiple();
    $data = [];
    if (count($subs_details) <= 0) {
      return $data;
    }

    foreach ($subs_details as $key => $val) {
      $data[$key]['title'] = $val->get('title')->getValue()[0]['value'];
      $data[$key]['amount'] = $val->get('subscription_amount')->getValue()[0]['value'];
      $data[$key]['duration'] = $val->get('duration')->getValue()[0]['value'];
      $data[$key]['description'] = $val->get('description')->getValue()[0]['value'];
      $data[$key]['subscription_id'] = $val->id();
      $data[$key]['unlimited_subscription'] = $val->get('unlimited_subscription')->getValue()[0]['value'];
    }
    return $data;
  }

  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form, $form_state);
    $element['submit']['#value'] = 'Submit';
    return $element;
  }

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

    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);
    _user_mail_notify('register_pending_approval', $account);
    $this->messenger()->addStatus($this->t('Thank you for applying for an account. Your account is currently pending approval by the site administrator.<br />In the meantime, a welcome message with further instructions has been sent to your email address.'));
    $form_state->setRedirect('<front>');
  }

}

I get the following error when I try to create a new user.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column uuid cannot be null: INSERT INTO {users} (uid, uuid, langcode) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array(
[:db_insert_placeholder_0] => 27
[:db_insert_placeholder_1] =>
[:db_insert_placeholder_2] => en
) in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 783 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

  • I'm not seeing anything myself, I wonder if this isn't a misdiagnoses of the problem. The error message says that it's trying to insert a new user into the database, but the UUID column is empty. I don't see anything in your code using the ::entity object that would look to cause that issue, and the UUID would be set somewhere altogether in the first place. It's strange that it's not. Anyways, Entity::save (api.drupal.org/api/drupal/…) is where the user is saved. Try to debug the missing UUID from there. – Jaypan Apr 2 at 10:34
  • [:db_insert_placeholder_1] => is trying to be written as null, somewhere in your form, db_insert_placeholder_1 is not being set, or you are losing that value. You can try adding a kpr($value);, and keep moving it down your form and see where it's lost. – Prestosaurus Apr 2 at 15:08
  • @jaypan i have extends RegisterForm class and nothing to write in save function, only call parent::save($form, $form_state);, i have checked in my code, we does not need to set uuid in my "RegistrationSubscriptionForm" class. could you please provide me more about it. – Surya Prakash Apr 3 at 13:13

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.