How to get carrier by "shipping method" in magento - magento

Typical magento's order has shipping_method. For example, in my case, it is "flatrate_flatrate".
How to bind carrier ("flatrate") with shipping_method?
Thanks for response.

public function getShippingMethodsList($quoteId, $store=null)
{
$quote = $this->_getQuote($quoteId, $store);
$quoteShippingAddress = $quote->getShippingAddress();
if (is_null($quoteShippingAddress->getId())) {
$this->_fault("shipping_address_is_not_set");
}
try {
$quoteShippingAddress->collectShippingRates()->save();
$groupedRates = $quoteShippingAddress->getGroupedAllShippingRates();
$ratesResult = array();
foreach ($groupedRates as $carrierCode => $rates ) {
$carrierName = $carrierCode;
if (!is_null(Mage::getStoreConfig('carriers/'.$carrierCode.'/title'))) {
$carrierName = Mage::getStoreConfig('carriers/'.$carrierCode.'/title');
}
foreach ($rates as $rate) {
$rateItem = $this->_getAttributes($rate, "quote_shipping_rate");
$rateItem['carrierName'] = $carrierName;
$ratesResult[] = $rateItem;
unset($rateItem);
}
}
} catch (Mage_Core_Exception $e) {
$this->_fault('shipping_methods_list_could_not_be_retrived', $e->getMessage());
}
return $ratesResult;
}

Related

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

Programmatically created order not sending order receipt email

When I make an order normally through the Magento store, I immediately get an email receipt. When I create an order through my custom code, No email is sent.
Here's my code:
private function _submitOrder($customer, $billing, $shipping, $products, $payment, $coupon, $finalize){
if($coupon && $this->_checkCouponValidity($coupon)){
$quote = Mage::getModel('sales/quote')->setCouponCode($coupon)->load();
}else{
$quote = Mage::getModel('sales/quote');
}
foreach($products as $item) {
if($item['qty']>0){
$product = Mage::getModel('catalog/product');
$productId = Mage::getModel('catalog/product')->getIdBySku($item['sku']);
$product->load($productId);
$quoteItem = Mage::getModel('sales/quote_item')->setProduct($product);
$quoteItem->setQuote($quote);
$quoteItem->setQty($item['qty']);
$quote->addItem($quoteItem);
}
}
$quote->getBillingAddress()
->addData($billing);
$quote->getShippingAddress()
->addData($billing)
->setShippingMethod('tablerate_bestway')
->setPaymentMethod('authorizenet')
->setCollectShippingRates(true);
$quote->setCheckoutMethod('guest')
->setCustomerId(null)
->setCustomerEmail($quote->getBillingAddress()->getEmail())
->setCustomerIsGuest(true)
->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
$quote->collectTotals();
$quote->save();
$convertQuote = Mage::getSingleton('sales/convert_quote');
$quotePayment = $quote->getPayment(); // Mage_Sales_Model_Quote_Payment
$quotePayment->setMethod('authorizenet');
$order = $convertQuote->addressToOrder($quote->getShippingAddress());
if($finalize){
$orderPayment = $convertQuote->paymentToOrderPayment($quotePayment);
$order->setBillingAddress($convertQuote->addressToOrderAddress($quote->getBillingAddress()));
$order->setShippingAddress($convertQuote->addressToOrderAddress($quote->getShippingAddress()));
$order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
$order->getPayment()->setCcNumber($payment['ccNumber']);
$order->getPayment()->setCcType($payment['ccType']);
$order->getPayment()->setCcExpMonth($payment['ccExpMonth']);
$order->getPayment()->setCcExpYear($payment['ccExpYear']);
$order->getPayment()->setCcLast4($payment['ccLast4']);
}
Mage::log("loop quote items");
foreach ($quote->getAllItems() as $item) {
$orderItem = $convertQuote->itemToOrderItem($item);
if ($item->getParentItem()) {
$orderItem->setParentItem($order->getItemByQuoteItemId($item->getParentItem()->getId()));
}
$order->addItem($orderItem);
}
try {
if($finalize){
$order->place();
$order->save();
if ($order->getCanSendNewEmailFlag()) {
try {
$order->sendNewOrderEmail();
} catch (Exception $e){
Mage::log($e->getMessage());
}
}
return $order;
}
else{
return $order;
}
} catch (Exception $e){
return $e->getMessage();
}
}
I figured out the problem.
This line:
$quote->getBillingAddress()->getEmail()
was returning nothing. I wasn't setting a shipping email when creating $billing. Whoops.

