Welcome, Guest
Username: Password: Remember me

TOPIC: [HOW TO] Cascad populateObjects()

The populateObjects() method and its possibilities 15 Apr 2013 13:54 #7048

  • vlemos
  • vlemos's Avatar
  • Online
  • Elite Member
  • Posts: 295
  • Thank you received: 41
  • Karma: 21
Hi All

As stated under the post "populateObjects(&$item) Not loading 3rd level item", an easy to use populateObjects method is integral to the development of my current project. J-Cook provides an excellent environment for this type of development.

Since I believe that the framework can and should handle recursive object population natively. I have spent a bit of time looking at ways to do just that. The submission below is a small refinement of my original implementation which did not cascade an explicit call to its children.

The code can be inserted in to the empty populateObjects method of the "jmodel.list.php" file. In its current form, it requires that a naming rule is followed:
<model[name]>.<state[context]>

To set the state "barking" from the "view.html.php" file you would use:
For a list object this would be "dogs.barking" -> $modellist->setState(dogs.barking, true);
For an item it would become "dogitem.barking" -> $modellist->setState(dogitem.barking, true);
and would execute the "barking" routine of each model in its path.
	/**
	* Prepare some additional related objects.
	*
	* @access	public
	* @param	array	&$items	The objects to populate.
	* @return	void
	*/
	public function populateObjects(&$items)
	{
		if (!isset($items) || empty($items))
			return;

		$model = JModel::getInstance($this->view_item, 'XxxModel');

		// If the state was explicitly called, cascad it to the children
		$state = preg_replace("/^\w+/", $this->name, $this->state->get('context') );
		if ( $this->getState($state) )
		{
			$state = preg_replace("/^\w+/", $this->view_item, $this->state->get('context') );
			$model->setState( $state, true );

		}

		foreach ($items as &$item)
		{
			if ( $model && method_exists( $model, 'populateObjects' ) )
			{
				$model->populateObjects($item);

			}

		}

	}
This should cascade the populateObjects method to any level without the need to code each for-loop in the retrieval path.

Feel free to comment on its pros and cons, how it may be improved, etc.

Regards
v

Also hope it can help someone who may be coding this feature...


Item model
	public function populateObjects( &$item )
	{
		// If state is called explicitly
		if ( $this->getState('dogitem.barking') )
		{
			// Do your thing...

		}

	}
Last Edit: 15 Apr 2013 13:55 by vlemos.
The administrator has disabled public write access.
Time to create page: 0.104 seconds

Get Started