Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
gremo opened this issue Jun 3, 2021 · 19 comments · Fixed by #1323
Closed

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

gremo opened this issue Jun 3, 2021 · 19 comments · Fixed by #1323

Comments

@gremo
Copy link
Contributor

gremo commented Jun 3, 2021

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
Copy link
Member

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

@gremo
Copy link
Contributor Author

gremo commented Jun 4, 2021

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

@VincentLanglet
Copy link
Member

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
Copy link
Contributor Author

gremo commented Jun 4, 2021

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
Copy link
Member

VincentLanglet commented Jun 4, 2021

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

I saw @jordisala1991 using it in sonata-project/SonataMediaBundle#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
Copy link
Contributor Author

gremo commented Jun 4, 2021

@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
Copy link
Contributor Author

gremo commented Jun 7, 2021

@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: sonata-project/SonataAdminBundle@7d92242 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
Copy link
Contributor Author

gremo commented Jun 7, 2021

@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
Copy link
Member

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
Copy link
Contributor Author

gremo commented Jun 7, 2021

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
Copy link
Contributor Author

gremo commented Jun 8, 2021

@VincentLanglet do you need anything else?

@VincentLanglet
Copy link
Member

@VincentLanglet do you need anything else?

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

@gremo
Copy link
Contributor Author

gremo commented Jun 8, 2021

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

@VincentLanglet
Copy link
Member

VincentLanglet commented Jun 8, 2021

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

Last PR on those file were #973
There is also #1209

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

@gremo
Copy link
Contributor Author

gremo commented Jul 15, 2021

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

@VincentLanglet
Copy link
Member

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
Copy link
Contributor Author

gremo commented Jul 15, 2021

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
Copy link
Member

It will be in the next release: #1321

@gremo
Copy link
Contributor Author

gremo commented Jul 19, 2021

I confirm that it works now, thanks @VincentLanglet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants