如何在 sonata admin 中显示自定义错误

how to show custom error in sonata admin

我有 MenuBundle,我想在 sonata 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.

解决方案#1:用ErrorElement.

只需在字段上使用error_bubbling => true

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

use Sonata\AdminBundle\Validator\ErrorElement;

解决方案 # 2:使用 Sonata - FLASH MESSAGES

我用Sonata - FLASH MESSAGES

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

菜单管理

/**
     * {@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 }