Search code examples
phpsymfonytwigtwig-extension

Twig function: how to return a custom error


I'm writing a Twig function that creates some links from 1 to 5 and a parameter passed as variable, something like:

<a href="myurl.com/criterium=criterium1&value=my_value">text</a>

I know I can have only criterium1, criterium2 and criterium3, so I have an array with them inside and with in_array() I check that the passed critrium is a valid one.

But, if the criterium isn't in the fixed array, I want to return an error and tell the developer which are the allowed criteria.

How can I return this type of error from inside the Twig function?

Something like:

You passed the criterium "wrong_criterium". Only "criterium1", "criterium2" and "criterium3" are allowed.


Solution

  • If you wanna to throw an exception so you can just do it with

    throw new UndefinedOptionsException();
    

    If you wanna just to render some html error so you can do it with :

    return "<p class='error'>You passed the criterium 'wrong_criterium'. Only 'criterium1', 'criterium2' and 'criterium3' are allowed</p>";