简体   繁体   中英

Custom Sort of Magento Collection?

Here's the thing, I have product collection that I need to sort by their size. The size attribute values are XS, S, M, L, XL. When I put simply

addAttributeToSort('size', 'DESC')

it sorts them by alphabetical order of size attribute values (XS, XL, S, M, L).

Does anyone have any tip how to solve this?

Best I could think of is to create some new select field during the select process which will, through case command, have values 1,2,3,4,5, depending on the size value, and the sort it by that. But I don't know how to do that, or if it's even possible in Magento.

The fastest hack for this would be to have a second attribute that defines a proper sort order for the attributes, which I think you may have been referring to in your last paragraph. That would let you sort on that attribute itself. Of course, this requires extra data input to make work in your catalog.

Another thing you could try (I honestly don't know if this will work) is attempt to work with the admin/store level labels for your attribute. It's possible that Magento uses one over the other for sorting, though I am somewhat skeptical.

Hope that helps!

Thanks, Joe

Interesting question. You'll notice from my earlier question on sorting that Magento uses SQL ORDER BY statements for sorting by default. That will make it pretty hard to achieve what you need (IMHO) using the addAttributeToSort() approach.

You could use a similar approach to the answer that I posted to that question which basically converts the collection to an array of objects, then applies a custom sort function.

You need to create your own custom module and update your layout xml to point at the new block eg

<block type="navigation/dropdown" name="product_list" template="catalog/product/list_dropdown.phtml"/>

Hope this helps,
JD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM