eZ Community » Forums » eZ Publish 5 Platform » Best way to check if a field is empty...
expandshrink

Best way to check if a field is empty in PHP

Best way to check if a field is empty in PHP

Friday 14 November 2014 12:33:05 pm - 5 replies

Hello all,

I am taking the big dive in eZ5 and have to re-learn a lot of basic stuff.

I am trying to check if a field is empty in a controller. I found the function isFieldEmpty in FieldHelper.php. What would be the cleanest way to use it ? 

Thank you very much

Modified on Friday 14 November 2014 12:33:27 pm by Paul Etienney

Friday 14 November 2014 2:51:23 pm

I might have reinvented the wheel. Here is my solution :

 

  public function isFieldEmpty($content, $fieldIdentifier) {
        $contentInfo = $content->contentInfo;
        $field = $content->getField($fieldIdentifier);
        $contentTypeService = $this->repository->getContentTypeService();        $fieldTypeService = $this->repository->getFieldTypeService();
        $contentType = $contentTypeService->loadContentType($contentInfo->contentTypeId);        $fieldDefinition = $contentType->getFieldDefinition($fieldIdentifier);        $fieldTypeIdentifier = $fieldDefinition->fieldTypeIdentifier;
        return $fieldTypeService->getFieldType($fieldTypeIdentifier)->isEmptyValue($field->value);
    }

Modified on Friday 14 November 2014 2:51:59 pm by Paul Etienney

Friday 14 November 2014 3:12:55 pm

Hi Paul

You may look at the implementation of the ez_is_field_empty Twig macro in https://github.com/ezsystems/ezpublish-kernel/blob/master/eZ/Publish/Core/MVC/Symfony/Templating/Twig/Extension/ContentExtension.php which makes basically the same.

For the use in Twig templates, I have wrapped this in a macro, which also checks wether a field is defined.

Cheers,
Donat

Friday 14 November 2014 3:20:30 pm

when i need that I just inject FieldHelper into my own service. looks clean to me. then i just do something similar to what ContentExtension does

return $this->fieldHelper->isFieldEmpty( $content, $fieldDefIdentifier, $forcedLanguage );

 

Modified on Friday 14 November 2014 3:21:13 pm by Carlos Revillo

Friday 14 November 2014 4:16:14 pm

+1 to the solution from Carlos. In a controller we do this:

if( $this->getContainer()->get( 'ezpublish.field_helper' )->isFieldEmpty( $content, $fieldDefIdentifier, $forcedLanguage )

This needs to be documented on confluence.ez.no.

Saturday 06 December 2014 2:43:37 pm

Answer approved, even though I'd rather inject it, including in controllers happy.gif Emoticon

And I'd add that this looks like a very clear use-case for this "intermediate" API we've been thinking off. The one that would sit between the public API and the developer, targetted towards day-to-day usage of eZ.

Modified on Saturday 06 December 2014 3:11:36 pm by Bertrand Dunogier

expandshrink

You must be logged in to post messages in this topic!

36 542 Users on board!

Forums menu

Proudly Developed with from