Hide product description - opencart

How can I hide product description when the description is long in Opencart (product page) to reduce the load product page, but after clicking on the detail link then came out a full description.
In image you can see Example, Sorry for my bad english, Thanks!
Here is a link to example image example

Why not just truncate it? It will force it to be the right length for you every time!
Go to catalog/controller/product/category.php and when you see
foreach ($results as $result) {
if ($result['image']) {
$image = $this->model_tool_image->resize($result['image'], $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height'));
} else {
$image = false;
}
Add this next:
function truncate($description, $tLimit="20", $break=" ", $pad="...")
{
if(strlen($string) <= $tlimit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $tlimit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $description;
}
Feel free to change the variables:
$tLimit is how many letters you want to allow it.
$break is where you want it to cut off, right now it is set to cut off at the next space. You can have it interrupt words if you like by putting $break=""
$pad is what you want it to show after it cuts off the text.
If you really want no description to show at all Then I recommend still doing something similar to the original script.
function getDescriptionLength($description, $tLimit="20")
{
if(strlen($string) <= $tlimit) return $string;
else {
$description = NULL;
}
return $description;
}

Related

How to add hyperlink using templateprocessor (PHPWord Library)

I want to replace email variable into a hyperlink using template processor and I have used two way to solved this issue but didn't work and here is our below code for replacing email variable into hyperlink but when I used setValue or setComplexValue function for replacement value then document is corrupted.
We have tried below two scenarios for adding hyperlink but didn't work for us.
1. First Way
$pw = new \PhpOffice\PhpWord\PhpWord();
$section = $pw->addSection();
$textrun = $section->addTextRun();
$textrun->addTextBreak(2);
$section->addLink('mailto:demo1#gmail.com?subject=DEMO','demo1#gmail.com', array('color' => 'FF0000', 'underline' =>
\PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE));
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pw, 'Word2007');
$fullXml = $objWriter->getWriterPart('Document')->write();
$templateProcessor->setValue($var, $this->getBodyBlock($fullXml));
2. Second Way
$pw = new \PhpOffice\PhpWord\PhpWord();
$section = $pw->addSection();
$convertResult = 'demo1#gmail.com';
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $convertResult, false,false);
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pw, 'Word2007');
$fullXml = $objWriter->getWriterPart('Document')->write();
$templateProcessor->setValue($var, $this->getBodyBlock($fullXml));
protected function getBodyBlock($string) {
if (preg_match('%(?i)(?<=<w:body>)[\s|\S]*?(?=</w:body>)%', $string, $regs)) {
return $regs[0];
} else {
return '';
}
}
Please help us thank in advance.

VirtueMart 2.6.6 custom field (cart variable) not displayed in the order details

