Reputation: 317
I have a symfony app with multipole relations and models, that worked well so far. I have an App model with a sourceSystem relation defined like this
/**
* @MaxDepth(2)
* @ManyToOne(targetEntity="SourceSystem", inversedBy="apps")
* @JoinColumn(name="sourceSystem_id", referencedColumnName="id")
*/
private $sourceSystem;
I now try to list the sourceSystems name in the view with {{app.sourceSystem.name}}
which fails with Impossible to access an attribute ("name") on a null variable in appstore_admin\list_apps.html.twig at line 25.
.
Next up, in my controller I try
/**
* @Route("/contentstore_admin/", name="appstore_list_apps")
* @Method({"GET"})
*/
public function listAppsAction()
{
$repository = $this->getDoctrine()->getRepository('AppBundle:App');
$apps = $repository->findAll();
/** @var App $app */
foreach ($apps as $app) {
dump($app->getSourceSystem()->getName());
}
// check if the user already has a trial license
return $this->render('appstore_admin/list_apps.html.twig', [
"apps" => $apps
]);
}
Which fails with Call to a member function getName() on null
but prints the system names into the debug bar.
I'm really confused by this behaviour and would like to make it work.
Upvotes: 0
Views: 812
Reputation: 36954
Since $app->getSourceSystem()
can returns a null
value, you need to check it before using it.
$sourceSystem = $app->getSourceSystem();
if ($sourceSystem) {
$name = $sourceSystem->getName();
}
or
{% if app.sourceSystem %}
{{app.sourceSystem.name}}
{% endif %}
If you don't want $sourceSystem
to be nullable, you can change the nullable
attribute.
@JoinColumn(name="sourceSystem_id", referencedColumnName="id", nullable=false)
Upvotes: 1