2

If I define searchable fields via IElementType::defineSearchableAttributes(), the provided fields have to be model attributes. Can they also be getter-methods on the model class, which may return values from other related elements?

e.g. on Plugin_XYElementType.php:

public function defineSearchableAttributes()
{
    return ['relatedTitle','otherField'],
}

in Plugin_XYModel.php:

public function getRelatedTitle()
{
    return craft()->plugin_service->getTitleFromRelatedThing($this->relatedThingId);
}

Will this fields be correctly indexed and searchable in a ElementIndexView, where I use this related fields in a table column? Or does this only work for Attributes, that were defined via defineAttributes() ?

Thanks!

  • I'd love to know the answer to this too. If my element type model has a related model (e.g. a customer model related to the order element type) is it possible to allow searching on attributes of the related (customer) model from the ElementIndexView search field? If so, how do we set this up in our custom element type class? – Tim Everts May 4 '16 at 8:22
1

I have since discovered that searching on a related model is fairly easy to implement. You just define the related model as an attribute that can be searched on in defineSearchableAttributes method of the element type.

For example:

/**
 * @inheritDoc IElementType::defineSearchableAttributes()
 *
 * @return array
 */
public function defineSearchableAttributes()
{
    return ['dateCreated', 'totalPaid', 'customer'];
}

Then you just have to have a matching handler for that attribute (customer) in the modifyElementsQuery method, like so:

    if ($criteria->customer) {
        if ($criteria->customer instanceof MyPlugin_CustomerModel) {
            if ($criteria->customer->id) {
                $criteria->customerId = $criteria->customer->id;
                $criteria->customer = null;
            } else {
                return false;
            }
        }
    }

    if ($criteria->customerId) {
        $query->andWhere(DbHelper::parseParam('orders.customerId', $criteria->customerId, $query->params));
    }

Then once search indexes are rebuilt, you'll be able to search on all attributes of a customer.

  • So this allows you to enter 'Australia' or 'customer:Australia' to find all related customers with Australia as the country. But the big question is, how would you search specifically on just the country attribute of a customer (i.e. the customers.country attribute)? What is the search input syntax for that? – Tim Everts May 4 '16 at 9:18

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.