1

I'm trying to dynamically create an element query in PHP where the custom field criteria come from an array of strings. Something like this...?

$users = User::find();
$users->group($groupList);

foreach ($criteria as $key => $value) {
    // Each key value is the handle for a custom field and the
    // field value used as criteria
    $users->$key($value);
}

$users->all();

How can I use a custom field name in a string as a parameter?

Edit If I don't chain the criteria, I also get a deprecation error when I iterate over $users...Is there a better way to do that, too?

3

You can use the Craft::configure() for that.. imagine your array looks like

$criteria = [
    'age' => ['and', '>=30', '<=50'],
    'enabled' => false
    'status' => null,
]

You can do

$query = User::find();
Craft::configure($query, $criteria);

$users = $query->all();

Or you can just use the parameter based syntax instead of the functional one

$users->$key = $value;

You'll receive a deprecated error when you don't fetch your users. Your so called $users variable hast actually nothing to do with users it's a really bad name because one might think users store information about a list of users but that's not the case. $users is a Query that looks for elements with the type craft\elements\user in your database. You'll receive your list of users when you execute your Query with one(), all() or something like that.

  • I'll give this a shot and report back. Thanks, Robin! – Mark J. Reeves Apr 28 '18 at 23:48

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.