I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}
Related
I currently have the following script, that change the producttitle of a product with a specific ID.
Now I want to re-write the script, so that it does not update the attributes but generates a .csv file of the entire catalog with two columns.
Product_SKU
$productnamingseo value
How can I achieve this?
Current working php script for 1 product, it adds successfully all product SKU's but not the referral $productnamingseo, only of the first product:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require('../app/Mage.php');
Mage::app();
$product = Mage::getModel('catalog/product')->load(409728);
Mage::register('current_product', $product);
$seotitle = Mage::helper('seo')->getCurrentSeo();
$productnamestring = Mage::getSingleton('seo/object_product')->getTitle();
$findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
$replaceseo = array('" $1', '$1', '$1$2 $3', '');
$productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);
$product->setName($productnamingseo);
$product->getResource()->saveAttribute($product, 'name');
EDIT already tried this, that works for only 1 product. All other products got that $productnamingseo value of product 1, instead of their own unique value.
This create a .csv file with the following output. Only the first line is correct. All other lines got the wrong $productnamingseo of the first product.
"ACER_EY.JE001.002","Acer C120 LED - EY.JE001.002"
"ALLIEDTELESIS_AT-2701FXA/SC-001","Acer C120 LED - EY.JE001.002"
"APC_0M-0213-005","Acer C120 LED - EY.JE001.002"
Script:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
ini_set('memory_limit', '4G');
require('app/Mage.php');
Mage::app();
$file_path = "var/import/productname.csv";
$mage_csv = new Varien_File_Csv();
$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->setPageSize(1)->setCurPage(1);
foreach ($products as $product) {
$prod = Mage::register('current_product', $product);
$seotitle = Mage::helper('seo')->getCurrentSeo();
$productnamestring = Mage::getSingleton('seo/object_product')->getTitle();
$findseo = array('/\h+inch (?:(i[357])-\w+|\h+\w+)?/', '/(\w+)#\w+/', '/(^| )(.{4,}) (.*)\2/', '/\s*-\s*$/');
$replaceseo = array('" $1', '$1', '$1$2 $3', '');
$productnamingseo = preg_replace($findseo, $replaceseo, $productnamestring);
echo $productnamingseo;
$data = array();
$data['sku'] = $product->getSku();
$data['name'] = $productnamingseo;
$products_row[] = $data;
Mage::unregister('current_product')
}
$mage_csv->saveData($file_path, $products_row);
echo 'Done!';
SEO helper Mirasvit_Seo_Model_Object_Product:
public function _construct()
{
parent::_construct();
$this->_product = Mage::registry('current_product');
if (!$this->_product) {
$this->_product = Mage::registry('product');
}
if (!$this->_product) {
return;
}
$this->_parseObjects['product'] = $this->_product;
$this->setAdditionalVariable('product', 'url', $this->_product->getProductUrl());
$this->setAdditionalVariable('product', 'final_price', $this->_product->getFinalPrice());
$this->setAdditionalVariable('product', 'final_price_minimal', Mage::helper('seo')->getCurrentProductFinalPrice($this->_product));
$this->setAdditionalVariable('product', 'final_price_range', Mage::helper('seo')->getCurrentProductFinalPriceRange($this->_product));
$this->setAdditionalVariable('product', 'stock_qty', Mage::helper('seo')->getCurrentProductStockQty($this->_product));
$categoryId = $this->_product->getSeoCategory();
$this->_category = Mage::registry('current_category');
if ($this->_category && !$categoryId) {
$this->_parseObjects['category'] = $this->_category;
} elseif ($this->_product) {
if (!$categoryId) {
$categoryIds = $this->_product->getCategoryIds();
if (count($categoryIds) > 0) {
//we need this for multi websites configuration
$categoryRootId = Mage::app()->getStore()->getRootCategoryId();
$category = Mage::getModel('catalog/category')->getCollection()
->addFieldToFilter('path', array('like' => "%/{$categoryRootId}/%"));
//don't delete (for some stores need main_table)
$stringSelect = $category->getSelect()->__toString();
$entityIdFilter = (strpos($stringSelect, 'main_table') !== false)
? 'main_table.entity_id' : 'entity_id';
$category = $category->addFieldToFilter($entityIdFilter, $categoryIds)
->setOrder('level', 'desc')
->setOrder($entityIdFilter, 'desc')
->getFirstItem()
;
$categoryId = $category->getId();
}
}
//load category with flat data attributes
$category = Mage::getModel('catalog/category')->load($categoryId);
$this->_category = $category;
$this->_parseObjects['category'] = $category;
if (!Mage::registry('seo_current_category')) {// to be sure that register will not be done twice
Mage::register('seo_current_category', $category);
};
}
$this->_parseObjects['store'] = Mage::getModel('seo/object_store');
$this->init();
}
getCurrentSeo() code:
public function getCurrentSeo()
{
if (Mage::app()->getStore()->getCode() == 'admin') {
return new Varien_Object();
}
$isCategory = Mage::registry('current_category') || Mage::registry('category');
$isProduct = Mage::registry('current_product') || Mage::registry('product');
$isFilter = false;
if ($isCategory) {
$filters = Mage::getSingleton('catalog/layer')->getState()->getFilters();
$isFilter = count($filters) > 0;
}
if ($isProduct) {
$seo = Mage::getSingleton('seo/object_product');
} elseif ($isCategory && $isFilter) {
$seo = Mage::getSingleton('seo/object_filter');
} elseif ($isCategory) {
$seo = Mage::getSingleton('seo/object_category');
} else {
$seo = new Varien_Object();
}
if ($seoTempalate = $this->checkTempalateRule($isProduct, $isCategory, $isFilter)) {
foreach ($seoTempalate->getData() as $k=>$v) {
if ($v) {
$seo->setData($k, $v);
}
}
}
if ($seoRewrite = $this->checkRewrite()) {
foreach ($seoRewrite->getData() as $k=>$v) {
if ($v) {
$seo->setData($k, $v);
}
}
}
$storeId = Mage::app()->getStore()->getStoreId();
$page = Mage::app()->getFrontController()->getRequest()->getParam('p');
if (!$page) {
$page = 1;
}
if ($isCategory && !$isProduct) {
if ($this->_titlePage) {
switch ($this->_config->getMetaTitlePageNumber($storeId)) {
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN:
if ($page > 1) {
$seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
$this->_titlePage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END:
if ($page > 1) {
$seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
$this->_titlePage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_BEGIN_FIRST_PAGE:
$seo->setMetaTitle(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaTitle()));
$this->_titlePage = false;
break;
case Mirasvit_Seo_Model_Config::META_TITLE_PAGE_NUMBER_END_FIRST_PAGE:
$seo->setMetaTitle(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaTitle(), $page));
$this->_titlePage = false;
break;
}
}
if ($this->_descriptionPage) {
switch ($this->_config->getMetaDescriptionPageNumber($storeId)) {
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN:
if ($page > 1) {
$seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
$this->_descriptionPage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END:
if ($page > 1) {
$seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
$this->_descriptionPage = false;
}
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_BEGIN_FIRST_PAGE:
$seo->setMetaDescription(Mage::helper('seo')->__("Page %s | %s", $page, $seo->getMetaDescription()));
$this->_descriptionPage = false;
break;
case Mirasvit_Seo_Model_Config::META_DESCRIPTION_PAGE_NUMBER_END_FIRST_PAGE:
$seo->setMetaDescription(Mage::helper('seo')->__("%s | Page %s", $seo->getMetaDescription(), $page));
$this->_descriptionPage = false;
break;
}
}
if ($page > 1) {
$seo->setDescription(''); //set an empty description for page with number > 1 (to not have a duplicate content)
}
}
if ($metaTitleMaxLength = $this->_config->getMetaTitleMaxLength($storeId)) {
$metaTitleMaxLength = (int)$metaTitleMaxLength;
if ($metaTitleMaxLength < Mirasvit_Seo_Model_Config::META_TITLE_INCORRECT_LENGTH) {
$metaTitleMaxLength = Mirasvit_Seo_Model_Config::META_TITLE_MAX_LENGTH; //recommended length
}
$seo->setMetaTitle($this->_getTruncatedString($seo->getMetaTitle(), $metaTitleMaxLength, $page));
}
if ($metaDescriptionMaxLength = $this->_config->getMetaDescriptionMaxLength($storeId)) {
$metaDescriptionMaxLength = (int)$metaDescriptionMaxLength;
if ($metaDescriptionMaxLength < Mirasvit_Seo_Model_Config::META_DESCRIPTION_INCORRECT_LENGTH) {
$metaDescriptionMaxLength = Mirasvit_Seo_Model_Config::META_DESCRIPTION_MAX_LENGTH; //recommended length
}
$seo->setMetaDescription($this->_getTruncatedString($seo->getMetaDescription(), $metaDescriptionMaxLength, $page));
}
return $seo;
}
I have an e-commerce site in opencart and I have a problem in the RG field which is as follows, when the user registers it fills all the fields normally but in the RG field there are those users that have one digit less in the RG that they are usually 9 more digits have users with 8 and they usually register on the site more when they are going to make a purchase they can not conclude it because the RG is with a number less would like to know if it is possible to put a code that does the following when the User to enter a RG with one digit less or less than 9 add a 0 at the end of the field so that it is complete.
This is uexatamente the input that I need to change so that when the user clicks on register it will be saved with the longest digit
<Input type = "text" name = "custom_field [account] [2]" value = "" placeholder = "RG" id = "input-custom-field2" class = "form-control">
I do not know if this is where I am going to implement my code but this is one of the controllers responsible for the registration of the form
<?php
class ControllerAccountRegister extends Controller {
private $error = array();
public function index() {
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
$this->load->language('account/register');
$this->document->setTitle($this->language->get('heading_title'));
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/moment.js');
$this->document->addScript('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js');
$this->document->addStyle('catalog/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.css');
$this->load->model('account/customer');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$customer_id = $this->model_account_customer->addCustomer($this->request->post);
// Clear any previous login attempts for unregistered accounts.
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->customer->login($this->request->post['email'], $this->request->post['password']);
unset($this->session->data['guest']);
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $customer_id,
'name' => $this->request->post['firstname']
//'name' => $this->request->post['firstname'] . ' ' . $this->request->post['lastname']
);
$this->model_account_activity->addActivity('register', $activity_data);
$this->response->redirect($this->url->link('account/success'));
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_register'),
'href' => $this->url->link('account/register', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_account_already'] = sprintf($this->language->get('text_account_already'), $this->url->link('account/login', '', 'SSL'));
$data['text_your_details'] = $this->language->get('text_your_details');
$data['text_your_address'] = $this->language->get('text_your_address');
$data['text_your_password'] = $this->language->get('text_your_password');
$data['text_newsletter'] = $this->language->get('text_newsletter');
$data['text_yes'] = $this->language->get('text_yes');
$data['text_no'] = $this->language->get('text_no');
$data['text_select'] = $this->language->get('text_select');
$data['text_none'] = $this->language->get('text_none');
$data['text_loading'] = $this->language->get('text_loading');
$data['entry_customer_group'] = $this->language->get('entry_customer_group');
$data['entry_firstname'] = $this->language->get('entry_firstname');
// $data['entry_lastname'] = $this->language->get('entry_lastname');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_telephone'] = $this->language->get('entry_telephone');
$data['entry_fax'] = $this->language->get('entry_fax');
$data['entry_company'] = $this->language->get('entry_company');
$data['entry_address_1'] = $this->language->get('entry_address_1');
$data['entry_address_2'] = $this->language->get('entry_address_2');
$data['entry_postcode'] = $this->language->get('entry_postcode');
$data['entry_city'] = $this->language->get('entry_city');
$data['entry_country'] = $this->language->get('entry_country');
$data['entry_zone'] = $this->language->get('entry_zone');
$data['entry_newsletter'] = $this->language->get('entry_newsletter');
$data['entry_password'] = $this->language->get('entry_password');
$data['entry_confirm'] = $this->language->get('entry_confirm');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_upload'] = $this->language->get('button_upload');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['firstname'])) {
$data['error_firstname'] = $this->error['firstname'];
} else {
$data['error_firstname'] = '';
}
// if (isset($this->error['lastname'])) {
// $data['error_lastname'] = $this->error['lastname'];
// } else {
// $data['error_lastname'] = '';
// }
if (isset($this->error['email'])) {
$data['error_email'] = $this->error['email'];
} else {
$data['error_email'] = '';
}
if (isset($this->error['telephone'])) {
$data['error_telephone'] = $this->error['telephone'];
} else {
$data['error_telephone'] = '';
}
if (isset($this->error['address_1'])) {
$data['error_address_1'] = $this->error['address_1'];
} else {
$data['error_address_1'] = '';
}
if (isset($this->error['city'])) {
$data['error_city'] = $this->error['city'];
} else {
$data['error_city'] = '';
}
if (isset($this->error['postcode'])) {
$data['error_postcode'] = $this->error['postcode'];
} else {
$data['error_postcode'] = '';
}
if (isset($this->error['country'])) {
$data['error_country'] = $this->error['country'];
} else {
$data['error_country'] = '';
}
if (isset($this->error['zone'])) {
$data['error_zone'] = $this->error['zone'];
} else {
$data['error_zone'] = '';
}
if (isset($this->error['custom_field'])) {
$data['error_custom_field'] = $this->error['custom_field'];
} else {
$data['error_custom_field'] = array();
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
if (isset($this->error['confirm'])) {
$data['error_confirm'] = $this->error['confirm'];
} else {
$data['error_confirm'] = '';
}
$data['action'] = $this->url->link('account/register', '', 'SSL');
$data['customer_groups'] = array();
if (is_array($this->config->get('config_customer_group_display'))) {
$this->load->model('account/customer_group');
$customer_groups = $this->model_account_customer_group->getCustomerGroups();
foreach ($customer_groups as $customer_group) {
if (in_array($customer_group['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$data['customer_groups'][] = $customer_group;
}
}
}
if (isset($this->request->post['customer_group_id'])) {
$data['customer_group_id'] = $this->request->post['customer_group_id'];
} else {
$data['customer_group_id'] = $this->config->get('config_customer_group_id');
}
if (isset($this->request->post['firstname'])) {
$data['firstname'] = $this->request->post['firstname'];
} else {
$data['firstname'] = '';
}
// if (isset($this->request->post['lastname'])) {
// $data['lastname'] = $this->request->post['lastname'];
// } else {
// $data['lastname'] = '';
// }
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['telephone'])) {
$data['telephone'] = $this->request->post['telephone'];
} else {
$data['telephone'] = '';
}
if (isset($this->request->post['fax'])) {
$data['fax'] = $this->request->post['fax'];
} else {
$data['fax'] = '';
}
if (isset($this->request->post['company'])) {
$data['company'] = $this->request->post['company'];
} else {
$data['company'] = '';
}
if (isset($this->request->post['address_1'])) {
$data['address_1'] = $this->request->post['address_1'];
} else {
$data['address_1'] = '';
}
if (isset($this->request->post['address_2'])) {
$data['address_2'] = $this->request->post['address_2'];
} else {
$data['address_2'] = '';
}
if (isset($this->request->post['postcode'])) {
$data['postcode'] = $this->request->post['postcode'];
} elseif (isset($this->session->data['shipping_address']['postcode'])) {
$data['postcode'] = $this->session->data['shipping_address']['postcode'];
} else {
$data['postcode'] = '';
}
if (isset($this->request->post['city'])) {
$data['city'] = $this->request->post['city'];
} else {
$data['city'] = '';
}
if (isset($this->request->post['country_id'])) {
$data['country_id'] = $this->request->post['country_id'];
} elseif (isset($this->session->data['shipping_address']['country_id'])) {
$data['country_id'] = $this->session->data['shipping_address']['country_id'];
} else {
$data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->request->post['zone_id'])) {
$data['zone_id'] = $this->request->post['zone_id'];
} elseif (isset($this->session->data['shipping_address']['zone_id'])) {
$data['zone_id'] = $this->session->data['shipping_address']['zone_id'];
} else {
$data['zone_id'] = '';
}
$this->load->model('localisation/country');
$data['countries'] = $this->model_localisation_country->getCountries();
// Custom Fields
$this->load->model('account/custom_field');
$data['custom_fields'] = $this->model_account_custom_field->getCustomFields();
if (isset($this->request->post['custom_field'])) {
if (isset($this->request->post['custom_field']['account'])) {
$account_custom_field = $this->request->post['custom_field']['account'];
} else {
$account_custom_field = array();
}
if (isset($this->request->post['custom_field']['address'])) {
$address_custom_field = $this->request->post['custom_field']['address'];
} else {
$address_custom_field = array();
}
$data['register_custom_field'] = $account_custom_field + $address_custom_field;
} else {
$data['register_custom_field'] = array();
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
if (isset($this->request->post['confirm'])) {
$data['confirm'] = $this->request->post['confirm'];
} else {
$data['confirm'] = '';
}
if (isset($this->request->post['newsletter'])) {
$data['newsletter'] = $this->request->post['newsletter'];
} else {
$data['newsletter'] = '';
}
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info) {
$data['text_agree'] = sprintf($this->language->get('text_agree'), $this->url->link('information/information/agree', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$data['text_agree'] = '';
}
} else {
$data['text_agree'] = '';
}
if (isset($this->request->post['agree'])) {
$data['agree'] = $this->request->post['agree'];
} else {
$data['agree'] = false;
}
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/register.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/register.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/register.tpl', $data));
}
}
public function validate() {
if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
$this->error['firstname'] = $this->language->get('error_firstname');
}
// if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
// $this->error['lastname'] = $this->language->get('error_lastname');
// }
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\#]+#.*.[a-z]{2,15}$/i', $this->request->post['email'])) {
$this->error['email'] = $this->language->get('error_email');
}
if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
$this->error['warning'] = $this->language->get('error_exists');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$this->error['telephone'] = $this->language->get('error_telephone');
}
if ((utf8_strlen(trim($this->request->post['address_1'])) < 3) || (utf8_strlen(trim($this->request->post['address_1'])) > 128)) {
$this->error['address_1'] = $this->language->get('error_address_1');
}
if ((utf8_strlen(trim($this->request->post['city'])) < 2) || (utf8_strlen(trim($this->request->post['city'])) > 128)) {
$this->error['city'] = $this->language->get('error_city');
}
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($this->request->post['postcode'])) < 2 || utf8_strlen(trim($this->request->post['postcode'])) > 10)) {
$this->error['postcode'] = $this->language->get('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$this->error['country'] = $this->language->get('error_country');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$this->error['zone'] = $this->language->get('error_zone');
}
// Customer Group
if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
// Custom field validation
$this->load->model('account/custom_field');
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
if ($custom_field['required'] && empty($this->request->post['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
$this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
}
}
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$this->error['password'] = $this->language->get('error_password');
}
if ($this->request->post['confirm'] != $this->request->post['password']) {
$this->error['confirm'] = $this->language->get('error_confirm');
}
// Agree to terms
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info && !isset($this->request->post['agree'])) {
$this->error['warning'] = sprintf($this->language->get('error_agree'), $information_info['title']);
}
}
return !$this->error;
}
public function customfield() {
$json = array();
$this->load->model('account/custom_field');
// Customer Group
if (isset($this->request->get['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->get['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->get['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
foreach ($custom_fields as $custom_field) {
$json[] = array(
'custom_field_id' => $custom_field['custom_field_id'],
'required' => $custom_field['required']
);
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
may be you can use this script.
function putZeroToLastItem($text) {
$length = strlen($text);
if( $length < 9 ) {
$text .= '0'
}
return $text
}
I hope , this script will solve your porblem.
<?php
$num = 3;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 03
?>
Try this simple snippet
You want to add 0 after the number (9 digit)? Use jquery if you want it in client side.
function addZero (data){
return data+(data <10 ? '0':'');
}
var num =$('#number').val();
var nNum = addZero(num);
Hope it helps.
A reduced way of #mehfatitem:
function putZeroToLastItem($text) {
return (strlen($text) < 9) ? $text . '0' : $text;
}
I am using consolibyte Quickbook online version for php.
I am creating the invoice and it is working fine for me.
And I am include tax in line. but I have to remove that tax and want to add in overall tax.
Can someone please help me.
Everything is working fine I just want to add tax same as attached image.
Please help
Thanks in advance
My code for add the invoice :
public function addInvoice($invoiceArray,$chargeArray,$customerRef,$db_product,$invoice_id,$other_charges,$price_grid,$payment,$orderId,$quickbook_id,$display_order_id,$payment_terms_name,$payment_terms_day){
$IPP = new \QuickBooks_IPP($this->QBO_DSN);
// Get our OAuth credentials from the database
$creds = $this->IntuitAnywhere->load(Session::get('useremail'), Session::get('user_id'));
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
\QuickBooks_IPP::AUTHMODE_OAUTH,
Session::get('useremail'),
$creds);
if ($this->is_sandbox) {
// Turn on sandbox mode/URLs
$IPP->sandbox(true);
}
// This is our current realm
$this->realm = $creds['qb_realm'];
// Load the OAuth information from the database
$this->context = $IPP->context();
$InvoiceService = new \QuickBooks_IPP_Service_Invoice();
if($quickbook_id > 0) {
$retr = $InvoiceService->delete($this->context, $this->realm, $quickbook_id);
}
$Invoice = new \QuickBooks_IPP_Object_Invoice();
$CustomField = new \QuickBooks_IPP_Object_CustomField();
$CustomField->setDefinitionId('2');
$CustomField->setName('Sales Rep');
$CustomField->setType('StringType');
$CustomField->setStringValue($invoiceArray[0]->sales_name);
$Invoice->addCustomField($CustomField);
$CustomField1 = new \QuickBooks_IPP_Object_CustomField();
$CustomField1->setDefinitionId('1');
$CustomField1->setName('Customer PO');
$CustomField1->setType('StringType');
$CustomField1->setStringValue($invoiceArray[0]->custom_po);
$Invoice->addCustomField($CustomField1);
$Invoice->setDocNumber('INV-' . $display_order_id);
$Invoice->setTxnDate(date('Y-m-d'));
if($payment_terms_name != '') {
if($payment_terms_day > 0) {
$due_day = $payment_terms_day;
} else {
$due_day = 0;
}
$TermService = new \QuickBooks_IPP_Service_Term();
$terms = $TermService->query($this->context, $this->realm, "SELECT * FROM Term WHERE Name = '".$payment_terms_name."' ");
$Term = new \QuickBooks_IPP_Object_Term();
$payment_terms_id = 0;
if(!empty($terms)){
$Term = $terms[0];
$payment_terms_id = $Term->getId();
$payment_terms_id = str_replace('{','',$payment_terms_id);
$payment_terms_id = str_replace('}','',$payment_terms_id);
$payment_terms_id = abs($payment_terms_id);
}
if($payment_terms_id > 0) {
$Invoice->setSalesTermRef($payment_terms_id);
} else {
$Term->setName($payment_terms_name);
$Term->setDueDays($due_day);
if ($resp = $TermService->add($this->context, $this->realm, $Term))
{
$payment_terms_id = $this->getId($resp);
$Invoice->setSalesTermRef($payment_terms_id);
}
}
if($due_day > 0) {
$setDate = date('Y-m-d', strtotime("+".$due_day. "days"));
$Invoice->setDueDate($setDate);
} else {
$Invoice->setDueDate(date('Y-m-d'));
}
}
foreach ($invoiceArray as $key => $value) {
$desc = array();
foreach ($value->sizeData as $sizeAll) {
$desc[] = $sizeAll->size.'('.$sizeAll->qnty.')';
}
$description = implode(', ' , $desc);
$product_name_desc_display = $value->product_name.' : '.$value->color_name.' : '.$description;
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount($value->total_line_charge * $value->total_qnty);
$Line->setDescription($product_name_desc_display);
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
if($value->vendor_id == 1) {
$SalesItemLineDetail->setItemRef($db_product[0]->ss);
} else {
$SalesItemLineDetail->setItemRef($db_product[0]->custom_product);
}
$SalesItemLineDetail->setUnitPrice($value->total_line_charge);
$SalesItemLineDetail->setQty($value->total_qnty);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if($chargeArray[0]->order_total != 0 && $chargeArray[0]->order_total != '') {
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount($chargeArray[0]->tax);
$Line->setDescription('Tax-'.$chargeArray[0]->tax_rate);
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef($db_product[0]->tax_charge);
$SalesItemLineDetail->setUnitPrice($chargeArray[0]->tax);
$SalesItemLineDetail->setQty(1);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if($chargeArray[0]->discount != 0 && $chargeArray[0]->discount != '') {
$Line = new \QuickBooks_IPP_Object_Line();
$Line->setDetailType('SalesItemLineDetail');
$Line->setAmount(-$chargeArray[0]->discount);
$Line->setDescription('Discount');
$SalesItemLineDetail = new \QuickBooks_IPP_Object_SalesItemLineDetail();
$SalesItemLineDetail->setItemRef($db_product[0]->discount_charge);
$SalesItemLineDetail->setUnitPrice(-$chargeArray[0]->discount);
$SalesItemLineDetail->setQty(1);
$Line->addSalesItemLineDetail($SalesItemLineDetail);
$Invoice->addLine($Line);
$Invoice->setCustomerRef($customerRef);
}
if ($resp = $InvoiceService->add($this->context, $this->realm, $Invoice))
{
$qb_invoice_id = $this->getId($resp);
$this->common->UpdateTableRecords('invoice',array('id' => $invoice_id),array('qb_id' => $qb_invoice_id));
//if($quickbook_id > 0) {
$this->common->UpdateTableRecords('payment_history',array('order_id' => $orderId),array('qb_id' => $qb_invoice_id,'qb_flag' => 0));
// }
return 1;
}
else
{
return 0;
}
}
enter image description here
I need to save some data's in php. I am trying this code
$click_free = [];
$ano = 0;
while($res_qry = mysql_fetch_array($sel_qry)){
$arr_cnt = sizeof($click_free);
if($arr_cnt != 0){
$m = 0;
for($k=0;$k<$arr_cnt;$k++)
{
if($click_free[$k][0] == $res_qry['Free_id'])
{
$click_free[$k][0] = ($click_free[$k][0]+$res_qry['Qty']);
$m=1;
}
}if($m==0){
$click_free[$arr_cnt] = [1,];
}
}else{
$click_free[0] = [$res_qry['Free_id'],$res_qry['Qty']];
}
}
But this code has many error. Please help me solve this
while($res_qry = mysql_fetch_array($sel_qry)){
$id_existed = false;
if(!empty($click_free))
foreach($click_free as $key=>$ligne)
if( $ligne[0] == $res_qry['Free_id']){
$qty = $ligne[1] + $res_qry['Qty'];
$click_free[$key] = [ $ligne[0] , $qty ];
$id_existed =true;
}
if(!$id_existed){
$click_free[] = [ $res_qry['Free_id'] , $res_qry['Qty'] ];
}
}
Finally we got a solution
while($res_qry = mysql_fetch_array($sel_qry)){
$arr_cnt = sizeof($click_free);
if($arr_cnt != 0){
$m = 0;
foreach ($click_free as $k => $v) {
if ($v['Free_id']==$res_qry['Free_id']) {
S_qty=$v['Qty']+$res_qry['Qty'];
$click_free[$k]['Qty']=$S_qty;
$m=1;
}
}
if($m==0){
$click_free[] = array("Free_id" => $res_qry['Free_id'],"Qty"=>$res_qry['Qty']);
}
}else{
$click_free[] = array("Free_id" => $res_qry['Free_id'],"Qty"=>$res_qry['Qty']);
}
}
Thanks to bfahmi, Kris Roofe, B. Desai , user3542450, dr_debug
I have Already Created The Categories in Magento by using the custom script,
but issue is when I again run the same URL my script creates another set of same category. as i want to update the existing category and insert the new categories if exist in the csv.
My csv structure is:
Category 1,Description,Category 2,Description,Category 3,Description,Category 4,Description
1,COSTUMES,1,ADULTS,1,MENS
1,COSTUMES,1,ADULTS,1,MENS,2,ASIAN
1,COSTUMES,1,ADULTS,1,MENS,3,BIKER
1,COSTUMES,1,ADULTS,1,MENS,1,CAPES & ROBES
1,COSTUMES,1,ADULTS,1,MENS,5,CAVE PEOPLE
Thanking All of You in Advance For Your Answer
Below is my code to create multi level categories:
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$count = 0;
$file = fopen('export/web categories.csv', 'r');
function odd($var)
{
$odd = array();
foreach ($var as $k => $v) {
if ($k % 2 !== 0) {
$odd[$k] = $v;
}
}
return $odd;
}
function even($var)
{
$even = array();
foreach ($var as $k => $v) {
if ($k % 2 == 0) {
$even[$k] = $v;
}
}
return $even;
}
function strcount($str,$sy){
$ch= explode($sy, $str);
return count($ch);
}
$pos=0;
$row_config= array();
$test=array();
$catgoryID=array();
$parID = 1;
while (($line = fgetcsv($file)) !== FALSE) {
if(!in_array($valtest,$row_config)){
if($count == 0){
$count++;
continue;
}
$count++;
$filterd_data=array_filter($line);
$odd_cell_data=odd($filterd_data);
$even_cell_data=even($filterd_data);
$config=array();
$string='';
$intialID=$even_cell_data[0];
foreach($odd_cell_data as $key=>$val){
if(!in_array($val,$config)){
$config[] = $val;
$data['general']['name'] =$val;
$data['general']['meta_title'] = "";
$data['general']['meta_description'] = "";
$data['general']['is_active'] = "";
$data['general']['url_key'] = "";
$data['general']['is_anchor'] = 0;
$data['general']['position'] =1 ;
$storeId = 0;
$string .=$val.'~';
if(!array_key_exists($string, $row_config)){
$catID=createCategory($data, $storeId);
$catgoryID[$string]=$catID;
$row_config[$string]=$parID;
} else {
$parID =$row_config[$string] ;
$row_config[$string]=$row_config[$string];
}
if( strcount($string,'~')==2){
$parID=1;
}
$int[$string]=$parID;
assignCat($catgoryID[$string],$parID);
$parID = $catgoryID[$string];
sleep(0.5);
unset($data);
}
}
}
}
//This Function is used for create each category
function createCategory($data, $storeId) {
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeId);
if (is_array($data)) {
$category->addData($data['general']);
if (!$category->getId()) {
$parentId = $data['category']['parent'];
if (!$parentId) {
if ($storeId) {
$parentId = Mage::app()->getStore($storeId)->getRootCategoryId();
} else {
$parentId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
}
}
$parentCategory = Mage::getModel('catalog/category')->load($parentId);
$category->setPath($parentCategory->getPath());
} if ($useDefaults = $data['use_default']) {
foreach ($useDefaults as $attributeCode) {
$category->setData($attributeCode, null);
}
}
$category->setAttributeSetId($category->getDefaultAttributeSetId());
if (isset($data['category_products']) && !$category->getProductsReadonly()) {
$products = array();
parse_str($data['category_products'], $products);
$category->setPostedProducts($products);
} try {
$category->save();
$category = Mage::getModel('catalog/category')->load($category->getId());
$category->setPosition($data['general']['position']);
$category->addData($data['general']);
$category->save();
echo "Suceeded <br /> ";
} catch (Exception $e) {
echo "Failed <br />";
}
}
return $category->getId();
}
//This Function is used for moving category under respective parent
function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}