MVC - technique to share form data for various models?

113 views
Skip to first unread message

AJH

unread,
Jul 28, 2012, 1:01:26 AM7/28/12
to joomla-de...@googlegroups.com
I'm in Joomla! 2.5, following the MVC pattern as described in the docs...

I'm looking for pointers on the best way for my models to 'inherit' fields from a generic table definition.

Simple example, having multiple tables with 'metadata', and that metadata is stored in a generic table.  Each table that wants to use this 'metadata' has a candidate key (unique identifier), and that key is the primary key for the meta data table.

My initial attempt at this is to override the getForm and loadFormData methods of any model that needs this metadata.  

Any suggestions would be most appreciated on how I can inject this metadata into various models, and not have to do any funny business in my views.

AJH

unread,
Jul 28, 2012, 2:20:54 AM7/28/12
to joomla-de...@googlegroups.com
I thought I would share my version of success with this issue.  I hope the experts can make sense of my quick post and share what I have done wrong or what could be improved.  Overall though, it seems like a fairly simple solution.  Ideally I would like to have a generic "metadata" xml form, and not have to copy/past the fields into each form that needs this metadata.

In the model that I want to include' the metadata:
  1. Add the fields that exist in the shared table to your XML form for the model in question
  2. Override the getForm method in for the model you wish to have the shared metadata something like:
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm('com_yourcomponent.product', 'product', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
// This section loads the metadata and injects it into the form we are returning
$metaDataTable = parent::getTable('MetaData', 'YourComponentTable', $config = array());
$metaDataTable->load($this->getItem()->guid);
$form->bind($metaDataTable);
return $form;
}
      3. Override the save method of your model in question like the following:

public function save($data)
{
$result = parent::save($data);
if($result)
{
// save the metadata
$metaDataTable = parent::getTable('MetaData', 'YourComponentTable', $config = array());
$result = $metaDataTable->save($data);
}
return $result;
}

Reply all
Reply to author
Forward
0 new messages