hasField example

XML;

        $dom = new \DOMDocument();
        $dom->loadXML($xml);

        \assert($dom->documentElement instanceof \DOMElement);

        $entity = Entity::fromXml($dom->documentElement);

        static::assertTrue($entity->hasField('name'));
        static::assertFalse($entity->hasField('label'));
    }

    public function testGetField(): void
    {
        $xml = <<<'XML' <entity name="my_entity" custom-fields-aware="true" label-property="name"> <fields> <string name="id"/> <string name="name" translatable="true" /> </fields> </entity>

class CommentPermalinkFormatter extends StringFormatter {

  /** * {@inheritdoc} */
  protected function getEntityUrl(EntityInterface $comment) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment_permalink = $comment->permalink();
    if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) {
      $attributes = $comment_permalink->getOption('attributes') ?: [];
      $attributes += ['title' => Unicode::truncate($body, 128)];
      $comment_permalink->setOption('attributes', $attributes);
    }
    return $comment_permalink;
  }

  /** * {@inheritdoc} */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    
private function getAffected(EntityWriteEvent $event): array
    {
        return array_filter($event->getCommandsForEntity(ProductDefinition::ENTITY_NAME)static function DWriteCommand $command) {
            if ($command instanceof DeleteCommand) {
                return false;
            }

            if ($command instanceof InsertCommand) {
                return true;
            }

            if ($command->hasField('stock')) {
                return true;
            }

            return false;
        });
    }
}
// Do not add any links if the entity is displayed for:       // - search indexing.       // - constructing a search result excerpt.       // - print.       // - rss.       return [];
    }

    $fields = $this->commentManager->getFields($entity->getEntityTypeId());
    foreach ($fields as $field_name => $detail) {
      // Skip fields that the entity does not have.       if (!$entity->hasField($field_name)) {
        continue;
      }
      $links = [];
      $commenting_status = $entity->get($field_name)->status;
      if ($commenting_status != CommentItemInterface::HIDDEN) {
        // Entity has commenting status open or closed.         $field_definition = $entity->getFieldDefinition($field_name);
        if ($view_mode == 'teaser') {
          // Teaser view: display the number of comments that have been posted,           // or a link to add new comments if the user has permission, the           // entity is open to new comments, and there currently are none.
foreach ($commented_entity_ids as $entity_type => $ids) {
      $commented_entities[$entity_type] = $this->entityTypeManager
        ->getStorage($entity_type)
        ->loadMultiple($ids);
    }

    foreach ($comments as $comment) {
      /** @var \Drupal\Core\Entity\EntityInterface $commented_entity */
      $commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()];
      $comment_permalink = $comment->permalink();
      if ($comment->hasField('comment_body') && ($body = $comment->get('comment_body')->value)) {
        $attributes = $comment_permalink->getOption('attributes') ?: [];
        $attributes += ['title' => Unicode::truncate($body, 128)];
        $comment_permalink->setOption('attributes', $attributes);
      }
      $options[$comment->id()] = [
        'title' => ['data' => ['#title' => $comment->getSubject() ?: $comment->id()]],
        'subject' => [
          'data' => [
            '#type' => 'link',
            '#title' => $comment->getSubject(),
            '#url' => $comment_permalink,
          ],
        $comment->setAuthorName(NULL);
      }
    }
    else {
      $author_id = $this->currentUser->id();
    }
    $comment->setOwnerId($author_id);

    // Validate the comment's subject. If not specified, extract from comment     // body.     if (trim($comment->getSubject()) == '') {
      if ($comment->hasField('comment_body')) {
        // The body may be in any format, so:         // 1) Filter it into HTML         // 2) Strip out all HTML tags         // 3) Convert entities back to plain-text.         $comment_text = $comment->comment_body->processed;
        $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
      }
      // Edge cases where the comment body is populated only by HTML tags will       // require a default subject.       if ($comment->getSubject() == '') {
        $comment->setSubject($this->t('(No subject)'));
      }

            '/0'
        );

        $event = EntityWriteEvent::create(
            WriteContext::createFromContext($context),
            [$command],
        );

        $subscriber->__invoke($event);

        static::assertFalse($command->hasField('available_stock'));
    }

    public function testThatDeleteCommandIsIgnored(): void
    {
        $context = Context::createDefaultContext();

        $subscriber = new AvailableStockMirrorSubscriber();

        $definition = $this->getDefinition();

        $command = new DeleteCommand(
            
// if a specific id has been defined in the options and there is no corresponding attribute         // return false in order to avoid a fallback to the id which might be of another object         if (\is_string($options->id) && null === $request->attributes->get($options->id)) {
            return [];
        }

        $criteria = [];
        $metadata = $manager->getClassMetadata($options->class);

        foreach ($mapping as $attribute => $field) {
            if (!$metadata->hasField($field) && (!$metadata->hasAssociation($field) || !$metadata->isSingleValuedAssociation($field))) {
                continue;
            }

            $criteria[$field] = $request->attributes->get($attribute);
        }

        if ($options->stripNull) {
            $criteria = array_filter($criteriastatic fn ($value) => null !== $value);
        }

        return $criteria;
    }


    $media_source = $this->getSource();
    foreach ($this->translations as $langcode => $data) {
      if ($this->hasTranslation($langcode)) {
        $translation = $this->getTranslation($langcode);
        // Try to set fields provided by the media source and mapped in         // media type config.         foreach ($translation->bundle->entity->getFieldMap() as $metadata_attribute_name => $entity_field_name) {
          // Only save value in the entity if the field is empty or if the           // source field changed.           if ($translation->hasField($entity_field_name) && ($translation->get($entity_field_name)->isEmpty() || $translation->hasSourceFieldChanged())) {
            $translation->set($entity_field_name$media_source->getMetadata($translation$metadata_attribute_name));
          }
        }

        // Try to set a default name for this media item if no name is provided.         if ($translation->get('name')->isEmpty()) {
          $translation->setName($translation->getName());
        }

        // Set thumbnail.         if ($translation->shouldUpdateThumbnail($this->isNew())) {
          
