How to set Component parameters in J2.5?

不羁岁月 提交于 2019-12-30 10:41:46

问题


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;
}


来源:https://stackoverflow.com/questions/13219774/how-to-set-component-parameters-in-j2-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!