如何在奏鸣曲管理员中显示自定义错误

I have MenuBundle and I want to show my custom error in sonata admin.

Admin : MenuAdmin.php

/**
 * {@inheritdoc}
 */
public function validate( ErrorElement $errorElement, $object ) {
    //
    if ( $object->getEnabled() == false && $object->getMenuType() == 'header' ) {
        $custom_error = 'Header menu cannot be disabled, please mark enabled to checked.';
        $errorElement->with( 'enabled' )->addViolation( $custom_error )->end();
    }
}

FormMapper in admin:

protected function configureFormFields( FormMapper $formMapper ) {
        $formMapper
            ->add( 'title' )
            ->add( 'menuType', 'choice', array(
                'choices'  => array(
                    'header'        => 'Header',
                    'footer_left'   => 'Footer Left',
                    'footer_right'  => 'Footer Right',
                    'footer_bottom' => 'Footer Bottom'
                ),
                'expanded' => true,
                'multiple' => false
            ) )
            ->add( 'enabled' );
    }

Validation is working fine but custom error is not appearing.

validation in admin

Solution # 1 : with ErrorElement.

simply use error_bubbling => true on field.

Note for solution # 1: Don't forget to add below use validator service in admin.

use Sonata\AdminBundle\Validator\ErrorElement;

Solution # 2: With Sonata - FLASH MESSAGES

I have done it by using Sonata - FLASH MESSAGES

$formMapper->add( 'enabled', null, array(
                'error_bubbling' => true
            ) );

MenuAdmin

/**
     * {@inheritdoc}
     */
    public function validate( ErrorElement $errorElement, $object ) {
        //
        if ( $object->getEnabled() == false && $object->getMenuType() == 'header' ) {
            $error = 'Header menu cannot be disabled, please mark enabled to checked.';
            $errorElement->with( 'enabled' )->addViolation($error)->end();
            $this->getRequest()->getSession()->getFlashBag()->add( "menu_type_check", $error );
        }

    }

YML

Path : YourBundle\Resources\config\admin.yml

sonata_core:
    flashmessage:
        error:
            #css_class: error_msg # optionally, a CSS class can be defined
            types:
                - { type: menu_type_check, domain: YourBundle }