webman
webman

Reputation: 1203

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

Upvotes: 0

Views: 1202

Answers (3)

Richard Albrecht
Richard Albrecht

Reputation: 91

Check this workaround:

<f:variable name="counter" value="0" />

<!-- Loop over the elements -->
<f:for each="{bookings}" as="booking">
  <!-- Check if the criteria is met -->
  <f:if condition="{booking.paid}">
    <!-- Increment the counter -->
    <f:variable name="counter" value="{counter + 1}" />
  </f:if>
</f:for>
<!-- Display the counter-Variable -->
{counter}

Upvotes: 1

Paul Beck
Paul Beck

Reputation: 2683

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.

Upvotes: 1

Paul Beck
Paul Beck

Reputation: 2683

You can count them in the controller or use the GroupedFor ViewHelper https://fluidtypo3.org/viewhelpers/fluid/master/GroupedForViewHelper.html

Upvotes: 0

Related Questions