Magento get attribule value on pdf invoice - magento

I try to get a product attribute value on my invoice, but everything i tried found on stack doesn't give a result (getdata, getattribute, getressouce...)
Below is an extract of the file, i would like to replace the last line "getname" by getattribute
Thanks a lot
$order = $this->getOrder();
$item = $this->getItem();
$pdf = $this->getPdf();
$page = $this->getPage();
//$lines = array();
//if not only checking the height - let's check and set up page and background if needed
if (!$returnHeight)
{
$blockHeight = $this->draw(true);
if ($pdf->y - $blockHeight < 12)
{
$page = $pdf->newPage(array('table_header' => true));
$this->setPage($page);
}
if ($pdf->currentItemWithBg)
{
$page -> setFillColor(new Zend_Pdf_Color_Html('#' . $pdf -> params['lightBg']));
$page -> drawRectangle(18, $pdf -> y, $page->getWidth() - 18, $pdf -> y - $blockHeight, $fillType = Zend_Pdf_Page::SHAPE_DRAW_FILL);
}
}
//get price and subtotal values
$prices = $this->getItemPricesForDisplay();
$topOffset = 10;
//if there are labels leave more space at the top
if (count($prices) > 0 && !empty($prices[0]['label']))
$topOffset = 16;
//slice product name into chunks
$font = $pdf->_setFontLight($page, 9);
$nameParts = $commonHelper->sliceStringByPoints($item->getName(), 191, $font, 9);

Related

Save multidimensional array using Laravel and ajax

I am building a pharmacy management system. I have a condition where I need to build a section
As shown in the picture, I need to store the data where the upper three should be same for all of the rows inputted below.
The form data is submitted as in the below picture.
But the data when looped and saved is not being saved as desired. Only the last row of the data is being inserted and I am also confused to store supplier, purchase date and note since these data should be repeated as many as the number of rows are added.
PurchaseController.php
public function storePurchase(PurchaseStoreRequest $request)
{
$purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}
Can someone help me to store these three fields in the database repeating the number of rows submitted ?
Currently only the last row is being inserted into the database.
This might be an another way to accomplish what you're looking for.
$sharedKeys = ['supplier', 'purchase_date', 'description'];
$sharedData = $request->only($sharedKeys);
$multiKeys = ['category', 'name', 'generic_name', 'batch_number', 'company', 'strength', 'expiry_date', 'quantity', 'selling_price', 'purchase_price'];
$multiData = $request->only($multiKeys);
for ($i = 0; $i < count($request->name); $i++) {
$individualData = array_combine($multiKeys, array_column($multiData, $i));
Purchase::create($sharedData + $individualData);
}
For every loop, you need to create a new instance, then It will create a new record on each loop :
public function storePurchase(PurchaseStoreRequest $request)
{
// $purchase = new Purchase();
$count = count($request->name);
// return response()->json($request->all());
for ($i = 0; $i < $count; $i++) {
$purchase = new Purchase(); // create new instance end with (); on each loop
$purchase->supplier = $request->supplier;
$purchase->purchase_date = $request->purchase_date;
$purchase->description = $request->description;
$purchase->category = $request->category[$i];
$purchase->name = $request->name[$i];
$purchase->generic_name = $request->generic_name[$i];
$purchase->batch_number = $request->batch_number[$i];
$purchase->company = $request->company[$i];
$purchase->strength = $request->strength[$i];
$purchase->expiry_date = $request->expiry_date[$i];
$purchase->quantity = $request->quantity[$i];
$purchase->selling_price = $request->selling_price[$i];
$purchase->purchase_price = $request->purchase_price[$i];
$purchase->save();
}
return response()->json(['message' => 'Purchase Saved Successfully']);
}

How to create a product in Prestashop 1.7

