Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Editorjs Bundle Laravel Package

darylseven/editorjs-bundle

Symfony bundle integrating Editor.js with Symfony Forms and Twig. Adds an EditorjsType form field, configurable editor setups, and a Twig helper to render/init the editor. Includes example config and JS init (Encore/webpack).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Bundle

    composer require tbmatuka/editorjs-bundle
    

    Ensure Tbmatuka\EditorjsBundle\TbmatukaEditorjsBundle::class is added to config/bundles.php.

  2. Configure the Bundle Copy examples/editorjs.yaml to config/packages/editorjs.yaml and adjust settings (e.g., default tools, CDN paths).

  3. Set Up Twig Add the form theme to config/packages/twig.yaml:

    twig:
        form_themes:
            - '@TbmatukaEditorjs/Form/editorjs_widget.html.twig'
    
  4. Install Editor.js via npm (Encore)

    npm install @editorjs/editorjs @editorjs/header @editorjs/paragraph
    

    Copy examples/editorjs-init.js to your assets/js/ directory and import it in your Encore entry file.

  5. Use in a Symfony Form

    use Tbmatuka\EditorjsBundle\Form\Type\EditorjsType;
    
    $builder->add('content', EditorjsType::class, [
        'config' => ['tools' => ['header', 'paragraph']],
    ]);
    
  6. Render the Form

    {{ form_start(form) }}
        {{ form_row(form.content) }}
        <button type="submit">Save</button>
    {{ form_end(form) }}
    

First Use Case

Replace a textarea in a blog post form with EditorjsType to enable rich-text editing. The bundle handles JSON serialization/deserialization automatically, so submitted data is stored as an array in your database.


Implementation Patterns

Common Workflows

1. Basic Form Integration

  • Use EditorjsType in Symfony forms for structured rich-text input.
  • Example:
    $builder->add('description', EditorjsType::class, [
        'config' => [
            'tools' => [
                'header' => HeaderTool,
                'paragraph' => ParagraphTool,
                'list' => ListTool,
            ],
            'placeholder' => 'Enter content here...',
        ],
    ]);
    

2. Dynamic Tool Configuration

  • Pass different toolsets per form or entity:
    $tools = ['header', 'paragraph', 'image']; // Image tool requires custom upload handler
    $builder->add('content', EditorjsType::class, ['config' => ['tools' => $tools]]);
    

3. Twig Extension for Reusable Configs

  • Define configs in editorjs.yaml and reference them in Twig:
    # config/packages/editorjs.yaml
    editorjs:
        configs:
            blog_post:
                tools: ['header', 'paragraph', 'embed']
                placeholder: 'Write your blog post...'
    
    {{ form_row(form.content, {'config': 'blog_post'}) }}
    

4. Handling Submitted Data

  • Submitted data is an array of blocks. Store it in Doctrine:
    // Entity
    #[ORM\Column(type: 'json')]
    private array $content = [];
    
    // Form handler
    $entity->setContent($form->get('content')->getData());
    

5. Encore Asset Management

  • Configure Editor.js in your Encore entry file:
    // assets/js/editor-init.js
    import EditorJS from '@editorjs/editorjs';
    import Header from '@editorjs/header';
    import Paragraph from '@editorjs/paragraph';
    
    export default (selector, config) => {
        const editor = new EditorJS({
            ...config,
            tools: {
                header: Header,
                paragraph: Paragraph,
            },
        });
        editor.render().then(() => {
            document.querySelector(selector).appendChild(editor.rendered);
        });
        return editor;
    };
    
  • Import in webpack.config.js:
    Encore
        .addEntry('editorjs', './assets/js/editor-init.js')
        .enableSingleRuntimeChunk();
    

6. Custom Tools

  • Create a custom tool (e.g., AlertTool) and register it:
    // assets/js/tools/AlertTool.js
    export default class AlertTool {
        static get toolbox() { return 'alert'; }
        // ... implementation
    }
    
    # config/packages/editorjs.yaml
    editorjs:
        configs:
            custom_tools:
                tools: ['header', 'paragraph', 'alert']
    

Integration Tips

