Drupal9:I want to create custom taxonomy field module

What I want to do

I want to realize this on Drupal9.

  • Finally,I want to create the custom field on a webform.
  • With this custom field,Submitter who use the webform can add a new taxonomy term to a vocabulary (This vacabulary is predetermined in module) on this webform.
  • This field is text field.
  • If the new term already exits in the vocaburaly,it isn’t added to the vocabulary.
  • If it is possible,the submitter can also choose a term from the terms which is already registered.

Problem

I am trying custom field which can register a term in a content type. (I can’t add custom field to webform.So,I tried it first.) I already created it tentatively.However,if I write something to this field,a warning is output.

Warning: Array to string conversion in Drupalmymodule2PluginFieldFieldTypeMyModule2Field->isEmpty() (line 62 of modules/custom/mymodule2/src/Plugin/Field/FieldType/MyModule2Field.php).

MyModule2 is the custom module which I created.

So I want to know how to create a custom field which can register a term properly.

Code and Folder Structure

mymodule2(folder) -mymodule2.info.yml

-mymodule2.module

-src(folder)/Plugin(folder)/Field(folder)

Field(folder)-FieldType(folder)-MyModule2Field.php

Field(folder)-FieldWidget(folder)-MyModule2Widget.php

Field(folder)-FieldFormatter(folder)-MyModule2Formatter.php

Codes

mymodule2.info.yml

name: mymodule2 type: module description: hogehoge core_version_requirement: ^8.8 || ^9 package: Example 

mymodule2.module

<?php ?> 

MyModule2Field.php

    <?php  namespace Drupalmymodule2PluginFieldFieldType;  use DrupalCoreFieldFieldItemBase; use DrupalCoreFieldFieldStorageDefinitionInterface; use DrupalCoreTypedDataDataDefinition; use DrupalCoreStringTranslationTranslatableMarkup; use DrupaltaxonomyEntityTerm;       use DrupalCoreLink; use DrupalCoreUrl; /**  * Plugin implementation of the 'MyModule2' field type.  *  * @FieldType(  *   id = "mymodule2",  *   label = @Translation("MyModule"),  *   description = @Translation("This field is used to store alpha-numeric values."),  *   default_widget = "MyModule2Widget",  *   default_formatter = "MyModule2Formatter"  * )  */ class MyModule2Field extends FieldItemBase {    /**   * {@inheritdoc}   */      public static function propertyDefinitions(FieldStorageDefinitionInterface $definition) {     // Prevent early t() calls by using the TranslatableMarkup.     $properties['mymodule2'] = DataDefinition::create('string')     ->setLabel(new TranslatableMarkup('Text value'));       return $properties;   }     /**    * {@inheritdoc}    */   public static function schema(FieldStorageDefinitionInterface $definition) {     $schema = [         'columns' => [           'mymodule2' => [             'type' => 'varchar',             'length' => 255,           ],         ],     ];                    return $schema;   }     /**    * {@inheritdoc}    */   public function isEmpty() {     $value = $this->getValue();     if (isset($value['mymodule2']) && $value['mymodule2'] != '') {              /*this is problem code*/       $val=implode("",$value);       $arr = explode(',',$val);       $categories_vocabulary='pixelarttag';       foreach($arr as $a){         $term = term::create(array(         'parent' => array(),         'name' => $a,         'vid' => $categories_vocabulary,))->save();       }       return FALSE;     }     return TRUE;   }   } ?> 

MyModule2Widget.php

<?php  namespace Drupalmymodule2PluginFieldFieldWidget;   use DrupalCoreFieldFieldItemListInterface; use DrupalCoreFieldWidgetBase; use DrupalCoreFormFormStateInterface;   /**  * Plugin implementation of the 'MyModule2Widget' widget.  *  * @FieldWidget(  *   id = "MyModule2Widget",  *   label = @Translation("My Field widget"),  *   field_types = {  *     "mymodule2"  *   }  * )  */ class MyModule2Widget extends WidgetBase {    /**    * {@inheritdoc}    */   public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {         $element['mymodule2'] =  [       '#type' => 'textfield',       '#title' => 'AddictionTaxonomy',       '#description' => 'Custom field to be used for alpha-numeric values',       '#default_value' => isset($items[$delta]->title) ? $items[$delta]->title : NULL,       '#weight' => 0,     ];       return $element;   }   } ?> 

MyModule2Formatter.php

<?php namespace Drupalmymodule2PluginFieldFieldFormatter;   use DrupalCoreFieldFormatterBase; use DrupalCoreFieldFieldItemListInterface;   /**  * Plugin implementation of the 'MyModule2Formatter' formatter.  *  * @FieldFormatter(  *   id = "MyModule2Formatter",  *   label = @Translation("My Field Formatter"),  *   field_types = {  *     "mymodule2"  *   }  * )  */ class MyModule2Formatter extends FormatterBase {    /**    * {@inheritdoc}    */   public static function defaultSettings() {     return [       // Implement default settings.     ] + parent::defaultSettings();   }     /**    * {@inheritdoc}    */   public function settingsSummary() {     $summary = [];     $summary[] = $this->t('Displays the random string.');     return $summary;   }     /**    * {@inheritdoc}    */   public function viewElements(FieldItemListInterface $items, $langcode) {       $elements = [];     foreach ($items as $delta => $item) {       $elements[$delta] = [         '#type' => 'markup',         '#markup' => $item->mymodule2       ];     }       return $elements;   } } ?> 

P.S.

I am not good at English, and I also do not know much about Drupal.I have studied Drupal since 1 month ago.So,I might ask something stupid.Please forgive me

Sincerely

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

Drupal9:I want to create custom taxonomy field module

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.