sonata-project / SonataPageBundle

This bundle provides a Site and Page management through container and block services
https://docs.sonata-project.org/projects/SonataPageBundle
MIT License
219 stars 210 forks source link

Block validation doesn't work properly in page composer #1318

Closed gremo closed 3 years ago

gremo commented 3 years ago

Environment

Sonata packages

show

``` $ composer show --latest 'sonata-project/*' sonata-project/admin-bundle 3.98.2 3.100.2 The missing Symfony Admin Generator sonata-project/block-bundle 3.23.1 4.6.0 Symfony SonataBlockBundle sonata-project/cache 1.1.1 2.1.1 Cache library sonata-project/cache-bundle 2.4.2 3.3.0 This bundle provides caching services sonata-project/classification-bundle 3.16.0 3.16.0 Symfony SonataClassificationBundle sonata-project/datagrid-bundle 3.3.0 3.3.0 Symfony SonataDatagridBundle sonata-project/doctrine-extensions 1.12.0 1.12.0 Doctrine2 behavioral extensions sonata-project/doctrine-orm-admin-bundle 3.34.0 3.34.2 Integrate Doctrine ORM into the SonataAdminBundle sonata-project/easy-extends-bundle 2.5.0 2.5.0 Symfony SonataEasyExtendsBundle sonata-project/exporter 2.6.2 2.6.2 Lightweight Exporter library sonata-project/form-extensions 1.9.0 1.9.0 Symfony form extensions sonata-project/formatter-bundle 4.5.0 4.5.0 Symfony SonataFormatterBundle sonata-project/intl-bundle 2.10.1 2.10.1 Symfony SonataIntlBundle sonata-project/media-bundle 3.31.1 3.31.2 Symfony SonataMediaBundle sonata-project/notification-bundle 3.12.0 3.12.0 Symfony SonataNotificationBundle sonata-project/page-bundle 3.22.0 3.22.2 This bundle provides a Site and Page management through con... sonata-project/seo-bundle 2.13.0 2.13.0 Symfony SonataSeoBundle sonata-project/twig-extensions 1.5.1 1.6.0 Sonata twig extensions sonata-project/user-bundle 4.11.1 4.11.1 Symfony SonataUserBundle ```

Symfony packages

show

