drupal 9 custom blocks dependency injection

Solutions on MaxInterview for drupal 9 custom blocks dependency injection by the best coders in the world

showing results for - "drupal 9 custom blocks dependency injection"
Benjamín
02 Oct 2018
1/**
2 * @file
3 * Contains \Drupal\mymod\Plugin\Block\MyModMyStoreProductsStatusBlock
4 */
5
6namespace Drupal\mymod\Plugin\Block;
7
8use Drupal\Core\Block\BlockBase;
9use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
10use Drupal\mymod\StoreService;
11use Symfony\Component\DependencyInjection\ContainerInterface;
12
13
14/**
15 * Provides a product status block for the store portal.
16 * 
17 * @Block(
18 *   id = "mymod_my_store_products_status_block",
19 *   admin_label = @Translation("My Store Products Status Block")
20 * )
21 */
22
23class MyModMyStoreProductsStatusBlock extends BlockBase implements ContainerFactoryPluginInterface {
24  // store service
25  protected $ss = NULL;
26  
27  /*
28   * static create function provided by the ContainerFactoryPluginInterface.
29   */
30  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
31    return new static(
32      $configuration,
33      $plugin_id,
34      $plugin_definition,
35      $container->get('mymod.store_mgr')
36    );
37  }
38  
39  /*
40   * BlockBase plugin constructor that's expecting the StoreService object provided by create().
41   */
42  public function __construct(array $configuration, $plugin_id, $plugin_definition, StoreService $ss) {
43    // instantiate the BlockBase parent first
44    parent::__construct($configuration, $plugin_id, $plugin_definition);
45    
46    // then save the store service passed to this constructor via dependency injection
47    $this->ss = $ss;
48  }
49  
50  /*
51   * return the render array with the vals provided by the injected store service.
52   */
53  public function build() {
54    return [
55      '#theme' => 'mymod_mystore_products_status_block',
56      '#n_total' => $this->ss->getTotalCount(),
57      '#n_active' => $this->ss->getActiveCount(),
58      '#sales_mtd' => $this->ss->getSalesMTD(),
59      '#n_products_sold' => $this->ss->getTotalSoldCount()
60    ];
61  }
62}