Score:1

I want to create custom taxonomy field module

es flag

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 Drupal\mymodule2\Plugin\Field\FieldType\MyModule2Field->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 Drupal\mymodule2\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\taxonomy\Entity\Term;      
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
 * 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 Drupal\mymodule2\Plugin\Field\FieldWidget;
 
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
 
/**
 * 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 Drupal\mymodule2\Plugin\Field\FieldFormatter;
 
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
 
/**
 * 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

apaderno avatar
us flag
Welcome to Drupal Answers! If `$value` contains an array, `$val = implode("", $value);` will cause that warning. Unfortunately, a question asking why the code written by users is causing a PHP warning and how to avoid it is off-topic for us, especially when the code causing the warning isn't using any Drupal function/method, as that isn't a question that requires Drupal knowledge to be answered.
yohei shibasaki avatar
es flag
Thanks,and sorry for asking question on wrong place.I'm going to ask same question on correct place.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.