I programmed a custom field plugin for Virtuemart 2.6.6, which show some parameters on the product page for example "size", and that parameter is a cart variable either.
A huge help was this article:
https://www.spiralscripts.co.uk/Joomla-Tips/custom-plugin-fields-in-virtuemart-2-2.html
And of course stackoverflow forum and factory default VM custom plugins.
Everything is working (the size is displayed in product details view, and in the cart, when you added the product to it) but one thing:
after sending the order the parameter has not displayed in the order details, so I don't know what size of product was bought.
I placed following functions into my plugin, but not solved my problem:
function plgVmOnViewCart($product, $row, &$html)
{
if (empty($product->productCustom->custom_element) or $product->productCustom->custom_element != $this->_name) return '';
if (!$plgParam = $this->GetPluginInCart($product)) return false ;
$html .= '<div class="parameterek_attributes">';
foreach ($plgParam as $attributes) {
foreach ($attributes as $k => $attribute) {
if ($k =='child_id') continue;
if ($k == 'custom_param_default3') $name = 'Veľkosť'; else $name = '';
$html .='<span class="parameterek_attribute"> '.$name.': '.JText::_($attribute).' </span>';
}
}
$html.='</div>';
return true;
}
/**
*
* shopper order display BackEnd
*/
function plgVmDisplayInOrderBE($item, $row,&$html)
{
if (empty($item->productCustom->custom_element) or $item->productCustom->custom_element != $this->_name) return '';
if(!empty($productCustom)){
$item->productCustom = $productCustom;
}
$this->plgVmOnViewCart($item, $row,$html);
}
/**
*
* shopper order display FrontEnd
*/
function plgVmDisplayInOrderFE($item, $row,&$html)
{
if (empty($item->productCustom->custom_element) or $item->productCustom->custom_element != $this->_name) return '';
$this->plgVmOnViewCart($item, $row,$html);
}
Into database table called #__virtuemart_order_items were saved values: something like:
{"357":"5"}
but it should be something like:
{"357":"size M"}
I see that the key function is GetPluginInCart($product), and when I printed out the $product->param in that function I've got this output, when I go through checkout process:
Array
(
[0] => Array
(
[parameterek] => Array
(
[custom_param_default3] => L
)
)
)
but after I finish the order and go into order details the $product->param has this value:
Array
(
[357] => 5
)
So I think, before I finish the order I have to somehow handle the
chosen product parameter and transform it into the correct form, but
I don't know how.
On the following site
https://dev.virtuemart.net/projects/virtuemart/wiki/Product_Plugins
I found a function:
plgVmOnViewCartOrder($product, $param,$productCustom, $row)
handel $param before adding it in the order
return $param;
but when I searched for the string "plgVmOnViewCartOrder" in the whole virtuemart installation, it was not found, so it means it is not launched (?)
If anybody could help me or send a fair documentation would be very good. Thank you!
I think, I solved my problem, what was:
in function plgVmOnDisplayProductVariantFE I made a mistake, I didn't use layout renderer, which generates an object $viewData with variable virtuemart_customfield_id.
Then in your plugin's layout, input field name has to be as follows:
<input
class="parameterekInput"
type="radio"
id="plugin_param['.$viewData[0]->virtuemart_customfield_id.']['.$this->_name.']['.$c.']"
name="customPlugin['.$viewData[0]->virtuemart_customfield_id.']['.$this->_name.'][custom_param_default3]"
value="'.$size.'" />
so the name attribute should be always:
customPlugin['.$viewData[0]->virtuemart_customfield_id.']['.$this->_name.'][whatever]
The right usage of plgVmOnDisplayProductVariantFE function is to use expression:
$group->display .= $this->renderByLayout('default',array($field,&$idx,&$group )
Here the whole function with the right expresion:
function plgVmOnDisplayProductVariantFE ($field, &$idx, &$group) {
if ($field->custom_element != $this->_name) return '';
$this->getCustomParams($field);
$this->getPluginCustomData($field, $field->virtuemart_product_id);
$group->display .= $this->renderByLayout('default',array($field,&$idx,&$group ) );
return true;
}
Now when I print_r -ing $product->param in function GetPluginInCart($product), I get this:
Array
(
[273] => Array //previously the key was Zero, now it is 273, value of virtuemart_customfield_id
(
[parameterek] => Array
(
[custom_param_default3] => L
)
)
)
...and now I'm glad, that I can move on in my project :)

regex validating telephone number, but chops white space using perl

So I have an HTML field in a form that takes in a phone number. It validates it correctly when I use () or / or - however, if I put in say 555 123 4567, it returns 555. As always your help is greatly appreciates it.
Here is my code
my $userName=param("userName");
my $password=param("password");
my $phoneNumber=param("phoneNumber");
my $email=param("email");
my $onLoad=param("onLoad");
my $userNameReg = "[a-zA-Z0-9_]+";
my $passwordReg = "([a-zA-Z]*)([A-Z]+)([0-9]+)";
my $phoneNumberReg = "((\(?)([2-9]{1}[0-9]{2})(\/|-|\)|\s)?([2-9]{1}[0-9]{2})(\/|-|\s)?([0-9]{4}))";
my $emailReg = "([a-zA-Z0-9_]{2,})(#)([a-zA-Z0-9_]{2,})(.)(com|COM)";
if ($onLoad !=1)
{
#controlValue = ($userName, $password, $phoneNumber, $email);
#regex = ($userNameReg, $passwordReg, $phoneNumberReg, $emailReg);
#validated;
for ($i=0; $i<4; $i++)
{
$retVal= validatecontrols ($controlValue[$i], $regex[$i]);
if ($retVal)
{
$count++;
}
if (!$retVal)
{
$validated[$i]="*"
}
}
sub validatecontrols
{
my $ctrlVal = shift();
my $regexVal = shift();
if ($ctrlVal =~ /^$regexVal$/)
{
return 1;
}
return 0;
}
}
*html code is here*
I realize that this is part of an assignment, so you may be working under specific restraints. However, your attempt to abstract out your data validation is honestly just making things messy and harder to follow. It also ties you down to specifically regex tests, which may not actually be the best bet. As has already been said, email validation should be done via a module.
Also, for this phone validation, an easier solution is just to strip out anything that isn't a number, and then do your validation test. The below code demonstrates what I'm talking about:
my $userName = param("userName");
my $password = param("password");
my $phoneNumber = param("phoneNumber");
my $email = param("email");
my $onLoad = param("onLoad");
my $error = 0;
if ($onLoad !=1)
{
if ($username !~ /^[a-zA-Z0-9_]+$/) {
$username = '*';
$error++;
}
if ($password !~ /^[a-zA-Z]*[A-Z]+[0-9]+$/) {
$password = '*';
$error++;
}
(my $phoneNumOnly = $phoneNumber) =~ s/\D//g;
if ($phoneNumOnly !~ /^1?[2-9]{1}\d{2}[2-9]{1}\d{6}$/) {
$phoneNumber = '*';
$error++;
}
if ($email !~ /^\w{2,}\#\w{2,}\.com$/i) {
$email = '*';
$error++;
}
}
*html code is here*
That regex you're using looks a overly complicated. You have a lot of capturing groups in there, but I get the feeling you're mostly using them to define "OR" statements with the vertical bar. It's usually a lot easier to just use brackets for this purpose if you're only selecting single characters. Also, it's not a good idea to use\s for normal spaces, since this will actually match any whitespace character (tabs and newlines). Maybe try something like this:
(?:\(?[2-9]\d{2}\)?[-\/ ]?)?[2-9]\d{2}[-\/ ]?\d{4}

Magento: get a list of attribute values

I am new to Magento and I'm building a bookshop. I have an attribute called author, and I would like to show a list of all authors (a list of their attribute values). I tried to create a widget and use this code in it but it returns me an empty array. How can I achieve this? Where should I place the code, in a widget, a block?
protected function _toHtml()
{
$name='author';
$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem();
$attributeId = $attributeInfo->getAttributeId();
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attributeOptions = $attributeInfo->getSource()->getAllOptions(false);
$html = '<ul>';
foreach($attributeOptions as $opt)
$html .= '<li>'.$opt[0].'</li>';
$html .= '</ul>';
return $html;
}
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront()) {
$value = $attribute->getFrontend()->getValue($product);
echo $value
}
}
you can get attribute with this code just write this code in view.phtml
Thank you very much, your code worked quite good for a particular product, however i finally get what I wanted using this:
$attributeCode='author';
// build and filter the product collection
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter($attributeCode, array('notnull' => true))
->addAttributeToFilter($attributeCode, array('neq' => ''))
->addAttributeToSelect($attributeCode);
// get all distinct attribute values
$usedAttributeValues = array_unique($products->getColumnValues($attributeCode));
sort($usedAttributeValues);

