如何在J2.5中设置组件参数? [英] How to set Component parameters in J2.5?
问题描述
我已经使用组件的admin文件夹中的config.xml创建了具有一些配置字段的J2.5组件.
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?
推荐答案
最安全的方法是包含com_config/models/component.php
并将其用于验证和保存参数.但是,如果您可以自己验证数据参数,则可以使用以下方法(更简单的解决方案):
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();
请注意,我如何将参数转换为字符串(在构建查询时),它将把JRegistry对象转换为JSON格式的字符串.
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:
来自模型:
$this->cleanCache('_system');
或者,其他地方:
$conf = JFactory::getConfig();
$options = array(
'defaultgroup' => '_system',
'cachebase' => $conf->get('cache_path', JPATH_SITE . '/cache')
);
$cache = JCache::getInstance('callback', $options);
$cache->clean();
这篇关于如何在J2.5中设置组件参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!