R
R
RS-qrsk2021-07-14 10:09:46
symfony
RS-qrsk, 2021-07-14 10:09:46

How not to get an exception when returned NULL?

Knowledgeable people, tell me please.
How not to fall for symphony exceptions if the code is in the repository, for example

$this->em->getRepository(Test::class)->findOneBy(['test' => $test]);

returned NULL, and you already have getters in your controller, and they, in turn, are already defined in variables for rendering in twig?

It turns out that I need to check for NULL in the controller, and if true, then define empty strings and arrays in the variables for rendering? Or how to be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nord Dev, 2021-07-14
@RS-qrsk

Enter checks and that's it, hosh in php, hosh in twig and no errors will fly out

$test = $this->em->getRepository(Test::class)->findOneBy(['test' => $test]);

if (!empty($test)) {
   $name = $test->getName();
   $surname = $test->getSurname();
}

return $this->render('test/index.html.twig', [
   'test' => $test,
   'name' => $name ?? null,
   'surname' => $surname ?? null
]);

// в твиге
{% if test is not null %}
   <div>{{ test.name }}</div>
   <div>{{ test.surname }}</div>
{% endif %}

I
Igor, 2021-07-14
@IgorPI

$project = $projectRepository->find($project_id);

    if (!$project instanceof Project) {
         throw new NotFoundException("Project not found", "project_not_found");
    }
  
   // Здесь совершенно точно буддет объект.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question