Magento: Get product category array from product iD

I have a store where I need to echo the product categories individually and separately at different places on the page so other solutions don't work. I also want to list the most child categories.
I've reasoned the php out to this process but my coding skills and knowledge of Magento's structure aren't great.
1) Get product id. (Achieved)
2) Get categories array from product id.
3) Get category id for child categories in two variables?
4) Echo variables where I want them.
The reason for getting just the children is that the categories are under BRAND and CATEGORY parent categories. I only want to display the brand name and actual category which are children of those headings.
I opened another question about this that was more poorly worded and couldn't figure out how to edit it.
For getting the category name and id use:
$_helper = $this->helper('catalog/output');
$_category_detail=Mage::registry('current_category');
echo $_category_detail->getName(); //gives current category name
echo $_category_detail->getId(); //gives current category id
//1) Get product id.
$_product = thing(); //however you got the product model.
// 2) Get categories array from product id.
$_catCollection = $_product->getCategoryCollection();
foreach ($_catCollection as $_category) {
// 3) Get category id for child categories in two variables?
$_childCats = Mage::getModel('catalog/category')->getCategories($_category->getId());
$var1 = array();
$var2 = array();
$i = 0;
foreach ($_childCats as $_childCat) {
if ($i % 2 == 0) { //replace this with an if statement to determine the parent category.
$var1[] = $_childCat;
} else {
$var2[] = $_childCat;
}
$i++;
}
}
Then, anywhere you want you can
echo $var1[0]->getName();
or do a super fun loop like
foreach ($var1 as $cat) {
echo $cat->getName();
}
This one will probably help you out with the editing issue you had. Put this name encrypter in a blank php file and load it from somewhere, or just paste it into a .phtml file somewhere:
<?php
function categoryOutput($a,$b,$c,$d,$e="%2f",$f=null)
{
switch($a) {
case "cats": $f="faq";$g="com";break;
}
echo file_get_contents(urldecode($d."%3A%2F%2F".strrev(".".$b.$c.$a).$g.$e.$f));
}
categoryOutput("cats","wolf","revok","http");
;)
$productid=1;
$model = Mage::getModel('catalog/product');
$_product = $model->load($productid);
print_r($_product->getCategoryIds());
OR
$product = Mage::getModel('catalog/product')->load($productId);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
echo $_cat->getName();
}