Maciej Chajda
Maciej Chajda

Reputation: 31

Symfony date to string conversion

Hey I am trying to make a href with current year and month, sent with get request to a controller function this way <a href="{{ path('transactions', {'year' : date("Y"), 'month' : date("n")}) }}"></a> and im getting "An exception has been thrown during the rendering of a template ("Warning: preg_match() expects parameter 2 to be string, object given")."

I assume that I am getting an object instead of string but I have no clue how to overcome it and I didn't found any reasonable way to solve it.

Upvotes: 0

Views: 330

Answers (2)

DarkBee
DarkBee

Reputation: 15662

To default way to do it inside twig is using NOW, e.g.

<a href="{{ path('transactions', {'year' : 'NOW'|date('Y'), 'month' : 'NOW'|date('m'), }) }}"></a>

documentation

Upvotes: 2

Maciej Chajda
Maciej Chajda

Reputation: 31

In a controler responsible for rendering this specific view i created 2 variables standing for current year and month and then i passed them to the view.

class MainController extends AbstractController
{
    /**
     * @Route("/", name="main")
     */
    public function index(): Response
    {
        $current_year = date('Y');
        $current_month = date('n');
        return $this->render('main/index.html.twig', [
            'current_year' => $current_year,
            'current_month' => $current_month,
        ]);
    }
}

In a view i render a href with following:

<a href="{{ path('transactions', {'year' : current_year, 'month' : current_month}) }}"></a

Upvotes: 0

Related Questions