Integrate SyliusSettingsBundle with SonataAdminBundle

Написана 13 Августа, 2015 в 19:45. Автор: borN_free   |   Теги: settings, sonata, bundle, admin Комментарии 5

Sonata is a great project that allows to build a rich Admin Dashboard. However, there is no integrated settings functionality in SonataAdminBundle.

Let's integrate an awesome SyliusSettingsBundle with Sonata's Admin Dashboard.

I assuming that you already have SonataAdminBundle installed. Let's install SyliusSettingsBundle.

Please see detailed installation procces in bundle's documentation (5 minutes to install):

SonataAdmin and SyliusSettingsBundle

Here is a structure of our AdminBundle where we will implement settings:

SonataAdmin and SyliusSettingsBundle - structure

Lets create our settings class. This file is used to generate settings form (see SyliusSettingsBundle's documentation):

namespace App\CoreBundle\Settings;

use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilderInterface;
use Symfony\Component\Form\FormBuilderInterface;

class AdminSettingsSchema implements SchemaInterface
{
    /**
     * @param SettingsBuilderInterface $builder
     */
    public function buildSettings(SettingsBuilderInterface $builder)
    {
        $builder
            ->setDefaults(
                [
                    'questions_per_quiz' => '80',
                    'questions_duration' => '8',
                    'question_time_limit' => '30',
                    'product_id' => '',
                    'contact_email' => '',
                ]
            )
            ->setAllowedTypes(
                [
                    'questions_per_quiz' => ['string'],
                    'questions_duration' => ['string'],
                    'question_time_limit' => ['string'],
                    'product_id' => ['string'],
                    'contact_email' => ['string'],
                ]
            );
    }

    /**
     * @param FormBuilderInterface $builder
     */
    public function buildForm(FormBuilderInterface $builder)
    {
        $builder
            ->add('questions_per_quiz')
            ->add('questions_duration')
            ->add('question_time_limit')
            ->add('product_id')
            ->add('contact_email', 'email')
        ;
    }
}

and service for it:

# src/CoreBundle/Resources/config/services.yml
services:
    app_core.settings_schema.meta:
        class: App\CoreBundle\Settings\AdminSettingsSchema
        tags:
            - { name: "sylius.settings_schema", namespace: "default" }

Then we create our Sonata's admin class:

namespace Application\Sonata\AdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Route\RouteCollection;
use Knp\Menu\ItemInterface as MenuItemInterface;
use Sonata\AdminBundle\Admin\AdminInterface;

class SettingsAdmin extends Admin
{
    /**
     * @var string
     */
    protected $baseRouteName = 'sonata_setting';

    /**
     * @var string
     */
    protected $baseRoutePattern = '/';

    /**
     * @var string
     */
    protected $translationDomain = 'SettingsAdmin';

    /**
     * @param RouteCollection $collection
     */
    protected function configureRoutes(RouteCollection $collection)
    {
        $collection->clear();
        $collection->add('update', '/settings');
        $collection->add(
            'list',
            '/settings',
            [
                '_controller' => 'Sylius\Bundle\SettingsBundle\Controller\SettingsController::updateAction',
                'namespace' => 'default'
            ]
        );
    }
}

Here we create only two routes:

  • update route: /settings URL will be used to open and update our settings form. Full URL will be: http://test.com/admin/settings
  • list route: this route is used to display Settings menu item on the sidebar. Without this route it will not be displayed. We just override controller and path here to use the same action as in the 'update' route.

We should also create a service for our admin class:

# src/Application/Sonata/AdminBundle/Resources/config/services.yml
quizzle_core.admin.settings:
        class: Application\Sonata\AdminBundle\Admin\SettingsAdmin
        arguments: [~, Sylius\Bundle\SettingsBundle\Model\Parameter, ApplicationSonataAdminBundle:SettingsAdmin]
        tags:
            - { name: sonata.admin, manager_type: orm, group: Settings, show_in_dashboard: true, label: Settings, label_translator_strategy: sonata.admin.label.strategy.underscore }
        calls:
            - [setFormTheme, [[SonataPageBundle:Form:form_admin_fields.html.twig, SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig]]]

Create an admin controller:

namespace Application\Sonata\AdminBundle\Controller;

use Sonata\AdminBundle\Controller\CRUDController;
use Sylius\Bundle\SettingsBundle\Controller\SettingsController;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Internal\Hydration\IterableResult;

/**
 * Class SettingsAdminController
 * @package Application\Sonata\AdminBundle\Controller
 */
class SettingsAdminController extends SettingsController
{
    /**
     * @param Request $request
     * @param string $namespace
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function updateAction(Request $request, $namespace = 'default')
    {
        $manager = $this->getSettingsManager();
        $settings = $manager->loadSettings($namespace);

        $form = $this
            ->getSettingsFormFactory()
            ->create($namespace)
        ;

        $form->setData($settings);

        if ($request->isMethod('POST') && $form->bind($request)->isValid()) {
            $manager->saveSettings($namespace, $form->getData());

            $message = $this->getTranslator()->trans('updated_successful', array(), 'SettingsAdmin');
            $this->get('session')->getFlashBag()->add('sonata_flash_success', $message);

            return $this->redirect($request->headers->get('referer'));
        }

        $admin_pool = $this->get('sonata.admin.pool');

        return $this->render('ApplicationSonataAdminBundle:Admin:settings.html.twig', array(
                'settings' => $settings,
                'form'     => $form->createView(),
                'admin_pool' => $admin_pool,
            ));
    }
}

Pretty straightforward code - load settings, create form and if form is submitted and is valid - add a flash message. The last file is a template to display our settings form:

{% extends 'SonataAdminBundle::standard_layout.html.twig' %}

{% form_theme form 'SonataAdminBundle:Form:form_admin_fields.html.twig' %}

{% block content %}
    

{{ 'dashboard.settings'|trans({}, 'SettingsAdmin') }}

{{ form_widget(form) }}
{% endblock %}

Enjoy!

5 comments

ответить
August 22, 2017 at 07:08 am

For a journalist, such theft carries risk. To run that cheap yeezy boost graph sans attribution, I’d have to assume that no other long-ago reader would remember it, and Gross wouldn’t see it. Should said assumptions chanel replica handbags backfire, I’d be fired. Were I a student caught in a similar situation, I’d fail the assignment fake rolex sale and probably be suspended or expelled. In either case, journalist or student, fear of getting caught shouldn’t be Cheap Longchamp the deterrent. You’re on fake chanel handbags an honor system; plagiarism is intellectually dishonest.

ответить
dang:
September 21, 2017 at 03:26 am

En 2000, Italo Fontana, petit-fils d'Ilvo, a découvert ces précieux dessins, qui devaient devenir sa source d'inspiration pour la création de la première montre U-Boat et sa nouvelle dimension dans le temps. Les <a href=http://www.frmontrepascher.eu">replique montres U-Boat sont caractérisées par leur forte identité, leur grande taille, leur lisibilité parfaite dans toutes les conditions météorologiques et légères, ainsi que leur design audacieux et distinctif: la couronne gauche protégée par une housse de sécurité spécialement conçue. Tout comme leur homonyme original, ces replique montre de luxe sont audacieuses, agressives et surdimensionnées.

La montre U-Boat U42 est un excellent exemple de cette combinaison au travail. Les cadrans robustes et les nombres surdimensionnés font que la replique montre soit rugueuse, et elle est tout aussi durable qu'elle apparaît.

ответить
September 21, 2017 at 03:27 am

<a href=http://www.frmontrepascher.eu">replique montres

ответить
September 21, 2017 at 03:28 am

<a href=http://www.frmontrepascher.eu">replique montres

ответить
September 25, 2017 at 01:22 am

The ultimate yacht party or beach vacation watch. After its release at Baselworld 2015, the Yacht-Master 40 with Oysterflex really turned some heads as it brought new variety to the rolex replica sale lineup.Pour commencer, on retrouve une connexion Bluetooth 4 LTE. Le minimum syndical pour être une replique montres connectée :pensuite, la Kronaby embarque un petit moteur pour vibrer, qui servira notamment pour les notifications.When it comes to fake chanel handbags, Boston’s most fashionable women know the beauty of the Brahmin handbag. Handcrafted in Massachusetts, each luxe creation is made from some of the finest leathers from Italy and all around the world. The intricate design process takes more than 24 artisans over 100 steps to handcraft each stylish bag.Our favorite bag is the Medium Asher Melbourne Tote in Denim available from the regular collection, a sturdy lightweight replica handbags that features two organizer pockets, an interior zip pocket and double adjustable handles, ideal for keeping everything inside neat and organized. The cheap mulberry bags creative director showed an unabashedly British collection that drew heavily from the stately-home circuit, but with a gritty edge that made the tweeds and equestrian details relevant to the fashion set in 2017.

Оставьте свой комментарий:

Поля с * обязательны.