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

时间:2015-12-30 10:16:25

标签: php symfony 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 in admin

1 个答案:

答案 0 :(得分:5)

解决方案#1:ErrorElement

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

  

注意解决方案#1:不要忘记在admin中添加以下use验证器服务。

     

使用Sonata \ AdminBundle \ Validator \ ErrorElement;

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

我是通过使用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

  

路径: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 }