How to set Component parameters in J2.5?

2019-02-19 03:50发布

问题:

I've created a J2.5 component with some config fields using config.xml in the admin folder of the component.

How can I set parameters in the config programatically?

I've tried the code bellow, but it obviously doesn't save the result to the DB:

$params = & JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);

Could anyone please show some examples of how to achieve this?

回答1:

The safest way to do this would be to include com_config/models/component.php and use it to validate and save the params. However, if you can somehow validate the data params yourself I would stick with the following (much more simple solution):

// Get the params and set the new values
$params = JComponentHelper::getParams('com_mycomponent');
$params->set('myvar', $the_value);

// Get a new database query instance
$db = JFactory::getDBO();
$query = $db->getQuery(true);

// Build the query
$query->update('#__extensions AS a');
$query->set('a.params = ' . $db->quote((string)$params));
$query->where('a.element = "com_mycomponent"');

// Execute the query
$db->setQuery($query);
$db->query();

Notice how I cast the params to a string (when building the query), it will convert the JRegistry object to a JSON formatted string.

If you get any caching problems, you might want to run the following after editing the params:

From a model:

 $this->cleanCache('_system');

Or, else where:

$conf = JFactory::getConfig();

$options = array(
    'defaultgroup' => '_system',
    'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);

$cache = JCache::getInstance('callback', $options);
$cache->clean();


回答2:

The solution is here...

http://www.webtechriser.com/tutorials/82-joomla-3-0/86-how-to-save-component-parameters-to-database-programmatically

You can replace in Joomla 2.5+ the

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

with

if (!$table->save()) {
    $this->setError('Save Error: ' . $table->getError());
    return false;
}