5

I need some help with my code. I am creating blocks dynamically using the plugin derivatives. I store some form data in a database table, then I display it in each block separately, depending on it's derivative id. My issue is: while, I do obtain all the individual blocks on a full clear cache, in the "Place Block" section, it's not there when I submit the form, basically, I would like the form submit function to trigger the derivative creation and it's discovery. Any suggestions appreciated.

Here's my Plugin Derivative code:

<?php

namespace Drupal\simpleads\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class SimpleAdsBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $query = \Drupal::database()
            ->select('simpleads_blocks', 'sb')
            ->fields('sb');
        $results = $query->execute()->fetchAll();

    foreach ($results as $result) {
        $this->derivatives[$result->bid] = $base_plugin_definition;
        $this->derivatives[$result->bid]['admin_label'] = $result->name;
    }

    return $this->derivatives;
    }
}
4
  • 2
    You can do that by callling the clearCachedDefinitions() method of the plugin.manager.block service. However, are you sure you really need derivatives? Each plugin plugin can have configuration, and you can create as many instances as you want. You can often save a lot of complexity through that. Derivatives useful when it's based on some other configuration that you have anyway and/or if the definition can be diferent, e.g. views blocks.
    – Berdir
    Commented Jun 27, 2016 at 18:18
  • Thank you for the answer, it does help me out with the discovery of the blocks, I do need the derivatives, because I'm trying to migrate the SimpleAds module, and I need to create these blocks dynamically on each form submission. Each block does a views_embed_view inside of it with the simpleads bundle of nodes. Commented Jun 28, 2016 at 7:13
  • @Berdir, could you please post your comment as an answer, with a precise syntax for the clearing block cache in D8, so we can close this question? Commented Jun 29, 2016 at 6:24
  • I'm 99% sure you could do the same with configuration, e.g. by selecting the simple ads configuration thingy with configuration. But I'll post the command.
    – Berdir
    Commented Jun 29, 2016 at 11:32

1 Answer 1

6

Copied from BlockContent::postSave():

// Invalidate the block cache to update custom block-based derivatives.
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.