1

I'm developing a plugin and I'm searching a way to get all entries where a field exists (by id or handle). I'm trying to get all the entries even if the value of the field is null, empty or text.

I can't find a way to that. Can somebody help ?

1 Answer 1

1

Fields are related to entry types via their field layout.

You need to find all field layouts your field is attached to then find entry types using these field layouts. Once you have that, fetch all your entries by types.

If you already know your field's id, you don't need this but to find the id of your field by its handle:

$fieldId = Craft::$app->getFields()->getFieldByHandle('yourfieldHandle')->id;

Get all field layouts using that field:

$fieldLayouts = (new Query())
    ->select(['layoutId'])
    ->from(['{{%fieldlayoutfields}}'])
    ->where(Db::parseParam('fieldId', $fieldId))
    ->column();

Get all entry types using the field layouts you've just fetched:

$entryTypes = (new Query())
    ->select(['handle'])
    ->from([Table::ENTRYTYPES])
    ->where(Db::parseParam('fieldLayoutId', $fieldLayouts))
    ->column();

Or you can do both the above at once (get entry types by field id):

$entryTypes = (new Query())
    ->select(['entrytypes.handle'])
    ->from(['{{%entrytypes}} entrytypes'])
    ->innerJoin('{{%fieldlayoutfields}} fieldlayoutfields', '[[entrytypes.fieldLayoutId]] = [[fieldlayoutfields.layoutId]]')
    ->where(Db::parseParam('fieldlayoutfields.fieldId', $fieldId))
    ->column();

Once you have your entry types, get all entries matching:

$entries = Entry::find()->type($entryTypes)->all();

Altogether:

use Craft;
use craft\db\Query;
use craft\elements\Entry;

... 

// Fetch your field by its handle, if you know the id, just manually set it here
$fieldId = Craft::$app->getFields()->getFieldByHandle('yourFieldHandle')->id;

// Find all entryTypes using the fieldLayouts your field is attached to
$entryTypes = (new Query())
    ->select(['entrytypes.handle'])
    ->from(['{{%entrytypes}} entrytypes'])
    ->innerJoin('{{%fieldlayoutfields}} fieldlayoutfields', '[[entrytypes.fieldLayoutId]] = [[fieldlayoutfields.layoutId]]')
    ->where(Db::parseParam('fieldlayoutfields.fieldId', $fieldId))
    ->column();

// Find all entries by entryType
$entries = Entry::find()->type($entryTypes)->all();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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