``` $ composer show --latest 'symfony/*' symfony/apache-pack v1.0.1 v1.0.1 A pack for Apache support in Symfony symfony/asset v4.4.22 v4.4.25 Manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files and imag... symfony/browser-kit v4.4.22 v4.4.25 Simulates the behavior of a web browser, allowing you to make requests, click on links and submit form... symfony/cache v4.4.22 v4.4.25 Provides an extended PSR-6, PSR-16 (and tags) implementation symfony/cache-contracts v2.4.0 v2.4.0 Generic abstractions related to caching symfony/config v4.4.23 v4.4.25 Helps you find, load, combine, autofill and validate configuration values of any kind symfony/console v4.4.22 v4.4.25 Eases the creation of beautiful and testable command line interfaces symfony/css-selector v4.4.22 v4.4.25 Converts CSS selectors to XPath expressions symfony/debug v4.4.22 v4.4.25 Provides tools to ease debugging PHP code symfony/debug-bundle v4.4.20 v4.4.20 Provides a tight integration of the Symfony Debug component into the Symfony full-stack framework symfony/debug-pack v1.0.9 v1.0.9 A debug pack for Symfony projects symfony/dependency-injection v4.4.23 v4.4.25 Allows you to standardize and centralize the way objects are constructed in your application symfony/deprecation-contracts v2.4.0 v2.4.0 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v4.4.22 v4.4.25 Provides integration for Doctrine with various Symfony components symfony/dom-crawler v4.4.20 v4.4.25 Eases DOM navigation for HTML and XML documents symfony/dotenv v4.4.20 v4.4.25 Registers environment variables from a .env file symfony/error-handler v4.4.23 v4.4.25 Provides tools to manage errors and ease debugging PHP code symfony/event-dispatcher v4.4.20 v4.4.25 Provides tools that allow your application components to communicate with each other by dispatching ev... symfony/event-dispatcher-contracts v1.1.9 v2.4.0 Generic abstractions related to dispatching event symfony/expression-language v4.4.22 v4.4.25 Provides an engine that can compile and evaluate expressions symfony/filesystem v4.4.22 v4.4.25 Provides basic utilities for the filesystem symfony/finder v4.4.20 v4.4.25 Finds files and directories via an intuitive fluent interface symfony/flex v1.12.2 v1.13.3 Composer plugin for Symfony symfony/form v4.4.22 v4.4.25 Allows to easily create, process and reuse HTML forms symfony/framework-bundle v4.4.22 v4.4.25 Provides a tight integration between Symfony components and the Symfony full-stack framework symfony/http-client v4.4.22 v4.4.25 Provides powerful methods to fetch HTTP resources synchronously or asynchronously symfony/http-client-contracts v2.4.0 v2.4.0 Generic abstractions related to HTTP clients symfony/http-foundation v4.4.23 v4.4.25 Defines an object-oriented layer for the HTTP specification symfony/http-kernel v4.4.23 v4.4.25 Provides a structured process for converting a Request into a Response symfony/inflector v4.4.21 v4.4.25 Converts words between their singular and plural forms (English only) Package symfony/inflector is abandoned, you should avoid using it. Use use `EnglishInflector` from the String component instead instead. symfony/intl v4.4.22 v4.4.25 Provides a PHP replacement layer for the C intl extension that includes additional data from the ICU l... symfony/mailer v4.4.22 v4.4.25 Helps sending emails symfony/maker-bundle v1.30.2 v1.31.1 Symfony Maker helps you create empty commands, controllers, form classes, tests and more so you can fo... symfony/mime v4.4.22 v4.4.25 Allows manipulating MIME messages symfony/monolog-bridge v4.4.22 v4.4.25 Provides integration for Monolog with various Symfony components symfony/monolog-bundle v3.7.0 v3.7.0 Symfony MonologBundle symfony/options-resolver v4.4.20 v4.4.25 Provides an improved replacement for the array_replace PHP function symfony/orm-pack v2.1.0 v2.1.0 A pack for the Doctrine ORM symfony/phpunit-bridge v5.2.7 v5.3.0 Provides utilities for PHPUnit, especially user deprecation notices management symfony/polyfill-intl-grapheme v1.22.1 v1.23.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.22.1 v1.23.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-idn v1.22.1 v1.23.0 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions symfony/polyfill-intl-normalizer v1.22.1 v1.23.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.22.1 v1.23.0 Symfony polyfill for the Mbstring extension symfony/polyfill-php72 v1.22.1 v1.23.0 Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions symfony/polyfill-php73 v1.22.1 v1.23.0 Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions symfony/polyfill-php80 v1.22.1 v1.23.0 Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions symfony/process v4.4.22 v4.4.25 Executes commands in sub-processes symfony/profiler-pack v1.0.5 v1.0.5 A pack for the Symfony web profiler symfony/property-access v4.4.20 v4.4.25 Provides functions to read and write from/to an object or array using a simple string notation symfony/property-info v4.4.22 v4.4.25 Extracts information about PHP class' properties using metadata of popular sources symfony/proxy-manager-bridge v4.4.18 v4.4.25 Symfony ProxyManager Bridge symfony/routing v4.4.22 v4.4.25 Maps an HTTP request to a set of configuration variables symfony/security-acl v3.1.1 v3.1.2 Symfony Security Component - ACL (Access Control List) symfony/security-bundle v4.4.22 v4.4.25 Provides a tight integration of the Security component into the Symfony full-stack framework symfony/security-core v4.4.22 v4.4.25 Symfony Security Component - Core Library symfony/security-csrf v4.4.22 v4.4.25 Symfony Security Component - CSRF Library symfony/security-guard v4.4.20 v4.4.25 Symfony Security Component - Guard symfony/security-http v4.4.22 v4.4.25 Symfony Security Component - HTTP Integration symfony/serializer v4.4.22 v4.4.25 Handles serializing and deserializing data structures, including object graphs, into array structures ... symfony/serializer-pack v1.0.4 v1.0.4 A pack for the Symfony serializer symfony/service-contracts v2.4.0 v2.4.0 Generic abstractions related to writing services symfony/stopwatch v4.4.20 v4.4.25 Provides a way to profile code symfony/string v5.2.6 v5.3.0 Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme cluste... symfony/swiftmailer-bundle v3.5.2 v3.5.2 Symfony SwiftmailerBundle symfony/templating v4.4.20 v4.4.25 Provides all the tools needed to build any kind of template system symfony/test-pack v1.0.7 v1.0.8 A pack for functional and end-to-end testing within a Symfony app symfony/translation v4.4.21 v4.4.25 Provides tools to internationalize your application symfony/translation-contracts v2.4.0 v2.4.0 Generic abstractions related to translation symfony/twig-bridge v4.4.22 v4.4.25 Provides integration for Twig with various Symfony components symfony/twig-bundle v4.4.20 v4.4.25 Provides a tight integration of Twig into the Symfony full-stack framework symfony/twig-pack v1.0.2 v1.0.1 A Twig pack for Symfony projects symfony/validator v4.4.22 v4.4.25 Provides tools to validate values symfony/var-dumper v4.4.22 v4.4.25 Provides mechanisms for walking through any arbitrary PHP variable symfony/var-exporter v4.4.22 v4.4.25 Allows exporting any serializable PHP data structure to plain PHP code symfony/web-link v4.4.21 v4.4.25 Manages links between resources symfony/web-profiler-bundle v4.4.22 v4.4.25 Provides a development tool that gives detailed information about the execution of any request symfony/webpack-encore-bundle v1.11.2 v1.11.2 Integration with your Symfony app & Webpack Encore! symfony/yaml v4.4.22 v4.4.25 Loads and dumps YAML files ```

