emilie zawadzki
emilie zawadzki

Reputation: 2127

Sonata Block - Pass custom arguments

I'm new with Sonata Block Bundle. I would like to put into my block a map. It uses some JS library. Function of the context, I need to pass different height, width etc... for example. But I don't know if it fits with my needs.

At first, I wanted to use Sonata Block because my Maps has dependencies with some Services. So this is cool, I can centralise them.

But can I pass some arguments functions the parent who calls my block ?

Thanks for your answer.

Redfog

Upvotes: 0

Views: 1279

Answers (1)

Artamiel
Artamiel

Reputation: 3762

Okay, if I understood your question, what you want to do, is pass some custom arguments from your template (where you call your block to be precise) to the php class that is executing the block. Let's get started:

Lets add option to pass height attribute:

{% sample render of your block %}
{{ sonata_block_render({'type':'your.block.id'}, {'height': 50}) }}

Now, in your block service (php/class). You have to add this attribute as a default option in your method: setDefaultSettings, like this:

public function setDefaultSettings(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        // your options goes here, and we add our new option right after them
        'height' => null // or whatever suits your needs
    ));
}

Finally, all you have to is access your option from your execute method like this:

public function execute(BlockContextInterface $blockContext, Response $response = null) {
    $settings = $blockContext->getSettings();
    // now your value can be access from $settings['height'];
}

Let me know if that's what you're looking for.

Upvotes: 2

Related Questions