How to save component parameters to the database programmatically

WebTechRiser.com > Joomla 3.0 > How to save component parameters to the database programmatically

Almost every component in Joomla! ships with a set of parameters (or, params). Using the “Options” button, we can easily alter the params values of a component. What if we want to change the 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 a new value to one or more parameters.

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

We have just set a new value to a parameter named “lastcreateddate”. To test if it’s set properly, 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 the database. Now, we shall find our component’s ID from the “#__extensions” table. The following piece of code will return the component ID of the “com_news” component from the “#__extensions” table:

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

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

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

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

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

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

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

7. Finally, save to the database:

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

If everything goes right, the components’ new parameters should save to the database successfully. Is it really? Let’s examine it by 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 the screen.

Also read:  Disable scripts loading in the head section in Joomla!

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.

Category Joomla 3.0

Leave Your Comment

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