PHP version

$ php -v
PHP 7.4.7 (cli) (built: Jun  9 2020 13:34:30) ( NTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.7, Copyright (c), by Zend Technologies

Subject

Block validation doesn't work properly in page composer. I've used Sonata in many projects and block validation was working properly; I can't track which update broke that thing.

Steps to reproduce

  1. Create a block class (look down for a ready-to-paste code) with a simple text field and the NotBlank constraint
  2. Add the block to a page, using the page composer
  3. Save the block with an empty title
<?php

declare(strict_types=1);

namespace App\Block;

use Sonata\BlockBundle\Block\Service\AbstractBlockService as BaseAbstractBlockService;
use Sonata\BlockBundle\Block\Service\EditableBlockService;
use Sonata\BlockBundle\Form\Mapper\FormMapper;
use Sonata\BlockBundle\Meta\Metadata;
use Sonata\BlockBundle\Meta\MetadataInterface;
use Sonata\BlockBundle\Model\BlockInterface;
use Sonata\Form\Type\ImmutableArrayType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;
use Sonata\Form\Validator\ErrorElement;
use Symfony\Component\Templating\EngineInterface;

class TitleBlockService extends BaseAbstractBlockService implements EditableBlockService
{
    public function __construct(EngineInterface $templating)
    {
        parent::__construct($templating);
    }

    public function configureSettings(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'title' => null,
                'template' => 'block/block_title.html.twig',
            ])
        ;
    }

    public function validate(ErrorElement $errorElement, BlockInterface $block)
    {
        $errorElement
            ->with('settings[title]')
                ->addConstraint(new Assert\NotBlank())
            ->end()
        ;
    }

    public function configureCreateForm(FormMapper $form, BlockInterface $block)
    {
        $this->configureEditForm($form, $block);
    }

    public function configureEditForm(FormMapper $form, BlockInterface $block)
    {
        $form
            ->add('settings', ImmutableArrayType::class, [
                'keys' => [
                    ['title', null, [
                        'label' => 'Input a title',
                    ]],
                ],
            ])
        ;
    }

    public function getMetadata(): MetadataInterface
    {
        return new Metadata('Title');
    }
}

Expected results

The error (a red error text) is show right down the field itself.

Actual results

No errors is shown. The (browser) network console tab reports a 400 HTTP error. It seems that the returned JSON is fine, but the JavaScript fails updating the view:

Cattura

On the other hand, creating the same block from the interface under "blocks" works just fine:

Cattura2

VincentLanglet commented 3 years ago

For the record, the validate method is deprecated in Sonata 3 and will be removed in Sonata 4.

gremo commented 3 years ago

Hi @VincentLanglet , I know. What's the suggested alternative method and will it solve the issue describred?

VincentLanglet commented 3 years ago

I don't know the ImmutableArrayType

But if it was an classic TextType, the recommended way would be

$form->add('foo', TextType, ['constraints' => [new Assert\NotBlank()]]);

like you would have done with a Symfony form

gremo commented 3 years ago

Ok @VincentLanglet I'll give it a try. BTW, where I can find an example of how correctly implement a block service (I mean without deprecations etc.)? Because all sonata packages, even the sandbox, are missing that or are quite outdated.

Even the documentation here: https://sonata-project.org/bundles/block/master/doc/reference/your_first_block.html is using the validate method (which doesn't work anymore, as this issue explain).

VincentLanglet commented 3 years ago

Oh, I thought it was an admin. Maybe this validate method is not deprecated (but maybe should be).