Symfony 8-Specific

  • Form Themes: Symfony 8 may require adjustments to the Twig form theme path. Verify compatibility with twig.form_themes.
  • PHP 8.1+: Use named arguments and union types in custom tool configurations if extending the bundle.

Performance

  • Lazy-Load Plugins: Dynamically import Editor.js plugins in Encore to reduce bundle size:
    // assets/js/editor-init.js
    const loadPlugin = (name) => import(`@editorjs/${name}`).then(module => module.default);
    
  • Cache Editor.js: Use Symfony’s asset cache or CDN for production.

Security

  • Sanitize Output: Validate and sanitize Editor.js JSON output before storage:
    use Symfony\Component\Validator\Constraints as Assert;
    
    #[Assert\Type(type: 'array')]
    #[Assert\All({
        new Assert\Type(type: 'array'),
        new Assert\NotBlank(),
    })]
    private array $content;
    

Testing

  • Unit Test Forms: Mock EditorjsType in PHPUnit:
    $formFactory = $this->createMock(FormFactoryInterface::class);
    $form = $formFactory->createNamedBuilder('content', EditorjsType::class, null, [
        'config' => ['tools' => ['header']],
    ]);
    
  • JavaScript Tests: Use Jest or Cypress to test Editor.js initialization and tool behavior.

Gotchas and Tips

Pitfalls

  1. Encore Dependency

    • The bundle requires Encore/Webpack for JS asset management. If you’re not using Encore, you’ll need to:
      • Manually load Editor.js from a CDN (undocumented; may require custom JS).
      • Use Vite or Laravel Mix with custom webpack configurations.
    • Workaround: Fork the bundle to add CDN support or use a standalone Editor.js setup.
  2. Symfony 8 Form System Changes

    • Symfony 8 introduced changes to FormBuilder and Twig forms. Test the bundle with:
      • New FormBuilder::add() syntax.
      • Twig 3+ template inheritance.
    • Tip: Check for deprecation warnings in Symfony 8’s form system.
  3. JSON Data Handling

    • Submitted data is an array, but Doctrine may not handle nested JSON well. Use:
      #[ORM\Column(type: 'json')]
      private array $content;
      
    • Gotcha: Deeply nested blocks may exceed database limits. Consider flattening or using a dedicated JSON column type.
  4. Plugin Compatibility

    • Not all Editor.js plugins are compatible with the bundle. Test plugins like:
      • @editorjs/image: Requires custom upload handlers.
      • @editorjs/embed: May need additional configuration for security.
    • Tip: Use npm install to ensure plugin versions match your Editor.js core version.
  5. Twig Template Overrides

    • The default Twig template (editorjs_widget.html.twig) may not fit your theme. Override it in:
      templates/bundles/TbmatukaEditorjs/Form/editorjs_widget.html.twig
      
    • Gotcha: Symfony 8’s Twig 3+ may require adjustments to template syntax.
  6. CSRF and Validation

    • Ensure Editor.js submissions include CSRF tokens. The bundle handles this if using Symfony forms, but custom JS may bypass it.
    • Tip: Validate the JSON structure server-side:
      $validator = $this->container->get('validator');
      $errors = $validator->validate($form->getData());
      
  7. Browser Support

    • Editor.js requires modern browsers. Test in:
      • Chrome, Firefox, Edge (latest versions).
      • Safari (may need polyfills for older versions).
    • Tip: Add a fallback for unsupported browsers in your Twig template.

Debugging Tips

  1. Check Console for JS Errors

    • Open browser dev tools (F12) to debug Editor.js initialization:
      console.log('EditorJS initialized:', editor);
      
    • Common errors:
      • Uncaught TypeError: editorjs__WEBPACK_IMPORTED_MODULE_0___default.a is not a constructor: Missing or incorrect plugin imports.
      • Failed to load resource: CDN or asset path issues.
  2. Validate Config

    • Ensure config/packages/editorjs.yaml is correctly formatted:
      editorjs:
          configs:
              default:
                  tools
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
symfony/ai-symfony-mate-extension
aashan/pimcore-mcp-bundle
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin