How do I set an incremental property on a custom field?

I built a custom module which creates a custom field type (with formatter and widget), and I would like to make one property of the field incremental (to increase its value by one for each instance of the field.)

What I have so far is:

  1. web/modules/custom/asciinema/src/Plugin/Field/FieldType/AsciinemaItem.php (the field definition)
  public static function schema(FieldStorageDefinitionInterface $field_definition) {     return [       // columns contains the values that the field will store       'columns' => [         // List the values that the field will save.         'aid' => [           'type'        => 'serial',           'size'        => 'normal',           'description' => 'The id of the asciinema instance.',           'unsigned'    => TRUE,           'not null'    => TRUE,         ],       ],       .....       'unique keys' => [         'aid' => ['aid'],       ],     ];    // This function ensures that the value is incremented each time a new field instance is saved.   public function preSave() {     if ($this->getEntity()->isNew()) {       // Increase the value of aid when dealing with a new entity.       $fieldConfig = $this->getFieldDefinition();       $field_name = $fieldConfig->getName();       $entity_type = $fieldConfig->getTargetEntityTypeId();              $query = Drupal::database()->select($entity_type . '__' . $field_name, 'ef')                 ->fields('ef', [$field_name . '_' . 'aid'])                 ->orderBy($field_name . '_' . 'aid', 'DESC');       $lastIndex = $query->execute()->fetchField();              $result = !empty($lastIndex) ? $lastIndex + 1 : 1;        $this->values['aid'] = $result;       $this->setValue($this->values);     }   } 
  1. web/modules/custom/asciinema/src/Plugin/Field/FieldWidget/AsciinemaDefaultWidget.php (the field widget).
 public function formElement(     FieldItemListInterface $items,     $delta,     array $element,     array &$form,     FormStateInterface $form_state   ) {     // Current values with fallbacks.     $aid      = isset($items[$delta]->aid) ? $items[$delta]->aid : 0;     ....     $element['asciinema']['id']['aid'] = [       '#title'          => t('AID'),       '#description'    => t('Asciinema ID.'),       '#disabled'       => TRUE,       '#type'           => 'textfield',       '#default_value'  => $aid,     ];     ....     return $element;      ....    public function massageFormValues(     array $values,     array $form,     FormStateInterface $form_state   ) {     foreach ($values as &$value) {       // ID.       $value['aid']       = $value['asciinema']['id']['aid'];     ....       unset($value['asciinema']);     }      return $values;   } 
  1. web/modules/custom/asciinema/src/Plugin/Field/FieldFormatter/AsciinemaDefaultFormatter.php (The formatter):
  public function viewElements(FieldItemListInterface $items, $langcode) {     $elements = [];     $source = [];      foreach ($items as $delta => $item) {       // Render output using asciinema_default theme.       $source['asciinema'] = [         '#theme'     => 'asciinema_default',         '#asciinema' => [           'aid'          => $item->aid,         ],       ];       ...       $elements[$delta] = [         '#markup' => Drupal::service('renderer')->render($source),       ];     }      return $elements; 

As it is right now I can save the values entered in my custom field and the aid gets increased for each field instance. However I can not edit any of the past data because that would generate:

NOTICE: PHP message: Uncaught PHP Exception DrupalCoreEntityEntityStorageException: "SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint "node_revision__asciinema__asciinema_aid__key" php_1       | DETAIL:  Key (asciinema_aid)=(4) already exists.: 

I would love to find out what’s missing or to find a better and cleaner way to deal with incremental fields.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

How do I set an incremental property on a custom field?

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.