I create my first module in Prestashop 1.7.4. This is my code:
public function createProductsObject()
{
$product = new Product;
$product->name = $productName;
$product->ean13 = '';
$product->reference = '';
$product->id_category_default = $getCategoryID;
$product->category = $getCategoryID;
$product->indexed = 1;
$product->description = $description;
$product->condition = 'new';
$product->redirect_type = '404';
$product->visibility = 'both';
$product->id_supplier = 1;
$product->link_rewrite = $link_rewrite;
$product->quantity = $singleStock;
$product->price = $price;
$product->active = 1;
$product->psoft_hurtobergamo_id = $productID;
$product->add();
$product->addToCategories($getCategoryID);
This function in not complite. But this is not important right now. Variable productName hase this value:
Array ( [0] => Test [1] => Test) )
Beacause I have two language. The problem is. Why I dont have the name after the product is create ?
thanks for help.
To resolve this problem I add new index to my array.
$productName = array('0' => '');
$link_rewrite = array('0' => '');
and then add values to array start from index 1. Because the first language has identity value set to 1. The second, 2.
for ($i = 1; $i <= $getNumberOfAvailableLanguage; $i++)
{
array_push($productName, $name);
array_push($link_rewrite, $clean1);
}

Magento Cart Get Custom Option (Text Field) Value in Model/Quote/Item.php

