Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

Extending StringField Class - "Trying to get property of non-object" Error Message


Reply


2 Posts   652 Views

Avatar
_Matt

Community Member, 27 Posts

10 May 2013 at 10:50am

Edited: 10/05/2013 10:51am

I've written an extension called 'StringToKey' that converts a template value, such as $Title, into lowercase with the spaces changed into hyphens - a bit like when you do $Title.LowerCase, or $Title.UpperCase.

In my case I'm converting menu titles in my template, like this (in a Menu loop):

<ul class="submenu $Title.StringToKey">

It is working (the values are correctly output in the template), but I'm also getting a big error message at the top of the page:

"[Notice] Trying to get property of non-object"

It then highlights this line in my code:

$title = $this->owner->value;

Can anyone suggest why this might be happening, I'm a bit stuck? Here's my full code:

<?php
class StringToKey extends Extension
{
/**
* Return StringToKey
*
* @return string
*/
public function StringToKey()
{
$title = $this->owner->value;

if ($title != null)
{
return $this->convertString($title);
// var_dump($this->convertString($title));
}
else
{
return false;
}
}

/**
* Convert string to lowercase and replace spaces with hyphens
*
* @return string
*/
protected function convertString($string)
{
// Lower case everything
$string = strtolower($string);
// Make alphaunermic
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
// Clean multiple dashes or whitespace
$string = preg_replace("/[\s-]+/", " ", $string);
// Convert whitespace and underscores to hyphens
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
}

Avatar
_Matt

Community Member, 27 Posts

12 May 2013 at 1:23am

I worked out that the reason for the error was because the first result being returned was 'null'. Not sure why though?

Anyway, I added an additional check to filter out this error:

public function StringToKey()
{
if (!$this->owner instanceof Varchar) {
return false;
}

$title = $this->owner->value;
if ($title != null) {
return $this->convertString($title);
// var_dump($this->convertString($title));
} else {
return false;
}
}

Not sure if this is the best way to do things, but it's the only thing I could think of.