rNix
rNix

Reputation: 2557

Use route as url in config with Symfony

I use CKEditor and want to use uploadimage plugin. I need to specify uploadUrl in config.yml. How can I put here a route instead of direct url?

ivory_ck_editor:
    default_config: my_config
    configs:
        my_config:
            extraPlugins: "lineutils,widget,notificationaggregator,uploadwidget,notification,uploadimage,wordcount"
            uploadUrl: '/admin/upload'

I know I can redefine config with form builder

$builder->add('field', 'ckeditor', array(
    'config' => array('uploadUrl' => ...),
));

But I want to do it once for every form. Which is the best way?

Upvotes: 0

Views: 171

Answers (1)

Cameron Hurd
Cameron Hurd

Reputation: 5031

If you define your form as a service, you could inject the router and use it to generate the path in your form. (This ignores the possibility of setting it in config.yml.)

services:
    app.form.type.yourformtype:
        class: AppBundle\Form\YourFormType
        arguments: [@router]
        tags:
            - { name: form.type }

Then, in your form:

<?php

namespace AppBundle\Form

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;

class YourFormType extends AbstractType
{
    private $router;

    public __construct(Router $router)
    {
        $this->router = $router;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $uploadRouteName = 'app_admin_upload'; // Or whatever maps out to /app/admin, re: your original question

        ...

        $builder->add('field', 'ckeditor', array(
            'config' => array('uploadUrl' => $this->router->generate($uploadRouteName)),
        ));

        ...

    }
}

To truly do this once for every form you should consider extending the ckeditor formtype and adding your route to uploadUrl in the configureOptions method using the OptionsResolver.. Then update the service definition to inject the router to that class, and in place of ckeditor in the second argument to add methods, use YourCkeditorExtendedType::class, and you won't need to add config each time.

Upvotes: 1

Related Questions