yadcf - 带有ajax serverSide和外部过滤器的数据表

时间:2016-04-22 08:06:57

标签: yadcf

我开发了一个应用程序,并使用了我的DataTable和Yadcf。

我的数据库中有很多数据,所以我习惯在ajax中搜索。

我需要在表格上方进行过滤,但现在只在表格的第一页上进行搜索。如何搜索整个图片?

我的代码:

JS

var oTable;


oTable = $('#table-announcement').DataTable({
    "processing": true,
    "serverSide": true,
    "bServerSide": true,
    "responsive": true,
    "stateSave": true,
    "autoWidth": false,
    "bJQueryUI": true,
    "bStateSave": true,
    //"ajax": "/app_dev.php/admin/avantages/announcement/datatable/add/ajax",
    ajax: {
        url: "/app_dev.php/admin/avantages/announcement/datatable/add/ajax",
        type: "POST"
    },
    "sAjaxDataProp": "data",
    "pageLength": 10,
    "paging": true,
    "searching": true,
    "bFilter": true,
    "order": [[ 1, 'desc' ]],
    "columnDefs": [{
        "targets": 'no-sort',  // no sort cols
        "orderable": false
    }],
    "language": {
        "lengthMenu": $lengthMenu,
        "zeroRecords": $zeroRecords,
        "info": $info,
        "infoEmpty": $infoEmpty,
        "infoFiltered": $infoFiltered,
        "searchPlaceholder": $searchPlaceholder,
        "search":$search,
        "sProcessing": $sProcessing,
        "oPaginate": {
            "sFirst":   $sFirst,
            "sLast":    $sLast,
            "sNext":    $sNext,
            "sPrevious": $sPrevious
        }
    },
    "columns":[
        {"data": "announcement"},
        {"data": "category"},
        {"data": "from"},
        {"data": "created_at"},
        {"data": "validationDate"},
        {"data": "priority"},
        {"data": "remainingValidate"},
        {"data": "status"},
        {"data": "nbcontacts"},
        {"data": "htmlActions"}
    ]
});



yadcf.init(oTable, [
    {column_number : 0,
        filter_type: "text",
        filter_container_id: 'external_filter_title',
        filter_default_label: "Titre"
    },
    { column_number : 1,
        select_type: 'select2',
        filter_container_id: 'external_filter_category',
        filter_default_label: "Rubrique"
    },
    {column_number : 2,
        filter_type: "text",
        filter_container_id: 'external_filter_user_announcement',
        filter_default_label: "De"
    },
    {column_number : 5,
        select_type: 'select2',
        filter_container_id: 'external_filter_priority',
        filter_default_label: "Urgence"
    },
    {column_number : 7,
        select_type: 'select2',
        column_data_type: "html",
        html_data_type: "text",
        filter_container_id: 'external_filter_status',
        filter_default_label: "Etat"
    }
],{   externally_triggered: true});

HTML

    <div class="filter-block tiny-full">
    <div class="row">
        <div class="col-xs-12 tiny-full list-count">
            <div>
                <span><b>{{ nbannouncement }}</b></span> {{ 'message.linkingAnnoucement.list.label_mer1'|trans }} <span><b>{{ nbAnnouncementsPending }}</b></span> {{ 'message.linkingAnnoucement.list.label_mer2'|trans }}
            </div>
            <div>

            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 filter-content">
            <div class="filter-table">
                <div class="filter-table-cell">
                    <div class="label_filter">{{ 'message.linkingAnnoucement.list.filter.filter_announcement'|trans }} </div><div class="filter"><span id="external_filter_title"></span></div>
                </div>
                <div class="filter-table-cell">
                    <div class="label_filter">{{ 'message.linkingAnnoucement.list.filter.filter_category'|trans }} </div><div class="filter"><span id="external_filter_category"></span></div>
                </div>
                <div class="filter-table-cell">
                    <div class="label_filter">{{ 'message.linkingAnnoucement.list.filter.filter_from'|trans }} </div><div class="filter"><span id="external_filter_user_announcement"></span></div>
                </div>
                <div class="filter-table-cell">
                    <div class="label_filter">{{ 'message.linkingAnnoucement.list.filter.filter_priority'|trans }} </div><div class="filter"><span id="external_filter_priority"></span></div>
                </div>
                <div class="filter-table-cell">
                    <div class="label_filter">{{ 'message.linkingAnnoucement.list.filter.filter_state'|trans }} </div><div class="filter"><span id="external_filter_status"></span></div>
                </div>
            </div>
        </div>
    </div>

</div>