massupdate customer data in magento customer grid

i need to massupdate customer streetaddress using magento. for this i wrote bultupdate function in customer grid controller. here is the query but it is not working. how can i change this query to update street address using customerid
public function massUpdateAction()
{
$customerIds = $this->getRequest()->getParam('customer');
$street_type = $this->getRequest()->getParam('street');
if (!is_array($customerIds)) {
$this->_getSession()->addError($this->__('Please select customer(s).'));
} else {
if (!empty($customerIds)) {
try {
foreach ($customerIds as $customerId) {
Mage::getSingleton('customer/address')
->updateAttributes($customerIds, array('billing_street_full' => $street_type), $storeId);
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
}
$this->_redirect('*/*/index');
}
Try this:
try {
foreach ($customerIds as $customerId) {
$addresses = Mage::getModel('customer/customer')->load($customerId)->getAddressesCollection();
foreach ($addresses as $address) {
$address->setData('billing_street_full', $street_type)->save();
}
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) have been Updated.', count($customerIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}

magento final_price,min_price,max_price wrong values insertion

Hi
i have problem with the final_price,min_price,max_price in the catalog_product_index_price table its is wrongly inserting the values after function save() during import.
The file is app\code\core\Mage\Catalog\Model\Convert\Adapter\Product.php
The control goes to finish() function
public function finish()
{
Mage::dispatchEvent('catalog_product_import_after', array());
$entity = new Varien_Object();
Mage::getSingleton('index/indexer')->processEntityAction(
$entity, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
);
}
where is the insert statement to insert the value in the catalog_product_index_price table?
How this can be resolved?
My saveRow fucnction to populate database.My excel sheet contains the following additional row
Price Type:radio:1
Unit Price:absolute:2691|Case Price:absolute:12420
Unit Price:absolute:762|Case Price:absolute:7029
The save database function is
public function saveRow(array $importData)
{
$product = $this->getProductModel()
->reset();
if (empty($importData['store'])) {
if (!is_null($this->getBatchParams('store'))) {
$store = $this->getStoreById($this->getBatchParams('store'));
} else {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'store');
Mage::throwException($message);
}
}
else {
$store = $this->getStoreByCode($importData['store']);
}
if ($store === false) {
$message = Mage::helper('catalog')->__('Skipping import row, store "%s" field does not exist.', $importData['store']);
Mage::throwException($message);
}
if (empty($importData['sku'])) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" is not defined.', 'sku');
Mage::throwException($message);
}
$product->setStoreId($store->getId());
$productId = $product->getIdBySku($importData['sku']);
if ($productId) {
$product->load($productId);
}
else {
$productTypes = $this->getProductTypes();
$productAttributeSets = $this->getProductAttributeSets();
/**
* Check product define type
*/
if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
$value = isset($importData['type']) ? $importData['type'] : '';
$message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
Mage::throwException($message);
}
$product->setTypeId($productTypes[strtolower($importData['type'])]);
/**
* Check product define attribute set
*/
if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
$message = Mage::helper('catalog')->__('Skip import row, the value "%s" is invalid for field "%s"', $value, 'attribute_set');
Mage::throwException($message);
}
$product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
foreach ($this->_requiredFields as $field) {
$attribute = $this->getAttribute($field);
if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
$message = Mage::helper('catalog')->__('Skipping import row, required field "%s" for new products is not defined.', $field);
Mage::throwException($message);
}
}
}
$this->setProductTypeInstance($product);
if (isset($importData['category_ids'])) {
$product->setCategoryIds($importData['category_ids']);
}
foreach ($this->_ignoreFields as $field) {
if (isset($importData[$field])) {
unset($importData[$field]);
}
}
if ($store->getId() != 0) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
if (!in_array($store->getWebsiteId(), $websiteIds)) {
$websiteIds[] = $store->getWebsiteId();
}
$product->setWebsiteIds($websiteIds);
}
if (isset($importData['websites'])) {
$websiteIds = $product->getWebsiteIds();
if (!is_array($websiteIds)) {
$websiteIds = array();
}
$websiteCodes = explode(',', $importData['websites']);
foreach ($websiteCodes as $websiteCode) {
try {
$website = Mage::app()->getWebsite(trim($websiteCode));
if (!in_array($website->getId(), $websiteIds)) {
$websiteIds[] = $website->getId();
}
}
catch (Exception $e) {}
}
$product->setWebsiteIds($websiteIds);
unset($websiteIds);
}
$custom_options = array();
foreach ($importData as $field => $value) {
if (in_array($field, $this->_inventoryFields)) {
continue;
}
if (in_array($field, $this->_imageFields)) {
continue;
}
$attribute = $this->getAttribute($field);
if (!$attribute) {
/* CUSTOM OPTION CODE */
if(strpos($field,':')!==FALSE && strlen($value)) {
$values=explode('|',$value);
if(count($values)>0) {
#list($title,$type,$is_required,$sort_order) = explode(':',$field);
$title = ucfirst(str_replace('_',' ',$title));
$custom_options[] = array(
'is_delete'=>0,
'title'=>$title,
'previous_group'=>'',
'previous_type'=>'',
'type'=>$type,
'is_require'=>$is_required,
'sort_order'=>$sort_order,
'values'=>array()
);
foreach($values as $v) {
$parts = explode(':',$v);
$title = $parts[0];
if(count($parts)>1) {
$price_type = $parts[1];
} else {
$price_type = 'fixed';
}
if(count($parts)>2) {
$price = $parts[2];
} else {
$price =0;
}
if(count($parts)>3) {
$sku = $parts[3];
} else {
$sku='';
}
if(count($parts)>4) {
$sort_order = $parts[4];
} else {
$sort_order = 0;
}
switch($type) {
case 'file':
/* TODO */
break;
case 'field':
case 'area':
$custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;
/* NO BREAK */
case 'date':
case 'date_time':
case 'time':
$custom_options[count($custom_options) - 1]['price_type'] = $price_type;
$custom_options[count($custom_options) - 1]['price'] = $price;
$custom_options[count($custom_options) - 1]['sku'] = $sku;
break;
case 'drop_down':
case 'radio':
case 'checkbox':
case 'multiple':
default:
$custom_options[count($custom_options) - 1]['values'][]=array(
'is_delete'=>0,
'title'=>$title,
'option_type_id'=>-1,
'price_type'=>$price_type,
'price'=>$price,
'sku'=>$sku,
'sort_order'=>$sort_order,
);
break;
}
}
}
}
/* END CUSTOM OPTION CODE */
continue;
}
$isArray = false;
$setValue = $value;
if ($attribute->getFrontendInput() == 'multiselect') {
$value = explode(self::MULTI_DELIMITER, $value);
$isArray = true;
$setValue = array();
}
if ($value && $attribute->getBackendType() == 'decimal') {
$setValue = $this->getNumber($value);
}
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
if ($isArray) {
foreach ($options as $item) {
if (in_array($item['label'], $value)) {
$setValue[] = $item['value'];
}
}
} else {
$setValue = false;
foreach ($options as $item) {
if ($item['label'] == $value) {
$setValue = $item['value'];
}
}
}
}
$product->setData($field, $setValue);
}
if (!$product->getVisibility()) {
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
}
$stockData = array();
$inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
: array();
foreach ($inventoryFields as $field) {
if (isset($importData[$field])) {
if (in_array($field, $this->_toNumber)) {
$stockData[$field] = $this->getNumber($importData[$field]);
}
else {
$stockData[$field] = $importData[$field];
}
}
}
$product->setStockData($stockData);
$imageData = array();
foreach ($this->_imageFields as $field) {
if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
if (!isset($imageData[$importData[$field]])) {
$imageData[$importData[$field]] = array();
}
$imageData[$importData[$field]][] = $field;
}
}
foreach ($imageData as $file => $fields) {
try {
$product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($file), $fields);
}
catch (Exception $e) {}
}
$product->setIsMassupdate(true);
$product->setExcludeUrlRewrite(true);
$product->save();
/* Remove existing custom options attached to the product */
foreach ($product->getOptions() as $o) {
$o->getValueInstance()->deleteValue($o->getId());
$o->deletePrices($o->getId());
$o->deleteTitles($o->getId());
$o->delete();
}
/* Add the custom options specified in the CSV import file */
if(count($custom_options)) {
foreach($custom_options as $option) {
try {
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option);
$opt->saveOptions();
}
catch (Exception $e) {}
}
}
return true;
}
This section of the code has been quite well tested, so it's unlikely (though conceivable) that this is a bug that you need to correct in the indexer. Can you provide more detail about the discrepancy that you are seeing?
There is a very good chance that you are seeing unexpected results because of some product being enabled/disabled, etc etc.

