Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to add a custom block in sonata
{% extends 'SonataBlockBundle:Block:block_base.html.twig' %}
{% block block %}
<h2>{{ settings.title }}</h2>
<div class="sonata-feeds-container">
{% for meeting in meetings %}
<div>
<div>{{ meeting.date }}, {{ meeting.time }}</div>
<div>{{ meeting.location }}</div>
</div>
{% else %}
No upcoming meetings scheduled.
{% endfor %}
</div>
{% endblock %}
sonata_admin:
dashboard:
blocks:
- { position: right, type: my.block.service.meetings, settings: { title: Meetings } }
<?php
namespace My\Bundle\BlockBundle\Block;
use Symfony\Component\HttpFoundation\Response;
use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\BlockBundle\Block\BaseBlockService;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
class MeetingBlock extends BaseBlockService
{
function getDefaultSettings()
{
return array(
'title' => 'My Title'
);
}
/**
* @param FormMapper $form
* @param BlockInterface $block
*
* @return void
*/
function buildEditForm(FormMapper $form, BlockInterface $block)
{
$form->add('settings', 'sonata_type_immutable_array', array(
'keys' => array(
array('title', 'text', array('required' => false)),
)
));
}
/**
* @param BlockInterface $block
* @param null|Response $response
*
* @return Response
*/
function execute(BlockInterface $block, Response $response = null)
{
$settings = array_merge($this->getDefaultSettings(), $block->getSettings());
$meetings = array();
return $this->renderResponse('MyBlockBundle:Block:block.html.twig', array(
'settings' => $settings,
'meetings' => $meetings,
), $response);
}
/**
* @param ErrorElement $errorElement
* @param BlockInterface $block
*
* @return void
*/
function validateBlock(ErrorElement $errorElement, BlockInterface $block)
{
$errorElement
->with('settings.title')
->assertNotNull(array())
->assertNotBlank()
->assertMaxLength(array('limit' => 50))
->end();
}
}
services:
my.block.service.meetings:
class: My\Bundle\BlockBundle\Block\MeetingBlock
tags:
- { name: sonata.block }
arguments: ['nameofblock?', @templating ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment