0

I use Craft CMS 4.2.5.2. I have a simple question, but I can't find an answer to it. I have a module. In it, I wrote a controller that runs through all the elements of the section and performs some actions on each element of the section. I need a condition with which I can check the element field for emptiness. I wrote this:

$entries = Entry::find()->section('products');

foreach($entries as $entry){
    if ($entry->getFieldValue('productApiId')){
        echo "field not empty<br />";
    }else{
        echo "field empty<br />";
    }        
}

But this design does not work. If the field is empty, the message "field empty" is not displayed. Tell me please.

1 Answer 1

0

It depends on what type of field productApiId is. If it's a simple number or text field, your code should work as is. But if it's a more complex field – for example, an Entries field, a Categories field, a Matrix field or a Super Table field – then getFieldValue will may return an object instead of a scalar value. All element relation fields (entries, categories, assets etc.) in particular return an ElementQuery object. For those fields, you need to check the result of the query to see if the field contains anything.

For example, if productApiId is an Entries field, you can check if the field has any elements selected like this:

$entry->getFieldValue('productApiId')->exists();

For all fields in general, check the documentation to see what kind of value they return. Some of those may be objects with their own way to tell if the object represents an empty value.

To find out what kind of value your field returns, you can use the useful debugging method Craft::dd:

\Craft::dd($entry->getFieldValue('productApiId'));
4
  • The productApiId field is a simple text! Unfortunately, but my code doesn't work. There are only two entries in my section. One has the field filled in, the other does not. The message "field not empty" prints only once. The message "field empty" does not output((
    – Dimi
    Commented Oct 25, 2022 at 20:31
  • this construction if ($entry->getFieldValue('productApiId')){ unable to return false. How to check for false?
    – Dimi
    Commented Oct 25, 2022 at 20:47
  • @Dimi That code is correct, you're likely seeing the effects of a secondary issue. Sometimes it's something simple like having a single space inside the text field, so it's technically not empty. Use Craft::dd as mentioned in the post to find out what getFieldValue is returning, this will tell you what's going wrong.
    – MoritzLost
    Commented Oct 26, 2022 at 8:26
  • thx, this info is usefull for me))
    – Dimi
    Commented Oct 27, 2022 at 18:17

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.