core23/commonmark-formatter-bundle
Install the Bundle
composer require core23/commonmark-formatter-bundle
Ensure sonata-project/formatter-bundle is already installed (this bundle extends it).
Enable the Bundle
Add to config/bundles.php:
Core23\CommonMarkFormatterBundle\CommonMarkFormatterBundle::class => ['all' => true],
Configure Formatter
Update config/packages/sonata_formatter.yaml:
sonata_formatter:
formats:
commonmark:
extension: '.md'
mime_type: 'text/markdown'
providers: ['sonata.formatter.text.html', 'sonata.formatter.text.raw']
First Use Case Create a Markdown field in a Sonata Admin entity:
$formMapper
->add('content', 'sonata_formatter_type', [
'source_key' => 'content',
'source_field' => 'content',
'format_field' => 'format',
'formats' => ['commonmark'],
]);
Markdown in Admin Panels
Use sonata_formatter_type in Sonata Admin forms to render Markdown fields with syntax highlighting (via sonata.formatter.text.html provider).
Dynamic Formatting
Leverage the format_field option to store the selected format (e.g., commonmark or html) in the database and apply it dynamically:
$formatter = $this->get('sonata.formatter');
$content = $formatter->getContent($entity->getContent(), $entity->getFormat());
Custom Providers Extend the bundle by creating a custom provider (e.g., for GitHub-flavored Markdown):
# config/packages/sonata_formatter.yaml
sonata_formatter:
providers:
- { service: 'custom.commonmark.provider', type: 'text/html' }
Twig Integration Use the formatter in Twig templates:
{{ formatter.transform(content, format) }}
Provider Dependencies
The bundle relies on sonata.formatter.text.html for HTML output. Ensure it’s installed and configured:
composer require sonata-project/formatter-text-bundle
Caching Issues Clear the Symfony cache after installing/updating:
php bin/console cache:clear
Markdown Parsing Quirks
{{ content|raw }} in Twig if you need unprocessed Markdown.use League\CommonMark\Extension\Table\TableExtension;
$configurator->addExtension(new TableExtension());
Sonata Admin Conflicts If the formatter doesn’t render in Sonata Admin, ensure:
format_field is mapped to a database column (e.g., format).source_key matches the entity property name (e.g., content).APP_DEBUG=true) to inspect formatter errors.php bin/console debug:container sonata.formatter.provider
$markdown = "# Hello\n**World**";
$html = $formatter->getContent($markdown, 'commonmark');
Custom Formatter Override the default formatter service:
# config/services.yaml
services:
App\Formatter\CustomCommonMarkFormatter:
decorates: 'sonata.formatter.commonmark'
arguments: ['@.inner']
Post-Processing
Hook into the formatter’s transform method via events (if the bundle supports them) or decorate the service.
Configuration Overrides
Extend the bundle’s configuration in config/packages/core23_commonmark_formatter.yaml:
core23_commonmark_formatter:
default_options:
html_input: 'allow' # Allow HTML in Markdown
How can I help you explore Laravel packages today?