My products have variable sizes which affect weight and I need to put weight logic in the cart to more accurately calculate shipping costs. I've moved a copy of app/code/core/Mage/Sales/Model/Quote/Item.php to the local code pool. I've been able to grab the associated product's base weight, however, I am not able to get the custom option (text field) value to do the math calculation before updating the cart. I'm doing this in the public function, setProduct. Here's what I have so far:
public function setProduct($product)
{
if ($this->getQuote()) {
$product->setStoreId($this->getQuote()->getStoreId());
$product->setCustomerGroupId($this->getQuote()->getCustomerGroupId());
}
//Get the Weight per UOM
$sku = $product->getSku();
$item = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$wpuom = $item->getResource()->getAttribute('weight_per_uom')->getFrontend()->getValue($item);
//Get the Length
$params = Mage::app()->getRequest()->getParams();
/** #var Mage_Catalog_Model_Product $product */
$info = new Varien_Object($params);
// Don't throw an exception if required options are missing
$processMode = Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_LITE;
$options = array();
foreach ($product->getOptions() as $option) {
/* #var $option Mage_Catalog_Model_Product_Option */
$group = $option->groupFactory($option->getType())
->setOption($option)
->setProduct($product)
->setRequest($info)
->setProcessMode($processMode)
->validateUserValue($info->getOptions());
$optionValue = $info->getData('options/' . $option->getId());
$options[] = array(
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($optionValue),
'value2' => $option->getValues(),
'option_id' => $option->getId(),
'option_type' => $option->getType()
);
//<<<This is Where I Cannot Get the Value for the Custom Option>>>
if($options[0]['label'] == 'Length') {
//print_r($options[0]['value']);
}
}
//Update Weight
$baseWeight = $item->getWeight();
$uom = $item->getResource()->getAttribute('uom')->getFrontend()->getValue($item);
if((($uom == 'Meters') && ($length >= 76)) || (($uom == 'Feet') && ($length >= 250))) { $spoolWeight = 3; }
else { $spoolWeight = 0; }
$finalWeight = ($baseWeight + ($length * $wpuom) + $spoolWeight);
$this->setData('product', $product)
->setProductId($product->getId())
->setProductType($product->getTypeId())
->setSku($this->getProduct()->getSku())
->setName($product->getName())
->setWeight($this->getProduct()->getWeight())
->setTaxClassId($product->getTaxClassId())
->setBaseCost($product->getCost())
->setIsRecurring($product->getIsRecurring());
if ($product->getStockItem()) {
$this->setIsQtyDecimal($product->getStockItem()->getIsQtyDecimal());
}
Mage::dispatchEvent('sales_quote_item_set_product', array(
'product' => $product,
'quote_item' => $this
));
return $this;
}
When I try adding print_r($options[0]);, I get everything except value, it's not even an array. What am I missing in order to get the value?
You're likely going to run into issues with the wishlist and other functionality if you display the product price in various spots on your site such as category pages, wishlist and other areas on the site.
That being said, I made some modifications to your code and updated it below. I took a slightly different approach to get the end result. First, get all the cart items for the current session. If the product type is configurable, do some logic, if not, do other logic. Inside the logic, I am gathering the items, associated attribute values, custom options, and custom option values. I also added some functionality to add the length and the unit of measure to the sku. Then I went ahead and showed examples of how you can use direct mySQL queries to update the database with your new pricing, skus, weight, and other details.
public function setProduct($product)
{
if ($this->getQuote()) {
$product->setStoreId($this->getQuote()->getStoreId());
$product->setCustomerGroupId($this->getQuote()->getCustomerGroupId());
}
$quote = Mage::getSingleton('checkout/session')->getQuote();
foreach ($quote->getAllVisibleItems() as $itm){
$sku = $product->getSku();
$item = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$assocProd = Mage::getModel('catalog/product')->loadByAttribute('sku',$itm->getSku());
if($product->getTypeId() == 'configurable') { //configurable product
foreach ($product->getOptions() as $o) {
if($o->getTitle() == "YOUR CUSTOM OPTION LABEL" && $o->getType() == "field"){
$optionId = $o->getOptionId();
$opz = $itm->getOptionByCode('info_buyRequest');
$buyRequest = new Varien_Object($opz ? unserialize($opz->getValue()) : null);
foreach($buyRequest['options'] as $key => $value){
if($key == $optionId) {
$length = $value;
//here is your length... do with it what you please
}
//example of how to update the database
$itemId = $itm->getId();
$query = 'UPDATE `sales_flat_quote_item` SET `weight` = "'.$finalWeight.'", `display_sku` = "'.$displaySku.'" WHERE `item_id` = "'.$itemId.'"';
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$writeConnection->query($query);
}
}
}
}
}
else { //simple product
if($product->getOptions()) { //has options
foreach ($product->getOptions() as $o) {
if($o->getTitle() == "YOUR OPTION LABEL" && $o->getType() == "field"){
$optionId = $o->getOptionId();
$opz = $itm->getOptionByCode('info_buyRequest');
$buyRequest = new Varien_Object($opz ? unserialize($opz->getValue()) : null);
foreach($buyRequest['options'] as $key => $value){
$finalWeight = '';
if($key == $optionId) {
$length = $value;
//here's your length value for simple products
}
//to update the database
$itemId = $itm->getId();
$query = 'UPDATE `sales_flat_quote_item` SET `weight` = "'.$finalWeight.'", `display_sku` = "'.$displaySku.'" WHERE `item_id` = "'.$itemId.'"';
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$writeConnection->query($query);
}
}
}
}
}
else { //doesn't have options
//this would be your logic for a simple product with no options
}
}
I hope this helps and feel free to let me know if you have any questions!

Codeigniter Pagination Links Error After ID

sorry if my question is duplicate, i have a problem with my codeigniter pagination. My url is: http://mysite/news/category/26/(page number), i have only 5 data and the page limit is 10, but the generated links active on page 3, i believe that is because of id/26/
This is my model :
function categpry($id){
$string_query = "SELECT * FROM news n JOIN category c ON n.category_id = c.id_category AND n.category_id = $id ORDER BY n.category_id DESC";
$query = $this->db->query($string_query);
$config['base_url'] = site_url('news/category/' . $id);
$config['total_rows'] = $query->num_rows();
$config['per_page'] = '10';
$num = $config['per_page'];
$offset = $this->uri->segment(4);
$offset = ( ! is_numeric($offset) || $offset < 1) ? 0 : $offset;
if(empty($offset)){
$offset = 0;
}
$this->pagination->initialize($config);
$news = $this->db->query($string_query." limit $offset,$num");
return $nes;
}
the generated links is 1 - 2 - 3, its should be no link because i only have 5 data
please help me on this, thank you
finally I fixed it with change the script with this :
function category($id){
$string_query = "SELECT * FROM news n JOIN category c ON n.category_id = c.id_category AND n.category_id = $id ORDER BY n.category_id DESC";
$query = $this->db->query($string_query);
$config['base_url'] = site_url('news/category/' . $id);
$config['total_rows'] = $query->num_rows();
$limit = $config["per_page"] = 10;
$config["uri_segment"] = 4;
$config["use_page_numbers"] = TRUE;
$this->pagination->initialize($config);
if($this->uri->segment(4))
$page = ($this->uri->segment(4)-1)*$limit;
else
$page = 1;
$news= $this->db->query($string_query." limit $page,$limit");
return $news;
}
Thank you