<div class="row">
    <div class="col-md-12">
        <table class="table table-striped hover dataTable no-footer" id="table-announcement">
            <thead>
            <tr>
                <th class="col-md-3">
                    {{ 'message.linkingAnnoucement.list.tab.tab_announcement'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_category'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_from'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_created_date'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_diffusion_date'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_priority'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_time_remaining'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_state'|trans }}
                </th>
                <th class="col-md-1">
                    {{ 'message.linkingAnnoucement.list.tab.tab_nb_contact'|trans }}
                </th>
                <th class="col-md-1 no-sort">
                </th>
            </tr>
            </thead>
            <tbody class="panel-body">
            </tbody>
        </table>
    </div>
</div>

我的symfony controler

    public function paginateAction(Request $request)
{

    $this->initImgManager();

    $formatter = new \IntlDateFormatter(\Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE);
    $formatter->setPattern("d MMMM YYYY");
    $this->formatter = $formatter;

    $length = $request->get('length');
    $length = $length && ($length!=-1)?$length:0;

    $start = $request->get('start');
    $start = $length?($start && ($start!=-1)?$start:0)/$length:0;

    $search = $request->get('search');
    $filters = [
      'query' => @$search['value']
    ];

    $announcements = $this->getDoctrine()->getRepository('AppBundle:Announcement\Announcement')->search(
      $filters, $start, $length
    );

    $output = array(
      'data' => array(),
      'recordsFiltered' => count($this->getDoctrine()->getRepository('AppBundle:Announcement\Announcement')->search($filters, 0, false)),
      'recordsTotal' => count($this->getDoctrine()->getRepository('AppBundle:Announcement\Announcement')->search(array(), 0, false))
    );

    /**
     * @var Announcement $announcement
     */
    foreach ($announcements as $announcement)
    {

        // first image announcement
        if ($announcement->getPicturesFiles()->count() > 0)
        {
            $image = $announcement->getPicturesFiles()->first()->getFilePath();
            $handlingAnnouncementFirst = $this->imageHandlingManager->open($image)->zoomCrop(75, 75, 'transparent')->guess(100);
            $imageAnnouncementFirst = $this->assetsHelper->getUrl($handlingAnnouncementFirst);

            $htmlAnnouncement = '<figure>
                                    <img src="'.$imageAnnouncementFirst.'">
                                    <figcaption>
                                        '.$announcement->getTitle().'
                                    </figcaption>
                                 </figure>';
        }
        else
        {
            $htmlAnnouncement = '<figure>
                                    <figcaption>
                                        '.$announcement->getTitle().'
                                    </figcaption>
                                 </figure>';
        }

        // image user from
        if (!empty($announcement->getUsers()->getFile()))
        {
            $image = $announcement->getUsers()->getFile()->getFilePath();
            $handlingUser = $this->imageHandlingManager->open($image)->zoomCrop(45, 45, 'transparent')->guess(100);
            $imageUser = $this->assetsHelper->getUrl($handlingUser);

            $htmlUserFrom = '<div style="float:left;">
                                <figure>
                                    <img class="img-circle" src="'.$imageUser.'">
                                </figure>
                             </div>
                             <div style="float:left;">
                                '.$announcement->getUsers()->getFirstname().' '.$announcement->getUsers()->getLastname().'
                             </div>';
        }
        else
        {
            $htmlUserFrom = '<div style="float:left;">
                                <div class="job-resume-img-author"></div>
                             </div>
                             <div style="float:left;">
                                '.$announcement->getUsers()->getFirstname().' '.$announcement->getUsers()->getLastname().'
                             </div>';
        }


        // remaining time
        if (!empty($announcement->getDuration()->getDuration()) && !empty($announcement->getValidationDate()))
        {
            /** @var AppExtension $twigExtensionService */
            $twigExtensionService = $this->get('app.twig_extension');
            $requestAttributes = $this->container->get('request')->attributes;
            $remainingValidateAnnouncement = $twigExtensionService->remainingtimeFilter($announcement->getDuration()->getDuration(), $announcement->getValidationDate()->format('Y-m-d H:i:s'), $announcement->getId());
        }
        else
        {
            $remainingValidateAnnouncement = "-";
        }

        // status
        $htmlStatus = '<span class="label '.$announcement->getStatus()->getClassStatus().'">
                           '.$announcement->getStatus()->getName().'
                      </span>';

        // actions
        $translator = $this->get('translator');
        $tradAction = $translator->trans('message.common.btn.lib_action');
        $tradView = $translator->trans('message.common.btn.lib_action');
        $urlView = $this->generateUrl('avantages_backend_mer_edit', array("id" => $announcement->getId()));
        $htmlActions = '<div class="btn-group">
                            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                '.$tradAction.'
                                <i class="fa fa-chevron-down" aria-hidden="true"></i>
                            </button>
                            <ul class="dropdown-menu pull-right text-left">
                                <li><a href="'.$urlView.'">'.$tradView.'</a></li>
                            </ul>
                        </div>';


        $output['data'][] = [
          'announcement' => $htmlAnnouncement,
          'category' => $announcement->getCategory()->getName(),
          'from' => $htmlUserFrom,
          'created_at' => $this->formatter->format($announcement->getCreatedDate()),
          'validationDate' => (!empty($announcement->getValidationDate()) ? $this->formatter->format($announcement->getValidationDate()):'-'),
          'priority' => $announcement->getPriority()->getName(),
          'remainingValidate' => $remainingValidateAnnouncement,
          'status' => $htmlStatus,
          'nbcontacts' => $announcement->getLinkingsannouncements()->count(),
          'htmlActions' => $htmlActions,
        ];
    }

    return new Response(json_encode($output), 200, ['Content-Type' => 'application/json']);

1 个答案:

答案 0 :(得分:0)

由于您使用"bServerSide": true,您必须在服务器端实现过滤逻辑,就像在showcase page - Server side source example中一样,展示文件是用JAVA编写的,但您可以从源代码中获得一般性的想法那个can be found on github,一般来说你必须读取来自请求(JAVA)的过滤值

就像您阅读全局过滤器String globalSearch = req.getParameter("search[value]");

一样

您必须读取每列的过滤值(例如第一/第二个库)

String sSearch_0 = req.getParameter("columns[0][search][value]");
String sSearch_1 = req.getParameter("columns[1][search][value]");

此外,如果您要使用必须添加到当前JSON的值填充select / auto_complete过滤器,请使用以下属性yadcf_data_0 / yadcf_data_1 / etc' 其中每个属性包含一个字符串列表 例如:

"yadcf_data_0":["KHTML","Webkit","Trident","Misc","Other browsers","Tasman","Presto","Gecko"],

同样,您应该阅读showcase page

上的注释