getComponents example


  public function id() {
    return $this->targetEntityType . '.' . $this->bundle . '.' . $this->mode;
  }

  /** * {@inheritdoc} */
  public function preSave(EntityStorageInterface $storage) {
    // Ensure that a region is set on each component.     foreach ($this->getComponents() as $name => $component) {
      // Ensure that a region is set.       if (isset($this->content[$name]) && !isset($component['region'])) {
        // Directly set the component to bypass other changes in setComponent().         $this->content[$name]['region'] = $this->getDefaultRegion();
      }
    }

    ksort($this->content);
    ksort($this->hidden);
    parent::preSave($storage);
  }

  
for ($delta = 0; $delta < $this->fieldTestData->field_storage->getCardinality()$delta++) {
      // field_test_widget uses 'textfield'       $this->assertEquals('textfield', $form[$this->fieldTestData->field_name]['widget'][$delta]['value']['#type'], "First field's form delta {$delta} widget is textfield");
    }
    for ($delta = 0; $delta < $this->fieldTestData->field_storage_2->getCardinality()$delta++) {
      // field_test_widget uses 'textfield'       $this->assertEquals('textfield', $form[$this->fieldTestData->field_name_2]['widget'][$delta]['value']['#type'], "Second field's form delta {$delta} widget is textfield");
    }

    // Test generating widgets for all fields.     $display = $display_repository->getFormDisplay($entity_type$this->fieldTestData->field->getTargetBundle());
    foreach ($display->getComponents() as $name => $options) {
      if ($name != $this->fieldTestData->field_name_2) {
        $display->removeComponent($name);
      }
    }
    $form = [];
    $form_state = new FormState();
    $display->buildForm($entity$form$form_state);

    $this->assertFalse(isset($form[$this->fieldTestData->field_name]), 'The first field does not exist in the form');
    $this->assertEquals($this->fieldTestData->field_2->getLabel()$form[$this->fieldTestData->field_name_2]['widget']['#title'], "Second field's form title is {$this->fieldTestData->field_2->getLabel()}");
    for ($delta = 0; $delta < $this->fieldTestData->field_storage_2->getCardinality()$delta++) {
      
/** * Tests different display options for the source field. */
  public function testDifferentSourceFieldDisplays() {
    $id = 'test_different_displays';
    $field_name = 'field_media_different_display';

    $this->createMediaTypeViaForm($id$field_name);

    // Source field not in displays.     $display = \Drupal::service('entity_display.repository')->getViewDisplay('media', $id);
    $components = $display->getComponents();
    $this->assertArrayHasKey($field_name$components);
    $this->assertSame('entity_reference_entity_id', $components[$field_name]['type']);

    $display = \Drupal::service('entity_display.repository')->getFormDisplay('media', $id);
    $components = $display->getComponents();
    $this->assertArrayHasKey($field_name$components);
    $this->assertSame('entity_reference_autocomplete_tags', $components[$field_name]['type']);
  }

  /** * Tests hidden source field in media type. */

  protected function getInlineBlockComponents(array $sections) {
    $inline_block_components = [];
    foreach ($sections as $section) {
      foreach ($section->getComponents() as $component) {
        $plugin = $component->getPlugin();
        if ($plugin instanceof DerivativeInspectionInterface && $plugin->getBaseId() === 'inline_block') {
          $inline_block_components[] = $component;
        }
      }
    }
    return $inline_block_components;
  }

  /** * Gets the section storage for an entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity. * * @return \Drupal\layout_builder\SectionStorageInterface|null * The section storage if found otherwise NULL. */

  protected function getEditedFieldNames(FormStateInterface $form_state) {
    return array_keys($this->getFormDisplay($form_state)->getComponents());
  }

  /** * Flags violations for the current form. * * If the entity form customly adds some fields to the form (i.e. without * using the form display), it needs to add its fields to array returned by * getEditedFieldNames() and overwrite this method in order to show any * violations for those fields; e.g.: * @code * foreach ($violations->getByField('name') as $violation) { * $form_state->setErrorByName('name', $violation->getMessage()); * } * parent::flagViolations($violations, $form, $form_state); * @endcode * * @param \Drupal\Core\Entity\EntityConstraintViolationListInterface $violations * The violations to flag. * @param array $form * A nested array of form elements comprising the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */
// Add the new field to the default form and view displays for this       // media type.       if ($source_field->isDisplayConfigurable('form')) {
        $display = $this->entityDisplayRepository->getFormDisplay('media', $media_type->id());
        $source->prepareFormDisplay($media_type$display);
        $display->save();
      }
      if ($source_field->isDisplayConfigurable('view')) {
        $display = $this->entityDisplayRepository->getViewDisplay('media', $media_type->id());

        // Remove all default components.         foreach (array_keys($display->getComponents()) as $name) {
          $display->removeComponent($name);
        }
        $source->prepareViewDisplay($media_type$display);
        $display->save();
      }
    }

    $t_args = ['%name' => $media_type->label()];
    if ($status === SAVED_UPDATED) {
      $this->messenger()->addStatus($this->t('The media type %name has been updated.', $t_args));
    }
    
