ReynierPM
ReynierPM

Reputation: 18680

How to avoid FATAL error in Smarty templates while we check for objects

I am performing the following check in a Smarty template:

{{if $Pricing->getCommission()}}
    do something
{{/if}}

This is part of the class Pricing:

class Pricing {
    ...
    protected $commission;

    public function getCommission() {
        return $this->commission;
    }
}

$Pricing = new Pricing();

Then I use the $Pricing PHP object in the Smarty template. If $Pricing lacks of commission property, accessed through getCommission() public method this will turn into a FATAL and the application will thrown this to the view or in the best case display a blank page. I want to avoid that, how? I can't change how values are received meaning I can't get rid of the object on the template. Any advice?

Upvotes: 1

Views: 59

Answers (2)

ReynierPM
ReynierPM

Reputation: 18680

I've found the solution:

{{if $Pricing && $Pricing->getCommission()}}
    do something
{{/if}}

That way I will be checking if $Pricing is not null and if $Pricing->getCommission() is not null either.

Upvotes: 1

kartsims
kartsims

Reputation: 1008

Add an isset condition around your statement such as

{{if isset($Pricing->Commission)}} ...

Note that Commission must be a public property. Otherwise you should do as stated in the comment and add a check inside the getCommission method

Upvotes: 0

Related Questions