getFieldName example

public function update(CommentInterface $comment) {
    // Allow bulk updates and inserts to temporarily disable the maintenance of     // the {comment_entity_statistics} table.     if (!$this->state->get('comment.maintain_entity_statistics')) {
      return;
    }

    $query = $this->database->select('comment_field_data', 'c');
    $query->addExpression('COUNT([cid])');
    $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())
      ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
      ->condition('c.field_name', $comment->getFieldName())
      ->condition('c.status', CommentInterface::PUBLISHED)
      ->condition('default_langcode', 1)
      ->execute()
      ->fetchField();

    if ($count > 0) {
      // Comments exist.       $last_reply = $this->database->select('comment_field_data', 'c')
        ->fields('c', ['cid', 'name', 'changed', 'uid'])
        ->condition('c.entity_id', $comment->getCommentedEntityId())
        ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
        
      // can edit name, homepage and mail. Anonymous users can also fill in the       // fields on comment creation.       if (in_array($field_definition->getName()['name', 'mail', 'homepage'], TRUE)) {
        if (!$items) {
          // We cannot make a decision about access to edit these fields if we           // don't have any items and therefore cannot determine the Comment           // entity. In this case we err on the side of caution and prevent edit           // access.           return AccessResult::forbidden();
        }
        $is_name = $field_definition->getName() === 'name';
        $anonymous_contact = $commented_entity->get($entity->getFieldName())->getFieldDefinition()->getSetting('anonymous');
        $admin_access = AccessResult::allowedIfHasPermission($account, 'administer comments');
        $anonymous_access = AccessResult::allowedIf($entity->isNew() && $account->isAnonymous() && ($anonymous_contact != CommentInterface::ANONYMOUS_MAYNOT_CONTACT || $is_name) && $account->hasPermission('post comments'))
          ->cachePerPermissions()
          ->addCacheableDependency($entity)
          ->addCacheableDependency($field_definition->getConfig($commented_entity->bundle()))
          ->addCacheableDependency($commented_entity);
        return $admin_access->orIf($anonymous_access);
      }
    }

    if ($operation == 'view') {
      
$owner = $this->userStorage->load($owner_id);
      if ($owner->getAccountName() != $author_name) {
        $this->context->buildViolation($constraint->messageMatch)
          ->atPath('name')
          ->addViolation();
      }
    }

    // Anonymous account might be required - depending on field settings. We     // can't validate this without a valid commented entity, which will fail     // the validation elsewhere.     if ($owner_id === 0 && empty($author_name) && $entity->getCommentedEntity() && $entity->getFieldName() &&
      $this->getAnonymousContactDetailsSetting($entity) === CommentInterface::ANONYMOUS_MUST_CONTACT) {
      $this->context->buildViolation($constraint->messageRequired)
        ->atPath('name')
        ->addViolation();
    }
  }

  /** * Gets the anonymous contact details setting from the comment. * * @param \Drupal\comment\CommentInterface $comment * The entity. * * @return int * The anonymous contact setting. */