Add "latest items by category" block in item view page of K2 component

I am using Joomla! K2 v2.4.1 component on Joomla! v1.5.23. I want to display latest items by category in the item view page, the category being the current one which the current viewed item belongs to.
There are modules which I can use to display most recent items by category but I want to modify item.php and other related files (actually I don't know which files to edit except the item.php template file) to accommodate this requirement. Is it possible to achieve this? If yes, which files do I need to edit and with what code?
Given below is what I think is used to retrieve latest items by category.
class K2ViewLatest extends JView {
function display($tpl = null) {
$mainframe = &JFactory::getApplication();
$params = &JComponentHelper::getParams('com_k2');
$user = &JFactory::getUser();
$cache = &JFactory::getCache('com_k2_extended');
$limit = $params->get('latestItemsLimit',3);
$limitstart = JRequest::getInt('limitstart');
$model = &$this->getModel('itemlist');
$itemModel = &$this->getModel('item');
if($params->get('source')){
$categoryIDs = $params->get('categoryIDs');
if(is_string($categoryIDs) && !empty($categoryIDs)){
$categoryIDs = array();
$categoryIDs[]=$params->get('categoryIDs');
}
$categories = array();
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
if(is_array($categoryIDs)){
foreach($categoryIDs as $categoryID){
$category = & JTable::getInstance('K2Category', 'Table');
$category->load($categoryID);
if ($category->published && ($category->access <= $user->get('aid', 0))) {
//Merge params
$cparams = new JParameter($category->params);
if ($cparams->get('inheritFrom')) {
$masterCategory = &JTable::getInstance('K2Category', 'Table');
$masterCategory->load($cparams->get('inheritFrom'));
$cparams = new JParameter($masterCategory->params);
}
$params->merge($cparams);
//Category image
if (! empty($category->image)) {
$category->image = JURI::root().'media/k2/categories/'.$category->image;
} else {
if ($params->get('catImageDefault')) {
$category->image = JURI::root().'components/com_k2/images/placeholder/category.png';
}
}
//Category plugins
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('content');
$category->text = $category->description;
$dispatcher->trigger('onPrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category K2 plugins
$category->event->K2CategoryDisplay = '';
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2CategoryDisplay', array(&$category, &$params, $limitstart));
$category->event->K2CategoryDisplay = trim(implode("\n", $results));
$category->text = $category->description;
$dispatcher->trigger('onK2PrepareContent', array ( & $category, &$params, $limitstart));
$category->description = $category->text;
//Category link
$link = urldecode(K2HelperRoute::getCategoryRoute($category->id.':'.urlencode($category->alias)));
$category->link = JRoute::_($link);
$category->feed = JRoute::_($link.'&format=feed');
JRequest::setVar('view', 'itemlist');
JRequest::setVar('task', 'category');
JRequest::setVar('id', $category->id);
JRequest::setVar('featured', 1);
JRequest::setVar('limit', $limit);
JRequest::setVar('clearFlag', true);
$category->name = htmlspecialchars($category->name, ENT_QUOTES);
$category->items = $model->getData('rdate');
JRequest::setVar('view', 'latest');
JRequest::setVar('task', '');
for ($i = 0; $i < sizeof($category->items); $i++) {
if ($user->guest){
$hits = $category->items[$i]->hits;
$category->items[$i]->hits = 0;
$category->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $category->items[$i], 'latest', '');
$category->items[$i]->hits = $hits;
}
else {
$category->items[$i] = $itemModel->prepareItem($category->items[$i], 'latest', '');
}
$category->items[$i] = $itemModel->execPlugins($category->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $category->items[$i], &$params, $limitstart));
$category->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$categories[]=$category;
}
}
}
$source = 'categories';
$this->assignRef('blocks', $categories);
} else {
$usersIDs = $params->get('userIDs');
if(is_string($usersIDs) && !empty($usersIDs)){
$usersIDs = array();
$usersIDs[]=$params->get('userIDs');
}
$users = array();
if(is_array($usersIDs)){
foreach($usersIDs as $userID){
$userObject = JFactory::getUser($userID);
if (!$userObject->block) {
//User profile
$userObject->profile = $model->getUserProfile($userID);
//User image
$userObject->avatar = K2HelperUtilities::getAvatar($userObject->id, $userObject->email, $params->get('userImageWidth'));
//User K2 plugins
$userObject->event->K2UserDisplay = '';
if (is_object($userObject->profile) && $userObject->profile->id > 0) {
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin('k2');
$results = $dispatcher->trigger('onK2UserDisplay', array(&$userObject->profile, &$params, $limitstart));
$userObject->event->K2UserDisplay = trim(implode("\n", $results));
}
$link = K2HelperRoute::getUserRoute($userObject->id);
$userObject->link = JRoute::_($link);
$userObject->feed = JRoute::_($link.'&format=feed');
$userObject->name = htmlspecialchars($userObject->name, ENT_QUOTES);
$userObject->items = $model->getAuthorLatest(0,$limit,$userID);
for ($i = 0; $i < sizeof($userObject->items); $i++) {
if ($user->guest){
$hits = $userObject->items[$i]->hits;
$userObject->items[$i]->hits = 0;
$userObject->items[$i] = $cache->call(array('K2ModelItem', 'prepareItem'), $userObject->items[$i], 'latest', '');
$userObject->items[$i]->hits = $hits;
}
else {
$userObject->items[$i] = $itemModel->prepareItem($userObject->items[$i], 'latest', '');
}
//Plugins
$userObject->items[$i] = $itemModel->execPlugins($userObject->items[$i], 'latest', '');
//Trigger comments counter event
$dispatcher = &JDispatcher::getInstance();
JPluginHelper::importPlugin ('k2');
$results = $dispatcher->trigger('onK2CommentsCounter', array ( & $userObject->items[$i], &$params, $limitstart));
$userObject->items[$i]->event->K2CommentsCounter = trim(implode("\n", $results));
}
$users[]=$userObject;
}
}
}
$source = 'users';
$this->assignRef('blocks', $users);
}
//Look for template files in component folders
$this->_addPath('template', JPATH_COMPONENT.DS.'templates');
$this->_addPath('template', JPATH_COMPONENT.DS.'templates'.DS.'default');
//Look for overrides in template folder (K2 template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'templates'.DS.'default');
//Look for overrides in template folder (Joomla! template structure)
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2'.DS.'default');
$this->_addPath('template', JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'com_k2');
//Assign params
$this->assignRef('params', $params);
$this->assignRef('source', $source);
//Set layout
$this->setLayout('latest');
//Display
parent::display($tpl);
}
}
But this file is somehow used to retrieve items in using menu link. I am sorry if this is not the case.
In order to make this work the way you want you would have to modify the K2 item model. The data you want to display (recent items in category) is not currently being pulled from the database so you'd have to change to model to accommodate that. You would be much better off using the K2 content module to pull the most recent items instead. It wouldn't require hacking any core K2 code.
Also, you really need to update your software. K2 is on v2.5.4 and Joomla is on 2.5.1.

Resources