How to override search results sort order in Plone

与世无争的帅哥 提交于 2019-12-04 21:46:37

问题


Plone search functionality is implemented in the plone.app.search package; the sort_on variable included in the request is used to control the sort order of the results on the search template.

By default, when this variable has no value, Plone uses relevance as sort order.

What's the easiest way of changing this to date (newest first)?


回答1:


You'll need to customize the search view to set new sorting options, and to alter the default sort when no sort has been set.

If you still need to be able to sort by relevance, use a non-empty value that you then change in the filter_query method:

from plone.app.search.browser import _, Search, SortOption

class MyCustomSearch(Search):
    def filter_query(self, query):
        query = super(MyCustomSearch, self).filter_query(query)

        if 'sort_on' not in query:
            # explicitly set a sort; if no `sort_on` is present, the catalog sorts by relevance
            query['sort_on'] = 'EffectiveDate'
            query['sort_order'] = 'reverse'
        elif query['sort_on'] == 'relevance':
            del query['sort_on']

        return query

    def sort_options(self):
        """ Sorting options for search results view. """
        return (
            SortOption(self.request, _(u'date (newest first'),
                'EffectiveDate', reverse=True
            ),
            SortOption(self.request, _(u'relevance'), 'relevance'),
            SortOption(self.request, _(u'alphabetically'), 'sortable_title'),
        )

Then register this view to your site; if you use a theme layer that'd be easiest:

<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:browser="http://namespaces.zope.org/browser"
    i18n_domain="plone">

    <browser:page
        name="search"
        layer=".interfaces.IYourCustomThemeLayer"
        class=".yourmodule.MyCustomSearch"
        permission="zope2.View"
        for="*"
        template="search.pt"
        />

    <browser:page
        name="updated_search"
        layer=".interfaces.IYourCustomThemeLayer"
        class=".yourmodule.MyCustomSearch"
        permission="zope2.View"
        for="Products.CMFCore.interfaces.IFolderish"
        template="updated_search.pt"
    />

</configure>

You'll need to copy over the search.pt and updated_search.pt templates from the plone.app.search package.



来源:https://stackoverflow.com/questions/15823413/how-to-override-search-results-sort-order-in-plone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!