FOSCKEditorBundle

repository·2.x·Indexed 19 days ago

https://github.com/friendsofsymfony/fosckeditorbundle

A Symfony bundle that integrates CKEditor 4 into Symfony applications. It provides a dedicated `ckeditor` form type that extends the standard Symfony `textarea` type, allowing for granular configuration of rich-text editing within Symfony forms.

Tokens
15.3K
Snippets
60
Records
75
Agent score
68%

What's inside FOSCKEditorBundle

  1. Overview of FOSCKEditorBundle

    2.x
    FOSCKEditorBundle integrates CKEditor into Symfony via the Symfony Form Component. It automatically registers a new form type called ckeditor. This type extends the standard Symfony textarea type, meaning all existing textarea options are available and usable alongside CKEditor-specific configurations.
  2. How CKEditor language selection works

    2.x

    FOSCKEditorBundle determines the editor's language using a fallback mechanism:

    1. Automatic Guessing: The bundle first attempts to guess the language based on the current Symfony request locale.
    2. Container Parameter: If the request locale is unavailable, it falls back to the locale container parameter.
    3. Default: If neither is available, the editor uses its default language.

    You can override this automatic behavior by providing an explicit language configuration.

  3. Handle plugin dependencies and icons

    2.x

    Plugin dependencies

    If a plugin requires other plugins to function, you must install and register those dependencies using the same process (downloading to the web directory and registering via configuration or widget).

    Plugin icons

    If you are using a built-in or custom toolbar, the plugin icon should appear automatically based on the plugin's own configuration. If you are not using a configured toolbar, you are responsible for manually configuring the icon in your toolbar settings.

  4. Use JsonBuilder to construct JSON

    2.x

    The JsonBuilder allows you to construct JSON structures using the Symfony PropertyAccess Component syntax. This provides a way to build complex, nested JSON objects while maintaining control over value escaping.

    To use the builder, instantiate it and use setValues or setValue to populate the data, then call build() to generate the final JSON string.

    use FOS\CKEditorBundle\Builder\JsonBuilder;
    
    $builder = new JsonBuilder();
    $builder->setValues(['foo' => ['bar']]);
    $json = $builder->build();
  5. Configure CKEditor templates

    2.x

    You can define a collection of templates that users can insert into the editor. Each template requires a title and can optionally include an image, a description, and the html content to be inserted. You can also define an imagesPath to specify where template images are located.

    Templates can be configured globally via app/config/config.yml or locally within a form widget.

    # Global configuration in app/config/config.yml
    fos_ck_editor:
        default_config: my_config
        configs:
            my_config:
                extraPlugins: "templates"
                templates:    "my_templates"
        templates:
            my_templates:
                imagesPath: "/bundles/mybundle/templates/images"
                templates:
                    - title:       "My Template"
                      image:       "image.jpg"
                      description: "My awesome template"
                      html:        "<p>Crazy template :)</p>"
    // Local configuration in a widget
    $builder->add('field', 'ckeditor', [
        'config' => [
            'extraPlugins' => 'templates',
            'templates'    => 'my_template',
        ],
        'templates' => [
            'my_template' => [
                'imagesPath' => '/bundles/mybundle/templates/images',
                'templates'  => [
                    [
                        'title'       => 'My Template',
                        'image'       => 'images.jpg',
                        'description' => 'My awesome template',
                        'html'        => '<p>Crazy template :)</p>',
                    ],
                ],
            ],
        ],
    ]);
  6. Migrate from IvoryCKEditorBundle to FOSCKEditorBundle

    2.x

    If you are migrating from IvoryCKEditorBundle to FOSCKEditorBundle, follow these steps to update your dependencies, bundle registration, configuration, namespaces, and services.

    1. Update Composer dependencies

    Remove the old bundle and install the new one:

    composer remove egeloen/ckeditor-bundle
    composer require friendsofsymfony/ckeditor-bundle

    2. Update Bundle Registration

    Depending on your Symfony setup, update the bundle registration.

    For Symfony Flex (config/bundles.php): Replace Ivory\CKEditorBundle\IvoryCKEditorBundle::class with FOS\CKEditorBundle\FOSCKEditorBundle::class.

    For non-Flex applications (app/AppKernel.php): Replace new Ivory\CKEditorBundle\IvoryCKEditorBundle() with new FOS\CKEditorBundle\FOSCKEditorBundle().

    3. Update Configuration Root Key

    The configuration root key has changed from ivory_ck_editor to fos_ck_editor.

    In Symfony Flex (config/packages/fos_ck_editor.yaml):

    # Replace ivory_ck_editor: with:
    fos_ck_editor:
        configs:
            my_config:
                toolbar: [ ["Source", "-", "Save"], "/", ["Anchor"], "/", ["Maximize"] ]
                # ...

    In non-Flex applications (app/config/config.yml): Replace the ivory_ck_editor: root key with fos_ck_editor:.

    4. Update Namespaces

    Search your application for all occurrences of Ivory\CKEditorBundle\* and replace them with FOS\CKEditorBundle\*. For example, when using the form type:

    // Before
    use Ivory\CKEditorBundle\Form\Type\CKEditorType;
    
    // After
    use FOS\CKEditorBundle\Form\Type\CKEditorType;

    5. Update Service Definitions

    If you access services directly from the container, replace the service prefix ivory_ck_editor.* with fos_ck_editor.*.

    // Before
    $this->get('ivory_ck_editor.form.type');
    
    // After
    $this->get('fos_ck_editor.form.type');

    6. Regenerate Assets

    After migration, install the CKEditor assets and regenerate Symfony assets:

    bin/console ckeditor:install
    bin/console assets:install
  7. Use Symfony routes for filebrowser URLs (Dynamic Routing)

    2.x

    When route parameters depend on the specific object being edited (e.g., a blog post's slug), use the filebrowser*Handler option. This allows you to provide a closure that receives the Symfony RouterInterface to generate a dynamic URL.

    This is the most powerful method as it allows the URL generation to be aware of your application's dependencies and the current entity state.

    // Example: Generating a route based on a specific post slug
    $post = $manager->find($id);
    
    $builder->add('field', 'ckeditor', [
        'config' => [
            'filebrowserBrowseHandler' => function (RouterInterface $router) use ($post) {
                return $router->generate(
                    'my_route',
                    ['slug' => $post->getSlug()],
                    UrlGeneratorInterface::ABSOLUTE_URL
                );
            },
        ],
    ]);
  8. Install CKEditor Assets to the web directory

    2.x

    If you are not using Webpack Encore, you must manually install the downloaded assets into your web directory.

    • Symfony <= 2.8: $ php app/console assets:install web
    • Symfony >= 3.0 (without Flex): $ php bin/console assets:install web
    • Symfony with Flex: $ php bin/console assets:install public
    # Symfony with Flex
    $ php bin/console assets:install public
  9. Synchronize the CKEditor textarea value

    2.x

    When CKEditor transforms a textarea into a widget, the original textarea is no longer updated in real-time, which can cause issues when serializing forms or accessing the field value via JavaScript. You can enable automatic synchronization of the CKEditor content back to the underlying textarea using the input_sync option.

    You can enable this globally for all CKEditor instances in your configuration, or specifically for a single field in a Symfony FormBuilder.

    # Global configuration in app/config/config.yml
    fos_ck_editor:
        input_sync: true
    // Per-field configuration in a FormType
    $builder->add('field', 'ckeditor', [
        'input_sync' => true
    ]);
  10. Append custom JavaScript to CKEditor widgets using Twig

    2.x

    To inject custom JavaScript into all CKEditor widgets, you can override the default Twig template (@FOSCKEditor/Form/ckeditor_widget.html.twig) by overriding the ckeditor_widget_extra block.

    1. Create a new template file at app/Resources/views/Form/ckeditor_widget.html.twig.
    2. Extend the bundle's default template and implement the ckeditor_widget_extra block with your JavaScript code.
    3. Register the template in your Symfony configuration under twig.form_themes to ensure it overrides the default bundle template.
    {# app/Resources/views/Form/ckeditor_widget.html.twig #}
    {% extends '@FOSCKEditor/Form/ckeditor_widget.html.twig' %}
    
    {% block ckeditor_widget_extra %}
        CKEDITOR.dtd.$removeEmpty['span'] = false;
    {% endblock %}
    # app/config/config.yml
    twig:
        form_themes:
            - "::Form/ckeditor_widget.html.twig"
  11. Handle file browse and upload in CKEditor

    2.x

    FOSCKEditorBundle does not automatically handle file browsing or uploading. You must implement the backend logic (controllers/routes) yourself. Once implemented, you must configure the CKEditor instance to point to your URIs or Symfony routes.

    CKEditor natively supports the following URI-based options:

    • filebrowserBrowseUrl
    • filebrowserFlashBrowseUrl
    • filebrowserImageBrowseUrl
    • filebrowserImageBrowseLinkUrl
    • filebrowserUploadUrl
    • filebrowserFlashUploadUrl
    • filebrowserImageUploadUrl