I working on some module and want to have ability to update table with image sizes - there already two columns in table (width, height). Its my first approach to joomla module develop. All code works except last foreach with update. Where I'm wrong?
And how to trigger this function in module or in backend module settings to button or link? Code in helper.php:
public static function updateSize( $params )
{
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
JHtml::_('behavior.framework', true);
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(array('a.imgfilename', 'b.catpath')))
->from($db->quoteName('#__imagestable', 'a'))
->where(($db->quoteName('height').'=') && ($db->quoteName('width').'='))
->join('INNER', $db->quoteName('#__imagestable_cat', 'b') . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('b.cid') . ')')
->order('RAND() LIMIT 5');
$db->setQuery($query);
$size = $db->loadObjectList();
return $size;
foreach($size as $imageSize){
$imgpath = $path.$imageSize->catpath.'/'.$imageSize->imgfilename;
$imgfilename = $imageSize->imgfilename;
list($width, $height) = getimagesize($imgpath);
$validImgs[] = $imageSize;
foreach ( $validImgs as $row ) {
$query = $db->getQuery(true)
->update($db->quoteName('#__imagestable'))
->where ($db->quoteName('imgfilename').'='.$imgfilename)
->set(array($db->quoteName('height') . '=' . $height, $db->quoteName('width') . '=' .$width));
$db->setQuery($query);
$imgSize = $db->execute();
}
}
}
Is it possible to attach this function to backend XML - maybe to button "Update image sizes"?
You are using return $size; before the foreach.
Related
How do I get the value of a specific attribute? I use the code:
$attributes = $this->model_catalog_product->getProductAttributes($product['product_id']);
if (!empty($attributes)) {
foreach ($attributes as $attr) {
if($attr['attribute_id'] == 15) {
$attr_text = $attr['text'] ;
$attr = $this->dd->createElement('param');
$attr->setAttribute('code', 'color');
$attr->setAttribute('name', 'Color');
$attr->appendChild($this->dd->createTextNode($attr_text));
$e->appendChild($attr);
}
}
}
But it does not work. How to get the value of a variable in OpenCart 2.3
$attr['text']
First off all, new get grouped attributes from getProductAttributes(), you need to create new function in model for attribute information by ID.
public function getProductAttributeById($product_id, $attribute_id) {
$product_attribute_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "' AND attribute_id = '" . (int)$attribute_id . "'");
return $query->row;
}
Code not tested!!!
And then you use it like this:
$attributes_by_id = $this->model_catalog_product->getProductAttributeById($product['product_id'], 15);
if (!empty($attributes_by_id )) {
$attr_text = $attributes_by_id ['text'] ;
$attr = $this->dd->createElement('param');
$attr->setAttribute('code', 'color');
$attr->setAttribute('name', 'Color');
$attr->appendChild($this->dd->createTextNode($attr_text));
$e->appendChild($attr);
} else {
// default code
}
I have function and my function works good only I do not understand this:
<?php
// $category output is 23 when I echo $category; and there is no records
->where('d.category_id = ' . (int) $category)
// also this method not work
->where('d.category_id = ' . $category)
// but this method works
->where('d.category_id = 23')
?>
this is full code:
$category = $params->get('title');
//echo $category;
public static function getSuggested($category) {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = 23')
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}
this function works good only need to get category data.
this is joomla module, and this function is in helper.php file in default.php file I am get some data from this function.
I found solution:
Add in mod_suggested_deals.php
$category = (int) $params->get('fieldvalue');
then:
$results = modsuggested_dealsHelper::getSuggested($category);
I found soluton for this question:
in my function I Add param $category
public static function getSuggested($category) {...}
in mod_suggested_deals.php I add code:
$category = $params->get('title');
then is code (it already was here).
$results = modsuggested_dealsHelper::getSuggested($category);
The mistake you are doing is you are defining a variable value outside a function but calling the variable inside it. If your class is not abstract class you can use $this->category or if your class is an abstract class then use the $category variable inside of the function like this
public static function getSuggested() {
$module = JModuleHelper::getModule('mod_yourmodulename');
$catid = new JRegistry($module->params);
$category = (int) $catid['title'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = '.$category)
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}
How can I cache (using ModX's cacheManager), the dynamic placeholders i am generating here:
// recursive function to generate our un-ordered list of menu items
if(!function_exists('GenerateMenu')){
function GenerateMenu($level, $parent = 0, $wc, $wi, $we, $cs, $sc, $cl){
try {
$lvl = ++$level;
global $modx;
// Check for #1, should this be cached, #2 does it already exist in the cache
$cached = $modx->cacheManager->get('Navigator');
if($sc && isset($cached)){
// need to get the placeholders from cache - here somehow!
return $cached;
}else{
// get the site start
$siteStartId = $modx->getOption('site_start');
// Set our initial rows array
$rows = array();
// Run our query to get our menu items
$sql = 'Select `id`, `menutitle`, `uri`, `longtitle`, `parent`, `link_attributes`, `class_key`, `content`, `alias`, `introtext`
From `' . $modx->getOption(xPDO::OPT_TABLE_PREFIX) . 'site_content`
Where `deleted` = 0 AND `hidemenu` = 0 AND `published` = 1 AND `parent` = :parent
Order by `parent`, `menuindex`';
$query = new xPDOCriteria($modx, $sql, array(':parent' => $parent));
if ($query->stmt && $query->stmt->execute()) {
$rows = $query->stmt->fetchAll(PDO::FETCH_ASSOC);
}
// do some cleanup
unset($query, $sql);
// make sure we have some rows, and then build our html for the menu
if($rows){
// grab a count of our results
$rCt = count($rows);
$cls = ($lvl > 1) ? 'sub-item-' . $lvl : 'main-item-' . $lvl;
$ret .= ' <ul class="' . $cls . '" id="' . $cls . '-' . $parent . '">' . "\r\n";
for($i = 0; $i < $rCt; ++$i){
// if this resource is a WebLink, show the content in it, as the URL for the href tag, otherwise, use the resource's URI
$url = ($rows[$i]['class_key'] == 'modWebLink') ? $rows[$i]['content'] : '/' . $rows[$i]['uri'];
// Check for the site's start id, if true, show a "blank" link, otherwise show the $url
$showUrl = ($siteStartId == $rows[$i]['id']) ? '/' : $url;
$la = (strlen($rows[$i]['link_attributes']) > 0) ? ' ' . $rows[$i]['link_attributes'] : null;
// Set some dynamic placeholders, they can only be used ont he pages that contain this snippet
$modx->toPlaceholders(array('Title-' . $rows[$i]['id'] => $rows[$i]['longtitle'],
'MenuTitle-' . $rows[$i]['id'] => $rows[$i]['menutitle'],
'URL-' . $rows[$i]['id'] => $showUrl),
'link');
$ret .= ' <li class="' . $cls . '" id="' . $rows[$i]['alias'] . '">' . "\r\n";
$ret .= ' <a href="' . $showUrl . '" title="' . $rows[$i]['longtitle'] . '"' . $la . '>' . $rows[$i]['menutitle'] . '</a>' . "\r\n";
$ret .= GenerateMenu($lvl, $rows[$i]['id']);
// Check for a snippet, and render it
$it = $rows[$i]['introtext'];
if($cs && IsSnippet($it)){
// if we find a snippet in the Summary field, run it, and attach it to our output
preg_match('/\[\[!?(.*)\]\]/', $it, $sm);
$ret .= $modx->runSnippet($sm[1]);
// clean up
unset($sm);
}
$ret .= ' </li>' . "\r\n";
}
$ret .= ' </ul>' . "\r\n";
}
// clean up
unset($rows);
// Check to see if we should cache it, if so, set it to cache, and apply the length of time it should be cached for: defaults to 2 hours
if($sc){
// NEED TO SET THE PLACEHOLDERS TO CACHE SOMEHOW
$modx->cacheManager->set('Navigator', $ret, $cl);
}
// return the menu
return $ret;
}
} catch(Exception $e) {
// If there was an error, make sure to write it out to the modX Error Log
$modx->log(modX::LOG_LEVEL_ERROR, '[Navigator] Error: ' . $e->getMessage());
return null;
}
}
}
The easiest solution may be pdoTools which allows you to establish caching at run time.
http://www.shawnwilkerson.com/modx/tags/pdotools/
Also, I do not believe resource placeholders are cached which is the best place to have your items cahced:
case '+':
$tagName= substr($tagName, 1 + $tokenOffset);
$element= new modPlaceholderTag($this->modx);
$element->set('name', $tagName);
$element->setTag($outerTag);
$elementOutput= $element->process($tagPropString);
break;
From lines 455-461 of https://github.com/modxcms/revolution/blob/master/core/model/modx/modparser.class.php#L455
You may notice the other tag types have:
$element->setCacheable($cacheable);
I cover the parser in Appendix D of my book. I found some issues in it in 2011 which Jason corrected.
Move toPlaceholders() to the end of your script and instead cache the array of placeholder data:
// attempt to retrieve placeholders from cache
$placeholders = $modx->cacheManager->get('Navigator');
// if not in cache, run your snippet logic and generate the data
if (empty($placeholders))) {
$placeholders = array(
'myplaceholder' => 'placeholder data'
);
$modx->cacheManager->set('Navigator', $placeholders, $cl);
}
// set placeholders for use by MODX
$modx->toPlaceholders($placeholders);
In my site, I allow my users to upload an avatar. The following code is used to print the URL:
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
This will give us for example /wp-content/uploads/userphoto/2.thumbnail.png.
The problem is that if the user has not uploaded an avatar, the URL will of course be /wp-content/uploads/userphoto/. So it will be a broken image.
I want to display a custom image for users with no avatar, for example no-image.png. I'm guessing that this is done by adding an if (isset) statement there? I can't seem to figure out how to solve this.
You could use empty:
$image_id = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . (empty($image_id) ? 'no-image.png' : $image_id);
Something like this should work, depending on if get_user_meta actually returns Null.
if (is_null(get_user_meta($user_info->ID, 'userphoto_thumb_file', true))) {
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/customimage.png';
} else {
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}
You can do
if(!empty(get_user_meta($user_info->ID, 'userphoto_thumb_file', true)))
{
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
}
else
{
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/no-image.png';
}
You should test if the file exists :
if(!file_exists( $_SERVER['DOCUMENT_ROOT'] . $r)) {
$r = '/path/to/default/image.jpg';
}
With this approach, even if the user has uploaded an avatar, but for some reason the image is not present on the server, it will display the default avatar.
You can actually just check if the function returns something that evaluates to false. An empty string evaluates to false in php.
$img = get_user_meta($user_info->ID, 'userphoto_thumb_file', true);
if(!$img) {
$img = 'no-image.png';
}
$r = $r . $photoUrl = '/wp-content/uploads/userphoto/' . $img;
Hopefully someone can help me with this. I am using smarty within CMSMS and have something called a User Defined Tag running within my page. This contains the following code:
$db = cmsms()->GetDb();
$menu = $smarty->get_template_vars('page');
$user_id = $smarty->get_template_vars('userid');
if (!isset($user_id)) {
$user_id = -1;
}
// Getting menu items from DB
$query = 'SELECT * FROM '. cms_db_prefix() .'module_tools_options
WHERE active = 1 AND user_id = ? AND menu = ?
ORDER BY sort';
$dbresult = $db->Execute($query, array($user_id, $menu));
while ($dbresult && $row = $dbresult->FetchRow()) {
$smarty->_compile_source('preprocess template', $row['title'], $_compiled);
#ob_start();
$smarty->_eval('?>' . $_compiled);
$result = #ob_get_contents();
#ob_end_clean();
echo '<li id="menu_' . $row['option_id'] . '">' . $result . "</li>\n";
}
I have upgraded the CMSMS installation so it now runs smarty 3 and this has broken my page. I get the following error:
/lib/smarty/sysplugins/smarty_internal_templatebase.php: Call of unknown method '_compile_source'.
I guess the Compile Source method has been depreciated in Smarty 3. Can anyone point me in the right direction of its replacement or a method to get this working again?
Many Thanks
Replace:
$smarty->_compile_source('preprocess template', $row['title'], $_compiled);
#ob_start();
$smarty->_eval('?>' . $_compiled);
$result = #ob_get_contents();
#ob_end_clean();
With:
$result = $smarty->fetch('string:'.$row['title']);