$this->renderer = $renderer;
    $this->entityFieldManager = $entity_field_manager ?: \Drupal::service('entity_field.manager');
  }

  /** * {@inheritdoc} */
  public function form(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->entity;
    $entity = $this->entityTypeManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
    $field_name = $comment->getFieldName();
    $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];
    $config = $this->config('user.settings');

    // In several places within this function, we vary $form on:     // - The current user's permissions.     // - Whether the current user is authenticated or anonymous.     // - The 'user.settings' configuration.     // - The comment field's definition.     $form['#cache']['contexts'][] = 'user.permissions';
    $form['#cache']['contexts'][] = 'user.roles:authenticated';
    $this->renderer->addCacheableDependency($form$config);
    


        if ($this->secure && $this->isSecure() !== $isSecure) {
            return false;
        }

        return true;
    }

    public function toString()
    {
        return $this->getFieldName() . ': ' . $this->getFieldValue();
    }

    public function toStringMultipleHeaders(array $headers)
    {
        $headerLine = $this->toString();

        foreach ($headers as $header) {
            if (!$header instanceof Zend_Http_Header_SetCookie) {
                throw new Zend_Http_Header_Exception_RuntimeException(
                    'The SetCookie multiple header implementation can only accept an array of SetCookie headers'
                );
            }
->getForm()
        ;

        $form->get('username')->addError(new FormError('username.max_length'));

        $this->view = $form->createView();
    }

    public function testFieldName()
    {
        $this->assertFalse($this->view->children['username']->isRendered());
        $this->assertSame('register[username]', $this->rawExtension->getFieldName($this->view->children['username']));
        $this->assertTrue($this->view->children['username']->isRendered());
    }

    public function testFieldValue()
    {
        $this->assertSame('tgalopin', $this->rawExtension->getFieldValue($this->view->children['username']));
        $this->assertSame(['sugar', 'salt']$this->rawExtension->getFieldValue($this->view->children['choice_multiple']));
    }

    public function testFieldLabel()
    {
        

  protected function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) {
    $links = [];
    $status = $commented_entity->get($entity->getFieldName())->status;

    if ($status == CommentItemInterface::OPEN) {
      if ($entity->access('delete')) {
        $links['comment-delete'] = [
          'title' => t('Delete'),
          'url' => $entity->toUrl('delete-form'),
        ];
      }

      if ($entity->access('update')) {
        $links['comment-edit'] = [
          
new TwigFunction('form_widget', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_errors', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_label', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_help', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_row', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_rest', null, ['node_class' => SearchAndRenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form', null, ['node_class' => RenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_start', null, ['node_class' => RenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('form_end', null, ['node_class' => RenderBlockNode::class, 'is_safe' => ['html']]),
            new TwigFunction('csrf_token', [FormRenderer::class, 'renderCsrfToken']),
            new TwigFunction('form_parent', 'Symfony\Bridge\Twig\Extension\twig_get_form_parent'),
            new TwigFunction('field_name', $this->getFieldName(...)),
            new TwigFunction('field_value', $this->getFieldValue(...)),
            new TwigFunction('field_label', $this->getFieldLabel(...)),
            new TwigFunction('field_help', $this->getFieldHelp(...)),
            new TwigFunction('field_errors', $this->getFieldErrors(...)),
            new TwigFunction('field_choices', $this->getFieldChoices(...)),
        ];
    }

    public function getFilters(): array
    {
        return [
            
$container->get('entity_type.bundle.info'),
      $container->get('entity_type.manager')
    );
  }

  /** * {@inheritdoc} */
  public function getMaxThread(CommentInterface $comment) {
    $query = $this->database->select($this->getDataTable(), 'c')
      ->condition('entity_id', $comment->getCommentedEntityId())
      ->condition('field_name', $comment->getFieldName())
      ->condition('entity_type', $comment->getCommentedEntityTypeId())
      ->condition('default_langcode', 1);
    $query->addExpression('MAX([thread])', 'thread');
    return $query->execute()
      ->fetchField();
  }

  /** * {@inheritdoc} */
  public function getMaxThreadPerThread(CommentInterface $comment) {
    
'entity_type' => 'node',
      'field_name' => 'comment_custom',
    ]);
    $comment2->save();

    $view = Views::getView('test_comment_field_name');
    $view->preview();

    $expected_result = [
      [
        'cid' => $comment->id(),
        'field_name' => $comment->getFieldName(),
      ],
      [
        'cid' => $comment2->id(),
        'field_name' => $comment2->getFieldName(),
      ],
    ];
    $column_map = [
      'cid' => 'cid',
      'comment_field_data_field_name' => 'field_name',
    ];
    $this->assertIdenticalResultset($view$expected_result$column_map);

    

  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);
      

  protected function getUrlInfo(ResultRow $row) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->getEntity($row);
    if (!$comment) {
      return NULL;
    }
    return Url::fromRoute('comment.reply', [
      'entity_type' => $comment->getCommentedEntityTypeId(),
      'entity' => $comment->getCommentedEntityId(),
      'field_name' => $comment->getFieldName(),
      'pid' => $comment->id(),
    ]);
  }

  /** * {@inheritdoc} */
  protected function getDefaultLabel() {
    return $this->t('Reply');
  }

}
// Check create-only fields.     foreach ($this->createOnlyFields as $field) {
      // Check view operation.       foreach ($permutations as $set) {
        $may_view = $set['comment']->{$field}->access('view', $set['user']);
        $may_update = $set['comment']->{$field}->access('edit', $set['user']);
        $this->assertTrue($may_viewnew FormattableMarkup('User @user can view field @field on comment @comment', [
          '@user' => $set['user']->getAccountName(),
          '@comment' => $set['comment']->getSubject(),
          '@field' => $field,
        ]));
        $expected = $set['user']->hasPermission('post comments') && $set['comment']->isNew() && (int) $set['comment']->getCommentedEntity()->get($set['comment']->getFieldName())->status !== CommentItemInterface::CLOSED;
        $this->assertEquals($expected$may_updatenew FormattableMarkup('User @user @state update field @field on comment @comment', [
          '@user' => $set['user']->getAccountName(),
          '@state' => $expected ? 'can' : 'cannot',
          '@comment' => $set['comment']->getSubject(),
          '@field' => $field,
        ]));
      }
    }

    // Check contact fields.     foreach ($this->contactFields as $field) {
      
/** * {@inheritdoc} */
  protected function getBuildDefaults(EntityInterface $entity$view_mode) {
    $build = parent::getBuildDefaults($entity$view_mode);

    /** @var \Drupal\comment\CommentInterface $entity */
    // Store a threading field setting to use later in self::buildComponents().     $commented_entity = $entity->getCommentedEntity();
    $build['#comment_threaded'] =
      is_null($commented_entity)
      || $commented_entity->getFieldDefinition($entity->getFieldName())
        ->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED;
    // If threading is enabled, don't render cache individual comments, but do     // keep the cacheability metadata, so it can bubble up.     if ($build['#comment_threaded']) {
      unset($build['#cache']['keys']);
    }

    return $build;
  }

  /** * {@inheritdoc} * * In addition to modifying the content key on entities, this implementation * will also set the comment entity key which all comments carry. * * @throws \InvalidArgumentException * Thrown when a comment is attached to an entity that no longer exists. */
Home | Imprint | This part of the site doesn't use cookies.