I am using an EntityFieldQuery with ->tableSort() and then adding a few columns to each row programatically. Is there a way to have tableSort() sort by my computed fields instead of only raw db fields? (Note: I don't mean the module Computed Field - which I now realize is probably the solution.)


Unfortunately not; an EntityFieldQuery is just an interface to a normal SQL query.

All values for computed fields are determined after the data has been loaded from the database (in the _computed_field_compute_value() function) so this won't be possible using the TableSort extender.

  • Two possible options for providing this functionality: 1. Add fields to the db table that are computed as the entity values change. Then use those as properties in a conventional EFQ. 2. Subclass EntityFieldQuery and override tableSort() with a function that could accept headers with type 'computed' and a callback function in the specifier that builds the computed field. Then modify tableSort() to make mysql sort if by db fields or load all rows and sort/limit by computed field in php. Thoughts? Jul 2 '12 at 21:11
  • Personally I wouldn't go with option 1; modifying core database tables is not considered good practice (even if you do it in a non-intrusive manner). I'm pretty sure you'd still need to subclass EntityFieldQuery to do that anyway so I'd go for option 2. It's a much more scalable (and pleasing) solution
    – Clive
    Jul 2 '12 at 21:17
  • For option 1, I was actually talking about adding properties to custom entities (not core). With option 2, performance would quickly become an issue since all rows would have to be loaded and computed fields would be computed on every query. What about an API that would use its own table to store the results of computed fields and provide an EFQ subclass that joined that table into the query? Actually, that would be very similar to just using Computed Field. Jul 2 '12 at 21:34
  • Ah if you're using custom entities that makes things a lot easier. Id go for option 1; I'm pretty sure all you'd need to do is implement hook_entity_presave() to loop through the fields on the entity, get the computed values, and assign them to the properties. Then they'd be persisted to the db and you can use them with a bog standard EntityFieldQuery
    – Clive
    Jul 2 '12 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.