Magento: Adminhtml form “Image” Field

I have set an input field of type “Image” in an admin form using the code below:
<?php
// Tab Form
// File: app/code/local/MyCompany/Mymodule/Block/Adminhtml/Items/Edit/Tab/Form.php
class MyCompany_Mymodule_Block_Adminhtml_Items_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('mymodule_form', array('legend'=>Mage::helper('mymodule')->__('Item information')));
$fieldset->addField('photo', 'image', array(
'label' => Mage::helper('mymodule')->__('Photo'),
'required' => false,
'name' => 'photo',
));
if ( Mage::getSingleton('adminhtml/session')->getMymoduleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getMymoduleData());
Mage::getSingleton('adminhtml/session')->setMymoduleData(null);
} elseif ( Mage::registry('mymodule_data') ) {
$form->setValues(Mage::registry('mymodule_data')->getData());
}
return parent::_prepareForm();
}
}
And then, inside the controller save the image using:
public function saveAction()
{
if($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('mymodule/speakers');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
$model->setKeynote($this->getRequest()->getParam('keynote'));
// Save photo
if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('photo');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS;
// Upload the image
$uploader->save($media_path, $_FILES['photo']['name']);
$data['photo'] = $media_path . $_FILES['photo']['name'];
}
catch (Exception $e) {
print_r($e);
die;
}
}
else {
if(isset($data['photo']['delete']) && $data['photo']['delete'] == 1) {
$data['photo'] = '';
}
else {
unset($data['photo']);
}
}
if(isset($data['photo'])) $model->setPhoto($data['photo']);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mymodule')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mymodule')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Long story short: When I save the item (using Save or Save and Continue Edit) in backend it saves well one time. Then the next time it gives the next error:
Notice: Array to string conversion in
/home/wwwadmin/public_html/aaa.bbb.ccc/public/lib/Zend/Db/Statement/Pdo.php
on line 232
The next saves ok. The next: error. The next ok… You know what I mean…
I was looking some code to see how this input type is used. But nothing yet. Neither inside the magento code. This is the only thing I’ve found: http://www.magentocommerce.com/wiki/how_to/how_to_create_pdf_upload_in_backend_for_own_module
Any ideas?
Thanks
When this line is runs:
$model->setData($data)->setId($this->getRequest()->getParam('id'));<br/>
$model->_data['image'] will be set to array('image'=>'[YOUR path]')<br/>
you should call method setData() after all manipulations with data['image'];
Try below code for save action in your controller
if ($data = $this->getRequest()->getPost()) {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('your_model')->load($id);
if (isset($data['image']['delete'])) {
Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
}
$image = Mage::helper('your_helper')->uploadBannerImage();
if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
$data['image'] = $image;
} else {
unset($data['image']);
}
$model->setData($data)
->setId($id);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess('Your request Save.');
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('your_helper')->__('Unable to find your request to save'));
$this->_redirect('*/*/');
}
In your helper
public function uploadBannerImage() {
$path = Mage::getBaseDir('media') . DS . 'images';
$image = "";
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array(
'jpg', 'jpeg', 'gif', 'png'
));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->save($path, $uploader->getCorrectFileName($_FILES['image']['name']));
$image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError($e->getMessage());
}
}
return $image;
}
public function deleteImageFile($image) {
if (!$image) {
return;
}
try {
$img_path = Mage::getBaseDir('media') . "/" . $image;
if (!file_exists($img_path)) {
return;
}
unlink($img_path);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}

Resources