I saw @jordisala1991 using it in https://github.com/sonata-project/SonataMediaBundle/pull/1963

BTW, in the doc it's ->with('settings.title') and you're doing setting[title] i don't know if it's the reason.

And shouldn't be this issue in SonataBlockBundle instead ?

gremo commented 3 years ago

@VincentLanglet I think is still relevant to SonataPageBundle because (if I'm right) it's something related how to returned JSON is parsed / error has shown. I'll try with ->with('settings.title') 👍

gremo commented 3 years ago

@VincentLanglet with ->with('settings.title') validation doesn't work at all (no errors, block is saved). With 'constraints' => [new Assert\NotBlank()] the same problem happens (no validation message appears).

EDIT: found a clue: app/block/380/edit?composer=1&uniqid=s9fdc9db89c must return the HTML fragment, but returns JSON instead. I think the offending commit is: https://github.com/sonata-project/SonataAdminBundle/commit/7d92242f230c070a8b993ad0d18def7b82fca29f introduced with v3.73.0, but I'm going to check further.

Basically, the problem is that page Composer works with HTML returned by the server, with error messages displayed inside it. But that commit changed the returned response to be JSON instead.

gremo commented 3 years ago

@VincentLanglet I've found the issue and the resolution 🥳 . I can't make a PR because npm run build does nothing on my system, don't know why. Assets are not created (sonata-page.back.js).

What's happening then? Well, this commit changed the way Ajax requests are threated. This is the related PR.

To put it simple:

  1. Page composer send requests using Ajax without any Accept header, that is */*
  2. That commit changed the Ajax request handling, as */* is now inside the getAcceptableContentTypes() array:
private function handleXmlHttpRequestErrorResponse(Request $request, FormInterface $form): ?JsonResponse
{
    if (empty(array_intersect(['application/json', '*/*'], $request->getAcceptableContentTypes()))) {
        // Do not handle the XmlHttpRequest
        return null;
    }

   // Return a JSON response
}

Before that commit, the same methods looks like:

private function handleXmlHttpRequestErrorResponse(Request $request, FormInterface $form): ?JsonResponse
{
    if (!\in_array('application/json', $request->getAcceptableContentTypes(), true)) {
        // Do not handle the XmlHttpRequest
        return null;
    }

     // Return a JSON response
}
  1. As a result, a JSON response is returned but SonataPageBundle can only handle HTML responses

Easy fix is adding an Accept header in assets/src/js/composer.js, inside the props of $.ajax:

headers: {
  Accept: 'text/html, application/xhtml+xml;'
},
VincentLanglet commented 3 years ago

Shouldn't you edit directly assets/src/js/composer.js and make a PR with this change ? I'm not sure to understand what you want to build. There is no sonata-page.back.js committed isn"t it ?

gremo commented 3 years ago

Well I think that one should edit assets/src/js/composer.js and then use npm run build (Gulp under the hood) to build the assets placed in Resources/public, which are committed (both minified and not minified version). I may be wrong but it seems reasonable.

For some reason when i run that command, assets are not created, that is Resources/public/js are still the old files, without my fix.

sonata-page.back.js
sonata-page.back.min.js
gremo commented 3 years ago

@VincentLanglet do you need anything else?

VincentLanglet commented 3 years ago

@VincentLanglet do you need anything else?

Someone with the time to do a PR to edit all of these files ^^'

gremo commented 3 years ago

I'll do it if someone (who?) can explain me the build process for the assets 🤣

VincentLanglet commented 3 years ago

I'll do it if someone (who?) can explain me the build process for the assets 🤣

Last PR on those file were https://github.com/sonata-project/SonataPageBundle/pull/973 There is also https://github.com/sonata-project/SonataPageBundle/pull/1209

Maybe @jlt10 @covex-nn can help you Also pinging @sonata-project/contributors

gremo commented 3 years ago

Is this project still active? It's a majoir issue I think, it's so sad seeing no one cares :(

VincentLanglet commented 3 years ago

The asset sonata-page.back.min.js is only supposed to be build if the sonata-page.back.js file is changed, so just open the PR with your assets/src/js/composer.js change.

gremo commented 3 years ago

Thanks @VincentLanglet I've submitted the PR, can you please check it and maybe release, so we can see if sonata-page.back.js will be changed?

VincentLanglet commented 3 years ago

It will be in the next release: https://github.com/sonata-project/SonataPageBundle/pull/1321

gremo commented 3 years ago

I confirm that it works now, thanks @VincentLanglet