/** * Asserts that the section has the expected components. * * @param \Drupal\layout_builder\SectionComponent[] $expected * The expected sections. * @param \Drupal\layout_builder\Section $section * The section storage to check. * * @internal */
  protected function assertComponents(array $expected, Section $section): void {
    $result = $section->getComponents();
    $this->assertEquals($expected$result);
    $this->assertSame(array_keys($expected)array_keys($result));
  }

  /** * @covers ::getThirdPartySettings * @dataProvider providerTestGetThirdPartySettings */
  public function testGetThirdPartySettings($provider$expected) {
    $this->assertSame($expected$this->section->getThirdPartySettings($provider));
  }

  
$this->moduleHandler()->invokeAll($view_hook[&$build_list[$key]$entity$display$view_mode]);
        $this->moduleHandler()->invokeAll('entity_view', [&$build_list[$key]$entity$display$view_mode]);

        $this->addContextualLinks($build_list[$key]$entity);
        $this->alterBuild($build_list[$key]$entity$display$view_mode);

        // Assign the weights configured in the display.         // @todo Once https://www.drupal.org/node/1875974 provides the missing         // API, only do it for 'extra fields', since other components have         // been taken care of in EntityViewDisplay::buildMultiple().         foreach ($display->getComponents() as $name => $options) {
          if (isset($build_list[$key][$name])) {
            $build_list[$key][$name]['#weight'] = $options['weight'];
          }
        }

        // Allow modules to modify the render array.         $this->moduleHandler()->alter([$view_hook, 'entity_view']$build_list[$key]$entity$display);
      }
    }

    return $build_list;
  }
$assert_session->elementTextContains('css', '.layout-builder__message.layout-builder__message--overrides', 'You are editing the layout for this Bundle with section field content item. Edit the template for all Bundle with section field content items instead.');
    $assert_session->linkExists('Edit the template for all Bundle with section field content items instead.');
    $page->clickLink('Add block');
    $page->clickLink('Powered by Drupal');
    $page->fillField('settings[label]', 'This is an override');
    $page->checkField('settings[label_display]');
    $page->pressButton('Add block');
    $page->pressButton('Save layout');
    $assert_session->pageTextContains('This is an override');

    // Get the UUID of the component.     $components = Node::load(1)->get('layout_builder__layout')->getSection(0)->getComponents();
    end($components);
    $uuid = key($components);

    $this->drupalGet('layout_builder/update/block/overrides/node.1/0/content/' . $uuid);
    $page->uncheckField('settings[label_display]');
    $page->pressButton('Update');
    $assert_session->pageTextNotContains('This is an override');
    $page->pressButton('Save layout');
    $assert_session->pageTextNotContains('This is an override');
  }

  
// Check that getComponents() returns options for all components.     $expected['name'] = [
      'label' => 'hidden',
      'type' => 'string',
      'weight' => -5,
      'settings' => [
        'link_to_entity' => FALSE,
      ],
      'third_party_settings' => [],
      'region' => 'content',
    ];
    $this->assertEquals($expected$display->getComponents());

    // Check that a component can be removed.     $display->removeComponent('component_3');
    $this->assertNULL($display->getComponent('component_3'));

    // Check that the removal is correctly persisted.     $display->save();
    $display = EntityViewDisplay::load($display->id());
    $this->assertNULL($display->getComponent('component_3'));

    // Check that createCopy() creates a new component that can be correctly
