Search code examples
typo3fluidextbasetypo3-7.6.xviewhelper

TYPO3 count objects with constraint and display result in fluid template


I have build an extension with the extension builder that handles objects, an object can be an "item" or a "project".

An object has a field status which has 4 options, and is filled with an integer (3 = sold).

An object can be signed as a "project", in that case it has a boolean 1 for isproject and a field items with related objects as items.

this all works fine, I can iterate trough the projects with my fluid template and with <f:count>{object.items}</f:count> display the number of items appartaining to the project.

In the same fashion I should display the count of only the sold items ...
(<f:count where="object.items.status == 3">{object.items}</f:count> this obviously does not work, just to render the idea)

with <f:debug>{object}</f:debug> I see the field status defined for all items ...
since I have no idea how to approch this I might have left out some vital information


Solution

  • As indicated in the previous answer, you can use the GroupedFor ViewHelper for this purpose. But using it would be to much logic inside the fluid template thats the reason why this should be done in the controller, model or repository.

    Example: Adding a Getter to the Object-Model

    /**
     * @return int
     */
    public function getSoldItems() {
        $soldCount = 0;
        foreach($this->getItems() as $item) {
            // 0 = sold
            if($item->getStatus()===0) {
                $soldCount++;
            }
        }
        return $soldCount;
    }
    

    In fluid you can call the Getter with {object.soldItems}

    A better performance solution especially with lazy loading subobjects would be counting with the repository. For this you have to create a function in the repository and call it inside the Getter-Function. To use common repository methods for creating the query, you need a "Backrelation" of items to the object. Otherwise you have to write the query with "statement()" on your own.