Hot answers tagged

16

If you want to order by multiple columns that include custom fields, first make sure you're at least on Craft 2.4.2684, then you'll be able to use this syntax: {% for gallery in craft.entries.section('Gallery').order('postDate desc, available desc').limit(null) %} Also note that that you should be using limit(null) instead of limit(none) if you want to ...


13

You can do that using MySQL’s cast() function: craft.entries.section('mySection').order('cast(title as unsigned)') Alternatively, you might get better performance if you create an actual Number field called “numberTitle”, attach it to your Entry Type, and set the Entry Type’s title to be dynamically generated using the template “{numberTitle}”. Then you ...


13

The SuperSort Plugin is built for use cases exactly such as this. It allows you to render each object in your array using a Twig object template and sort the array based on the rendered value. For example, in OP's case, we could sort the combined array by the created_time variable like this: ... {% set feed = instagram|merge(community) %} {% set sortedFeed ...


12

Currently, the only way to add custom fields to the sortable attributes is to write a custom plugin which makes use of the modifyEntrySortableAttributes hook, e.g.: public function modifyEntrySortableAttributes(&$attributes) { $attributes['yourCustomFieldHandle'] = Craft::t('Label'); $attributes['anotherCustomField'] = Craft::t('Another label'); ...


9

The order param sets the ORDER BY part of the MySQL query. You can also pass MySQL functions in it. In your case GREATEST() should do the job: {% set allEntries = craft.entries .section(['publication','text', 'exhibition']) .order('GREATEST(releaseDate, publicationReleaseDate, exhibitionOpeningDate) desc') .limit(null) %}


8

This is only possible with a custom Twig Extension, since sorting a multidimensional array can't be done with Twig itself. I've written a plugin which extends Twigs sorting methods, which you could use as a base: Craft-TwigBetterSort. Just add this to the TwigBetterSortTwigExtension.php public function twig_sort($array, $method='asort', $sort_flag='...


7

That SQL code snippet Brad posted only works with the order parameter. The group filter doesn't allow SQL, but you could try to replicate the logic using Twig's ternary operator. {% set artists = craft.entries.section('lineup').order('(CASE WHEN field_sortTitle IS NULL OR field_sortTitle = "" THEN title ELSE field_sortTitle END)') %} {% set artistsGrouped = ...


7

Depends on how you want to determine "most popular"... If you want to calculate based on page views, then check out Ben Croker's Entry Count plugin (as Brad mentioned in his answer). If you want your users to vote on most popular, then check out my Upvote plugin, designed to emulate Stack Exchange or Facebook "likes".


5

You can't do that with core Craft functionality or Twig filters, but as Mats already suggested in the comments, you can do it with a plugin like "Super Sort". The template code to sort the array returned from the table field with that plugin would be: {% for row in entry.tablefield|supersort('sortAs', '{{ object.firstName }}') %}


5

Not at the moment. Sorting by custom field in the back end entries screen is not yet implemented although I know it is definitely possible in the future based on the way the code is currently laid out. I would create a front end method to list and sort the entries with links into edit with cpEditUrl http://buildwithcraft.com/docs/templating/categorymodel#...


5

Sure, I've had experience with two different types of sorting with SuperTable (check the link for associated JS). If you're modelling the fieldtype after a table, you might like to use the Craft.DataTableSorter method. Its pretty restrictive to a table layout, and you'll need to give each tr element a data-id. Craft.FieldType = Garnish.Base.extend({ ...


4

Twig doesn't have a natsort() filter. But I've put together a simple plugin which extends the sort-filter: https://github.com/victor-in/Craft-TwigBetterSort


4

There is nothing that will automatically sort blocks for you in the Control Panel. Without writing a plugin with some very fancy JavaScript, the only way to arrange blocks is manually. You can manually arrange your blocks by clicking & dragging the crosshairs in the upper-right corner of each block:


4

The natural sort order for related entries is the order defined in the control panel (not the post date of the related entries), unless you otherwise specify the sort order. Here is an example taken from one of my projects, where related articles are defined within an entries field-type in an article entry: {% set relatedArticles = entry.relatedArticles %} &...


4

This is a bit tricky to do from the template, but what I would suggest is to query for the Matrix blocks once, than loop through the blocks and store the data to a new custom array. The idea is, to build that array in a way that ensures, you can later apply sort and group Twig filters. {% set allDates = [] %} {% for block in entry.myEventsMatrix %} {% ...


4

One solution is to retrieve the entry ids for the season entries and all entries separately; subtract the 'season entry ids' from 'all entry ids' (using craft's without twig filter); then merge the two arrays back together (using twig's merge filter) in the proper order. You can then use this new id array to generate an elementCriteriaModel which can be used ...


4

Okay so you can either do this through ajax or through a page reload, a page reload is going to be much easier, but you can get it to work without reloading the page... Reloading the page You can basically make it so that when a user selects an option, use jQuery to redirect to the current page and append the <option> value to append as a query ...


3

Try using the replace filter inside SuperSort's micro-template: {% set foo = craft.entries.section('foo')... %} {% set sortAsList = { 'ShopType1': "A", 'ShopType2': "B", 'ShopType3': "C" } %} {% set sortedFoo = foo | supersort('sortAs', '{ shopType | replace(sortAsList) }') %} The first parameter you pass to SuperSort specifies the sort ...


3

There's a special loop variable available in for loops which provides info about the iteration. In your case you'd just insert that list item after the 2nd iteration: {% for entry in entriesOnPage %} <li class="class-A">{{ entry.title }}</li> {% if loop.index == 2 %} <li class="class-B">I'm am different</li> {% ...


3

It won't work with getPrev and getNext, as they only work with ElementCriteriaModels and not with an array of Entry models. But that is what you get returned from the plugin. Supersort converts your craft.entries ElementCriteriaModel into an array of Entry models. This is necessary so that it can do the sorting. The only workaround I know of would be to ...


3

I went and looked at the MatrixBlockModel; there's an attribute named sortOrder (If you output {{sortOrder}} inside the for loop, it will display the index of that block). You can use that attribute to sort by, in reverse: {% for cta in entry.ctas.order('sortOrder desc') %}


3

You could of course manually create a select query with a join that fetches entries ordered by hits descending, however you will basically be recreating what $criteria->find() does above. I imagine this will introduce an almost negligible performance improvement, but it really depends on how many entries you are returning. The following code should give ...


3

Seems to be the new standard since version 2.2.2582: "Entry and category search results now place a 5X weight on search term matches within Title fields."


3

Thanks for asking about this, Cole! There was a bug that was causing rsortAs to return erroneous results. The issue is fixed in the 1.0 release. Grab yourself a fresh copy and you should be squared away.


3

Rather than fetching the entries at first, just grab their IDs using ids() instead of find(): {% set featuredBlogId = craft.entries.section('blogs').limit(1).ids() %} {% set featuredArticleId = craft.entries.section('articles').limit(1).ids() %} {% set featuredSpecialReportId = craft.entries.section('specialReports').limit(1).ids() %} {% set ...


3

With that last {% set news = craft.entries.id(ids) %} criteria model you're querying in one locale only and there's no way to change that, Craft doesn't have a feature to set up a criteria model to query in multiple locales. You'd have to merge the entry models themselves and use something like the Super Sort plugin to bring them in order. {% set entriesA =...


3

You can get all of the works entries related to your contents Matrix field like so: {% set works = craft.entries({ relatedTo: { sourceElement: issue, field: 'contents.works' } }) %} They will most likely be out of order though. We can control that with the order parameter. If you enable Dev Mode and look at the resulting SQL query in your browser ...


3

In short, you need to set the selected attribute on the option element based on the sort order. So, if the sort order is title asc, then that option would have the selected (selected="selected") attribute set on it. I took the liberty to refactor your code to render sort options dynamically and make the selected sort order sticky by comparing the current ...


3

You are getting this error because the "entries" fields are always considered to be a query (ElementCriteriaModel) that can return more than one element. Therefore, if you know for sure that you will always have one and only one town linked to a business, you could do something like that: {% set businessesByTown = businesses|group('bizTown[0].title') %} If ...


3

According to SUBSTRING, the first character starts at 1. So if you wanted to start at the position immediate after The (with one space), you'd need to start at position 5. Just did a test locally and it works as expected for me if I use: .order('(CASE WHEN title LIKE "The %" THEN SUBSTRING(title, 5) ELSE title END ) asc')


Only top voted, non community-wiki answers of a minimum length are eligible