throw new \RuntimeException('No entities found in parsed xml file');
        }

        foreach ($schema->getEntities()->getEntities() as $entity) {
            if ($entity->isCustomFieldsAware()) {
                $label = $entity->getLabelProperty();

                if ($label === null) {
                    throw CustomEntityException::noLabelProperty();
                }

                if (!$entity->hasField($label)) {
                    throw CustomEntityException::labelPropertyNotDefined($label);
                }

                if (!$entity->getField($label) instanceof StringField) {
                    throw CustomEntityException::labelPropertyWrongType($label);
                }
            }

            foreach ($entity->getFields() as $field) {
                if ($field instanceof OneToManyField) {
                    $this->validateAssociation($field);
                }
/** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
    $form_object = $form_state->getFormObject();
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_object->getEntity();

    // ContentEntityForm::submit will update the changed timestamp on submit     // after the entity has been validated, so that it does not break the     // EntityChanged constraint validator. The content translation metadata     // field for the changed timestamp does not have such a constraint defined     // at the moment, but it is correct to update its value in a submission     // handler as well and have the same logic like in the Form API.     if ($entity->hasField('content_translation_changed')) {
      $metadata = $this->manager->getTranslationMetadata($entity);
      $metadata->setChangedTime(REQUEST_TIME);
    }
  }

  /** * Form submission handler for ContentTranslationHandler::entityFormAlter(). * * Takes care of the source language change. */
  public function entityFormSourceChange($form, FormStateInterface $form_state) {
    
$entity = Term::load($id);
    $this->assertInstanceOf(TermInterface::class$entity);
    $this->assertSame($expected_language$entity->language()->getId());
    $this->assertEquals($expected_label$entity->label());
    $this->assertEquals($expected_vid$entity->bundle());
    $this->assertEquals($expected_description$entity->getDescription());
    $this->assertEquals($expected_format$entity->getFormat());
    $this->assertEquals($expected_weight$entity->getWeight());
    $this->assertEquals($expected_parents$this->getParentIDs($id));
    $this->assertHierarchy($expected_vid$id$expected_parents);
    if (!is_null($expected_field_integer_value)) {
      $this->assertTrue($entity->hasField('field_integer'));
      $this->assertEquals($expected_field_integer_value$entity->field_integer->value);
    }
    if (!is_null($expected_term_reference_tid)) {
      $this->assertTrue($entity->hasField('field_integer'));
      $this->assertEquals($expected_term_reference_tid$entity->field_term_reference->target_id);
    }
    if (isset($expected_container_flag)) {
      $this->assertEquals($expected_container_flag$entity->forum_container->value);
    }
  }

  

  public function buildComponents(array &$build, array $entities, array $displays$view_mode) {
    $entities_by_bundle = [];
    foreach ($entities as $id => $entity) {
      // Initialize the field item attributes for the fields being displayed.       // The entity can include fields that are not displayed, and the display       // can include components that are not fields, so we want to act on the       // intersection. However, the entity can have many more fields than are       // displayed, so we avoid the cost of calling $entity->getProperties()       // by iterating the intersection as follows.       foreach ($displays[$entity->bundle()]->getComponents() as $name => $options) {
        if ($entity->hasField($name)) {
          foreach ($entity->get($name) as $item) {
            $item->_attributes = [];
          }
        }
      }
      // Group the entities by bundle.       $entities_by_bundle[$entity->bundle()][$id] = $entity;
    }

    // Invoke hook_entity_prepare_view().     $this->moduleHandler()->invokeAll('entity_prepare_view', [$this->entityTypeId, $entities$displays$view_mode]);

    
Collection::class,
                true,
                new Type($collectionKeyType),
                new Type(Type::BUILTIN_TYPE_OBJECT, false, $class)
            )];
        }

        if ($metadata instanceof ClassMetadataInfo && isset($metadata->embeddedClasses[$property])) {
            return [new Type(Type::BUILTIN_TYPE_OBJECT, false, $metadata->embeddedClasses[$property]['class'])];
        }

        if ($metadata->hasField($property)) {
            $typeOfField = $metadata->getTypeOfField($property);

            if (!$builtinType = $this->getPhpType($typeOfField)) {
                return null;
            }

            $nullable = $metadata instanceof ClassMetadataInfo && $metadata->isNullable($property);
            $enumType = null;
            if (null !== $enumClass = $metadata->getFieldMapping($property)['enumType'] ?? null) {
                $enumType = new Type(Type::BUILTIN_TYPE_OBJECT, $nullable$enumClass);
            }

            


  /** * Tests the account form implements entity field access for mail. */
  public function testUserMailFieldAccess() {
    \Drupal::state()->set('user_access_test_forbid_mail_edit', TRUE);
    \Drupal::service('module_installer')->install(['user_access_test']);
    $user = $this->drupalCreateUser();
    $this->drupalLogin($user);
    $this->drupalGet("user/" . $user->id() . "/edit");
    $this->assertFalse($this->getSession()->getPage()->hasField('mail'));
  }

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