getSetting example

/** * Returns the value of a field setting. * * @param string $setting_name * The setting name. * * @return mixed * The setting value. */
  protected function getFieldSetting($setting_name) {
    return $this->fieldDefinition->getSetting($setting_name);
  }

  /** * {@inheritdoc} */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    // By default, formatters are available for all fields.     return TRUE;
  }

}
return $this;
  }

  /** * {@inheritdoc} */
  public function getSetting($setting_name) {
    if (array_key_exists($setting_name$this->settings)) {
      return $this->settings[$setting_name];
    }
    else {
      return $this->getFieldStorageDefinition()->getSetting($setting_name);
    }
  }

  /** * {@inheritdoc} */
  public function setSetting($setting_name$value) {
    $this->settings[$setting_name] = $value;
    return $this;
  }

  

  public function testGenerateSampleValue(int $max_length): void {
    foreach ([TRUE, FALSE] as $unique) {
      $definition = $this->prophesize(FieldDefinitionInterface::class);
      $constraints = $unique ? [$this->prophesize(UniqueFieldConstraint::class)] : [];
      $definition->getConstraint('UniqueField')->willReturn($constraints);
      $definition->getSetting('max_length')->willReturn($max_length);
      for ($i = 0; $i < 1000; $i++) {
        $sample_value = StringItem::generateSampleValue($definition->reveal());
        // When the field value needs to be unique, the generated sample value         // should match the maximum length to ensure sufficient entropy.         if ($unique) {
          $this->assertEquals($max_lengthmb_strlen($sample_value['value']));
        }
        else {
          $this->assertLessThanOrEqual($max_lengthmb_strlen($sample_value['value']));
        }
      }
    }
return [
      'case_sensitive' => FALSE,
    ] + parent::defaultStorageSettings();
  }

  /** * {@inheritdoc} */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Text value'))
      ->setSetting('case_sensitive', $field_definition->getSetting('case_sensitive'))
      ->setRequired(TRUE);

    return $properties;
  }

  /** * {@inheritdoc} */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }
$edit = ['settings[file_extensions]' => 'jpg php'];
    $this->submitForm($edit, 'Save settings');
    $this->assertSession()->pageTextContains('Saved ' . $field_name . ' configuration.');

    // Check that a file extension with an underscore can be configured.     $edit = [
      'settings[file_extensions]' => 'x_t x.t xt x_y_t',
    ];
    $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id");
    $this->submitForm($edit, 'Save settings');
    $field = FieldConfig::loadByName('node', $type_name$field_name);
    $this->assertEquals('x_t x.t xt x_y_t', $field->getSetting('file_extensions'));

    // Check that a file field with an invalid value in allowed extensions     // property throws an error message.     $invalid_extensions = ['x_.t', 'x._t', 'xt_', 'x__t', '_xt'];
    foreach ($invalid_extensions as $value) {
      $edit = [
        'settings[file_extensions]' => $value,
      ];
      $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id");
      $this->submitForm($edit, 'Save settings');
      $this->assertSession()->pageTextContains("The list of allowed extensions is not valid. Allowed characters are a-z, 0-9, '.', and '_'. The first and last characters cannot be '.' or '_', and these two characters cannot appear next to each other. Separate extensions with a comma or space.");
    }
