Trying to get property 'Code' of non-object

Silverstripe Version:


this will happen if this code does not have a result. what i want is if there is no match, don’t show this error.

$members = AccessCode::get();
$access=$members->find('Code', 'eric')->Code;

As the error suggests, if there’s no object there, you can’t get a property on it. So, the thing to do is check that the object exists first. It would also make sense to assign a default value to the $access variable so you have nice, clean code.

For the specific example, I’d probably use get_one() to make it a bit neater and ensure the query is cached:

 $access = false;
 $member = AccessCode::get_one(AccessCode::class, ['Code' => 'eric']);
 if ($member) {
   $access = $member->Code;

(Obviously all untested!)