How to save component parameters to database programmatically

Almost every component in Joomla! ships with a set of parameters (or, params). Using “Options” button, we can easily alter the params values of a component. What if we want to change values of some parameters programmatically, i.e., using Joomla! codes.

 

Let’s do it step by step.

1. Load component params.

$comparams = JComponentHelper::getParams('com_news');

2. Set new value to one or more params.

$comparams->set('lastcreatedate', $data['created']);

We have just set a new value to a parameter named “lastcreateddate”. To test if it’s set proporly, use var_dump to view it.

var_dump($comparams);

You should see this output:

object(Joomla\Registry\Registry)#151 (1) { ["data":protected]=> object(stdClass)#10 (1) { ["lastcreatedate"]=> string(10) "2014-08-15" } }

3. Now it’s time to save the whole component params with our new values back to database. Now, we shall find our component’s ID from ‘#__extensions” table. The following piece of code will return the component ID of “com_news” component from ‘#__extensions” table:

$componentid = JComponentHelper::getComponent('com_news')->id;

4. To save our data, we shall take an instance of “#__extension” table using JTable class and load component data by component ID, ie., $componentid variable.

$table = JTable::getInstance('extension');
$table->load($componentid);

5. We shall bind “params” field with new values:

$table->bind(array('params' => $comparams->toString()));

6. Well, we have binded “params” field of “#__extensions” table with new values. Next, we shall push the data to the database after a regular check for error (if any).

// check for error
if (!$table->check()) {
    $this->setError('lastcreatedate: check: ' . $table->getError());
    return false;
}

7. Finally, save to database:

// Save to database
if (!$table->store()) {
    $this->setError('lastcreatedate: store: ' . $table->getError());
    return false;
}

If everything goes right, components new parameters should save to database successfully. Is it really? Let’s examine it loading the params and running the var_dump function again.

$comparams = JComponentHelper::getParams('com_news');
var_dump($comparams);

You should now see the new value in the output on screen.

I have applied this technique in my component development. It may not be the ‘best practice’, but it works. Hope this will work in your case too.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.