'loading' => [
        'attribute' => 'lazy',
      ],
    ] + parent::defaultSettings();
  }

  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $element = [];
    $max_width = $this->getSetting('max_width');
    $max_height = $this->getSetting('max_height');

    foreach ($items as $delta => $item) {
      $main_property = $item->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
      $value = $item->{$main_property};

      if (empty($value)) {
        continue;
      }

      try {
        
/** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form$form_state);
    $entity_type = $this->entityTypeManager->getDefinition($this->fieldDefinition->getTargetEntityTypeId());

    if ($entity_type->hasLinkTemplate('canonical')) {
      $form['link_to_entity'] = [
        '#type' => 'checkbox',
        '#title' => $this->t('Link to the @entity_label', ['@entity_label' => $entity_type->getLabel()]),
        '#default_value' => $this->getSetting('link_to_entity'),
      ];
    }

    return $form;
  }

  /** * {@inheritdoc} */
  public function settingsSummary() {
    $summary = [];
    

  public function postComment($entity$comment$subject = '', $contact = NULL, $field_name = 'comment') {
    $edit = [];
    $edit['comment_body[0][value]'] = $comment;

    if ($entity !== NULL) {
      $field = FieldConfig::loadByName($entity->getEntityTypeId()$entity->bundle()$field_name);
    }
    else {
      $field = FieldConfig::loadByName('node', 'article', $field_name);
    }
    $preview_mode = $field->getSetting('preview');

    // Must get the page before we test for fields.     if ($entity !== NULL) {
      $this->drupalGet('comment/reply/' . $entity->getEntityTypeId() . '/' . $entity->id() . '/' . $field_name);
    }

    // Determine the visibility of subject form field.     $display_repository = $this->container->get('entity_display.repository');
    if ($display_repository->getFormDisplay('comment', 'comment')->getComponent('subject')) {
      // Subject input allowed.       $edit['subject[0][value]'] = $subject;
    }
    // @see \Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface::DATE_STORAGE_FORMAT     'date-only' => 'Y-m-d',
  ];

  /** * {@inheritdoc} */
  public function normalize($datetime$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($datetime instanceof DateTimeIso8601);
    $field_item = $datetime->getParent();
    // @todo Remove this in https://www.drupal.org/project/drupal/issues/2958416.     if ($field_item instanceof DateTimeItem && $field_item->getFieldDefinition()->getFieldStorageDefinition()->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
      $drupal_date_time = $datetime->getDateTime();
      if ($drupal_date_time === NULL) {
        return $drupal_date_time;
      }
      return $drupal_date_time->format($this->allowedFormats['date-only']);
    }
    return parent::normalize($datetime$format$context);
  }

  /** * {@inheritdoc} */
 + parent::defaultSettings();
  }

  /** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements['view_mode'] = [
      '#type' => 'select',
      '#options' => $this->entityDisplayRepository->getViewModeOptions($this->getFieldSetting('target_type')),
      '#title' => $this->t('View mode'),
      '#default_value' => $this->getSetting('view_mode'),
      '#required' => TRUE,
    ];

    return $elements;
  }

  /** * {@inheritdoc} */
  public function settingsSummary() {
    $summary = [];

    

class LanguageSelectWidget extends WidgetBase {

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'language_select',
      '#default_value' => $items[$delta]->value,
      '#languages' => $this->getSetting('include_locked') ? LanguageInterface::STATE_ALL : LanguageInterface::STATE_CONFIGURABLE,
    ];

    return $element;
  }

  /** * {@inheritdoc} */
  public static function defaultSettings() {
    $settings = parent::defaultSettings();
    $settings['include_locked'] = TRUE;

    

  public function commentPermalink(Request $request, CommentInterface $comment) {
    if ($entity = $comment->getCommentedEntity()) {
      // Check access permissions for the entity.       if (!$entity->access('view')) {
        throw new AccessDeniedHttpException();
      }
      $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];

      // Find the current display page for this comment.       $page = $this->entityTypeManager()->getStorage('comment')->getDisplayOrdinal($comment$field_definition->getSetting('default_mode')$field_definition->getSetting('per_page'));
      // @todo: Cleaner sub request handling.       $subrequest_url = $entity->toUrl()->setOption('query', ['page' => $page])->toString(TRUE);
      $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all()$request->cookies->all()[]$request->server->all());
      // Carry over the session to the subrequest.       if ($request->hasSession()) {
        $redirect_request->setSession($request->getSession());
      }
      $request->query->set('page', $page);
      $response = $this->httpKernel->handle($redirect_request, HttpKernelInterface::SUB_REQUEST);
      if ($response instanceof CacheableResponseInterface) {
        // @todo Once path aliases have cache tags (see
// Verify that cacheability metadata is bubbled from the menu link tree     // access checking that is performed when determining the "default parent     // item" options in menu_ui_form_node_type_form_alter(). The "log out" link     // adds the "user.roles:authenticated" cache context.     $this->drupalGet('admin/structure/types/manage/page');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Contexts', 'user.roles:authenticated');

    // Assert the description of "Available menus" checkboxes field.     $this->assertSession()->pageTextContains('Content of this type can be placed in the selected menus.');

    // Verify that the menu link title has the correct maxlength.     $title_max_length = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('menu_link_content')['title']->getSetting('max_length');
    $this->drupalGet('node/add/page');
    $this->assertSession()->responseMatches('/<input .* id="edit-menu-title" .* maxlength="' . $title_max_length . '" .* \/>/');

    // Verify that the menu link description has the correct maxlength.     $description_max_length = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('menu_link_content')['description']->getSetting('max_length');
    $this->drupalGet('node/add/page');
    $this->assertSession()->responseMatches('/<input .* id="edit-menu-description" .* maxlength="' . $description_max_length . '" .* \/>/');

    // Disable the default main menu, so that no menus are enabled.     $edit = [
      'menu_options[main]' => FALSE,
    ];


  /** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form$form_state);

    $form['future_format'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Future format'),
      '#default_value' => $this->getSetting('future_format'),
      '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
    ];

    $form['past_format'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Past format'),
      '#default_value' => $this->getSetting('past_format'),
      '#description' => $this->t('Use <em>@interval</em> where you want the formatted interval text to appear.'),
    ];

    $form['granularity'] = [
      
/** * {@inheritdoc} */
  public function getDerivativeDefinitions($base_plugin_definition) {
    // Get all entity reference fields.     $field_map = $this->entityFieldManager->getFieldMapByFieldType('entity_reference');

    foreach ($field_map as $entity_type => $fields) {
      foreach ($fields as $field_name => $field) {
        foreach ($field['bundles'] as $bundle) {
          $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type$bundle);
          $target_type = $field_definitions[$field_name]->getSetting('target_type');

          // If the field's target type is not supported, skip it.           if (!array_key_exists($target_type$base_plugin_definition['target_types'])) {
            continue;
          }

          // Key derivatives by entity types and bundles.           $derivative_key = $entity_type . '__' . $bundle;

          $derivative = $base_plugin_definition;
          $entity_type_definition = $this->entityTypeManager->getDefinition($entity_type);

          
Home | Imprint | This part of the site doesn't use cookies.