将自定义操作添加到 Sonata 管理员



我创建了一个自定义操作,该操作在订单的显示模板底部呈现一个小表单。该表单是一个基本复选框和一个带有拖曳按钮的选择字段。它工作得很好,但渲染不正确。

我知道我渲染节目模板的方式不是 100% 正确的,因为当它渲染时,左侧菜单不再起作用。

这是我带有动作的自定义控制器;

namespace QiBssFrontendBundleController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationSecurity;
use SensioBundleFrameworkExtraBundleConfigurationMethod;
use SymfonyBundleFrameworkBundleControllerController;
use QiBssFrontendBundleCrudCrud;
use QiBssBaseBundleEntityBusinessPmodOrder;
use SymfonyComponentHttpFoundationRedirectResponse;
class PmodOrderController extends Controller
{   
    /**
     * @Route("/{id}/approve", name = "order_approve")
     * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
     * @Method({"GET", "POST"})
     */
    public function approveAction(Request $request, $id){
        $em = $this->getDoctrine()->getManager();
        $order = $em->getRepository('QiBssBaseBundle:PmodOrder')->find($id);
        $approveForm = $this->createFormBuilder($order)
            ->add('requireApproval', 'checkbox', array('label' => 'Require second Approval', 'required' => false, 'mapped' => false))
            ->add('secondApprover', 'choice', array('choices' => Crud::enumStatus(), 'label' => 'User', 'required' => false))
            ->getForm();
        $approveForm->handleRequest($request);
        if ($approveForm->isSubmitted() && $approveForm->isValid()) {
            $secondApproval = $request->request->get('form');
            $approval = $approveForm->getData();
            if (isset($secondApproval['requireApproval'])) {
                $approval->setStatus(PmodOrder::STATUS_PARTLY_APPROVED);
                $em->persist($approval);
                $em->flush();
                return new RedirectResponse($this->container->get('router')->generate('admin_bss_base_business_pmodorder_show', array('id' => $order->getId())));
            } else {
                $approval->setSecondApprover(NULL);
                $approval->setStatus(PmodOrder::STATUS_APPROVED);
                $em->persist($approval);
                $em->flush();
                return new RedirectResponse($this->container->get('router')->generate('admin_bss_base_business_pmodorder_show', array('id' => $order->getId())));
            }            
        }
        return $this->render('QiBssFrontendBundle:PmodOrder:order_approve.html.twig', array(
            'order' => $order,
            'form' => $approveForm->createView(),
        ));
    }
}

令我困扰的是,我实际上应该从Sonata的CRUDController延伸出来。当我这样做时,我得到一个错误;

呈现

模板期间引发异常 ("没有为控制器定义_sonata_admin PathToControllerPmodOrderController和电流 路线")

而且我也知道我实际上应该使用像return new RedirectResponse($this->admin->generateUrl('show'));这样的回报

此时,我不知道该怎么办了。如果有人可以指导我如何在我的情况下从CRUDController正确扩展,那将不胜感激

这里有一个例子,我不知道这是否是最好的解决方案,但我希望这可以帮助您:

1-创建自定义CRUD控制器:

# CustomCRUDcontroller.php :
class CustomCRUDDController extends Controller
{   
    /**
     * Show action.
     *
     * @param int|string|null $id
     * @param Request         $request
     *
     * @return Response
     *
     * @throws NotFoundHttpException If the object does not exist
     * @throws AccessDeniedException If access is not granted
     */
    public function showAction($id = null)
    {
        $request = $this->getRequest();
        // DO YOUR LOGIC IN THE METHOD, for example :
        if(isset($request->get('yourFormParam'))){
            $this->doTheJob();
        }
        $id = $request->get($this->admin->getIdParameter());
        $object = $this->admin->getObject($id);
        if (!$object) {
            throw $this->createNotFoundException(sprintf('unable to find the object with id : %s', $id));
        }
        $this->admin->checkAccess('show', $object);
        $preResponse = $this->preShow($request, $object);
        if ($preResponse !== null) {
            return $preResponse;
        }
        $this->admin->setSubject($object);
        return $this->render($this->admin->getTemplate('show'), array(
            'action' => 'show',
            'object' => $object,
            'elements' => $this->admin->getShow(),
        ), null);
    }
}

2-在admin.yml中注册:

# admin.yml :
x.admin.x:
        class: NamespaceYourAdminClass
        arguments: [~, NamespaceEntity, Namespace:CustomCRUD]
        tags:
            - {name: sonata.admin, manager_type: orm, group: X, label: X}

3-创建自己的custom_show.html.twig(只是位于Sonata-admin文件夹中的原始模板base_show.html.twig的复制和粘贴),在这里您可以在视图中显示额外的元素:

# custom_show.html.twig :
{% extends base_template %}
{% import 'SonataAdminBundle:CRUD:base_show_macro.html.twig' as show_helper %}
{% block actions %}
    {% include 'SonataAdminBundle:CRUD:action_buttons.html.twig' %}
{% endblock %}
{% block tab_menu %}
    {{ knp_menu_render(admin.sidemenu(action), {
        'currentClass' : 'active',
        'template': sonata_admin.adminPool.getTemplate('tab_menu_template')
    }, 'twig') }}
{% endblock %}
{% block show %}
    <div class="sonata-ba-view">
        {{ sonata_block_render_event('sonata.admin.show.top', { 'admin': admin, 'object': object }) }}
        {% set has_tab = (admin.showtabs|length == 1 and admin.showtabs|keys[0] != 'default') or admin.showtabs|length > 1 %}
        {% if has_tab %}
            <div class="nav-tabs-custom">
                <ul class="nav nav-tabs" role="tablist">
                    {% for name, show_tab in admin.showtabs %}
                        <li{% if loop.first %} class="active"{% endif %}>
                            <a href="#tab_{{ admin.uniqid }}_{{ loop.index }}" data-toggle="tab">
                                <i class="fa fa-exclamation-circle has-errors hide"></i>
                                {{ admin.trans(name, {}, show_tab.translation_domain) }}
                            </a>
                        </li>
                    {% endfor %}
                </ul>
                <div class="tab-content">
                    {% for code, show_tab in admin.showtabs %}
                        <div
                                class="tab-pane fade{% if loop.first %} in active{% endif %}"
                                id="tab_{{ admin.uniqid }}_{{ loop.index }}"
                        >
                            <div class="box-body  container-fluid">
                                <div class="sonata-ba-collapsed-fields">
                                    {% if show_tab.description != false %}
                                        <p>{{ show_tab.description|raw }}</p>
                                    {% endif %}
                                    {{ show_helper.render_groups(admin, object, elements, show_tab.groups, has_tab) }}
                                </div>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </div>
        {% elseif admin.showtabs is iterable %}
            {{ show_helper.render_groups(admin, object, elements, admin.showtabs.default.groups, has_tab) }}
        {% endif %}
    </div>
    {{ sonata_block_render_event('sonata.admin.show.bottom', { 'admin': admin, 'object': object }) }}
{% endblock %}

4-然后向您的管理员控制器指示,当当前路由为"显示"(而不是默认模板base_show.html.twig)时显示您的custom_show模板:

# YourEntityAdminController.php :
class YourEntityAdminController extends Controller
{
    // allows you to chose your custom showAction template :
    public function getTemplate($name){
        if ( $name == "show" )
            return 'YourBundle:Admin:custom_show.html.twig' ;
        return parent::getTemplate($name);
    }
}

相关内容

  • 没有找到相关文章

最新更新