2

Ok I'm building a plugin that needs to check for an id in an array and return only users that have the id in the checkbox array.

So this is what I have:

$user_criteria = craft()->elements->getCriteria(ElementType::User);
$user_criteria->interests = $interestId;
$users = $user_criteria->find();

interests is a dynamically created checkbox array which sits under the users profile. $interestId is the id I wish to look for in that array and return all users that have it.

Any help much appreciated.

1

The default Checkboxes field type stores its value to the database as a serialized PHP array. So for an entry with checkboxes "7", "12" and "32" checked, the value in the field_interests column is ["7","12","32"].

This is not query friendly at all, so the best solution would be to use a different field type.

But if you really want to use the checkboxes field, here's how you can query for your elements. Convert your criteria model to a DbCommand object and add a new WHERE clause with a LIKE condition to perform pattern matching. Include the quotes enclosing each ID in the pattern, this should make the query robust.

$user_criteria = craft()->elements->getCriteria(ElementType::User);

$query = craft()->elements->buildElementsQuery($user_criteria);
$params = array(
    ':interestId' => '%"'.$interestId.'"%',
);
$query->andWhere('field_interests LIKE :interestId', $params);
$results = $query->queryAll();

$users = EntryModel::populateModels($results);

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.