We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 36834
    • 25 Posts
    Hopefully I've phrased the question correctly. Here's what I am trying do.

    When I retrieve a custom object from the db I would like to construct strings from various field values and have them available as a property of that object only at runtime. I can extend the model generated from the schema to provide a custom method to do this, but I have been trying to achieve the same with a constructor method, so that the temporary properties are available in every object without having to call a function.

    The first example below works fine but doesn't automatically create the property. The second example doesn't work because it creates a new empty object when the parent constructor is called rather than adding the property to the object instantiated with $object = $this->modx->getObject('myCustomTable', $id)

    Please can anybody point me in the right direction?

    Thanks in advance.

    class myCustomTable extends xPDOSimpleObject {
    	public $runtime_property;
    	public function get_runtime_property() {
    		return $this->getOne('RelatedTable')->get('value') . $this->another_value;
    	}
    }


    class myCustomTable extends xPDOSimpleObject {
    	public $runtime_property;
    	public function __construct(& $modx) {
    		parent::__construct($modx);
    		$this->runtime_property = $this->getOne('RelatedTable')->get('value') . $this->another_value;
    	}
    }

      • 22303 MODX Staff
      • 10,725 Posts
      If you set xPDO::OPT_HYDRATE_ADHOC_FIELDS to true, xPDOObjects will support get() and set() on those properties, and they can also be accessed using toArray() and fromArray().

      As for the constructor, I would make sure you have a RelatedTable instance before trying to get a value from it.
        • 36834
        • 25 Posts
        Thanks for your help.

        I think I get it now - it's not possible to use properties from the database in the constructor as they don't exist at that point.