/** * Implements \Drupal\field_layout\Display\EntityDisplayWithLayoutInterface::setLayoutId(). */
  public function setLayoutId($layout_id, array $layout_settings = []) {
    if ($this->getLayoutId() !== $layout_id) {
      // @todo Devise a mechanism for mapping old regions to new ones in       // https://www.drupal.org/node/2796877.       $layout_definition = $this->getLayoutDefinition($layout_id);
      $new_region = $layout_definition->getDefaultRegion();
      $layout_regions = $layout_definition->getRegions();
      foreach ($this->getComponents() as $name => $component) {
        if (isset($component['region']) && !isset($layout_regions[$component['region']])) {
          $component['region'] = $new_region;
          $this->setComponent($name$component);
        }
      }
    }
    $this->setThirdPartySetting('field_layout', 'id', $layout_id);
    // Instantiate the plugin and consult it for the updated plugin     // configuration. Once layouts are no longer stored as third party settings,     // this will be handled by the code in     // \Drupal\Core\Config\Entity\ConfigEntityBase::set() that handles
/** * {@inheritdoc} */
  public function buildMultiple(array $entities) {
    $build_list = [];
    foreach ($entities as $key => $entity) {
      $build_list[$key] = [];
    }

    // Run field formatters.     foreach ($this->getComponents() as $name => $options) {
      if ($formatter = $this->getRenderer($name)) {
        // Group items across all entities and pass them to the formatter's         // prepareView() method.         $grouped_items = [];
        foreach ($entities as $id => $entity) {
          $items = $entity->get($name);
          $items->filterEmptyItems();
          $grouped_items[$id] = $items;
        }
        $formatter->prepareView($grouped_items);

        
return $widget;
  }

  /** * {@inheritdoc} */
  public function buildForm(FieldableEntityInterface $entity, array &$form, FormStateInterface $form_state) {
    // Set #parents to 'top-level' by default.     $form += ['#parents' => []];

    // Let each widget generate the form elements.     foreach ($this->getComponents() as $name => $options) {
      if ($widget = $this->getRenderer($name)) {
        $items = $entity->get($name);
        $items->filterEmptyItems();
        $form[$name] = $widget->form($items$form$form_state);
        $form[$name]['#access'] = $items->access('edit');

        // Assign the correct weight. This duplicates the reordering done in         // processForm(), but is needed for other forms calling this method         // directly.         $form[$name]['#weight'] = $options['weight'];

        
else {
        $this->removeSectionField($entity_type_id$bundle, OverridesSectionStorage::FIELD_NAME);
      }
    }

    $already_enabled = isset($this->original) ? $this->original->isLayoutBuilderEnabled() : FALSE;
    $set_enabled = $this->isLayoutBuilderEnabled();
    if ($already_enabled !== $set_enabled) {
      if ($set_enabled) {
        // Loop through all existing field-based components and add them as         // section-based components.         $components = $this->getComponents();
        // Sort the components by weight.         uasort($components, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
        foreach ($components as $name => $component) {
          $this->setComponent($name$component);
        }
      }
      else {
        // When being disabled, remove all existing section data.         $this->removeAllSections();
      }
    }
  }

  protected function getPathForFieldBlock($entity_type_id$bundle$view_mode$field_name) {
    $delta = 0;
    /** @var \Drupal\layout_builder\Entity\LayoutEntityDisplayInterface $display */
    $display = $this->container->get('entity_type.manager')->getStorage('entity_view_display')->load("$entity_type_id.$bundle.$view_mode");
    $body_component = NULL;
    foreach ($display->getSection($delta)->getComponents() as $component) {
      if ($component->getPluginId() === "field_block:$entity_type_id:$bundle:$field_name") {
        $body_component = $component;
      }
    }
    $this->assertNotNull($body_component);
    return 'layout_builder/update/block/defaults/node.after.default/0/content/' . $body_component->getUuid();
  }

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