sortSearchPages example

// Declare entities out of their expected order so we can be sure they were     // sorted. We cannot mock these because of uasort(), see     // https://bugs.php.net/bug.php?id=50688.     $unsorted_entities['test4'] = new TestSearchPage(['weight' => 0, 'status' => FALSE, 'label' => 'Test4']);
    $unsorted_entities['test3'] = new TestSearchPage(['weight' => 10, 'status' => TRUE, 'label' => 'Test3']);
    $unsorted_entities['test2'] = new TestSearchPage(['weight' => 0, 'status' => TRUE, 'label' => 'Test2']);
    $unsorted_entities['test1'] = new TestSearchPage(['weight' => 0, 'status' => TRUE, 'label' => 'Test1']);
    $expected = $unsorted_entities;
    ksort($expected);

    $sorted_entities = $this->searchPageRepository->sortSearchPages($unsorted_entities);
    $this->assertSame($expected$sorted_entities);
  }

}

class TestSearchPage extends SearchPage {

  public function __construct(array $values) {
    foreach ($values as $key => $value) {
      $this->$key = $value;
    }
  }

  }

  /** * {@inheritdoc} */
  public function blockForm($form, FormStateInterface $form_state) {
    // The configuration for this block is which search page to connect the     // form to. Options are all configured/active search pages.     $options = [];
    $active_search_pages = $this->searchPageRepository->getActiveSearchPages();
    foreach ($this->searchPageRepository->sortSearchPages($active_search_pages) as $entity_id => $entity) {
      $options[$entity_id] = $entity->label();
    }

    $form['page_id'] = [
      '#type' => 'select',
      '#title' => $this->t('Search page'),
      '#description' => $this->t('The search page that the form submits to, or Default for the default search page.'),
      '#default_value' => $this->configuration['page_id'],
      '#options' => $options,
      '#empty_option' => $this->t('Default'),
      '#empty_value' => '',
    ];

  }

  /** * {@inheritdoc} */
  public function getDerivativeDefinitions($base_plugin_definition) {
    $this->derivatives = [];

    if ($default = $this->searchPageRepository->getDefaultSearchPage()) {
      $active_search_pages = $this->searchPageRepository->getActiveSearchPages();
      foreach ($this->searchPageRepository->sortSearchPages($active_search_pages) as $entity_id => $entity) {
        $this->derivatives[$entity_id] = [
          'title' => $entity->label(),
          'route_name' => 'search.view_' . $entity_id,
          'base_route' => 'search.plugins:' . $default,
          'weight' => $entity->getWeight(),
        ];
      }
    }
    return $this->derivatives;
  }

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