I'm working on building a Drupal module that allows the user to select a contact. If they select a contact and the contact has children then they are allowed to select a sub child, e.g. Stackoverflow > C++ > Mark. Although I programmed this in PHP fine, I'm having difficulty getting this code to work in Drupal 7. Any assistance is welcomed :-) . I seem to be having issue with the way Drupal handles form submits (e.g. renders a form render twice).
SQL
CREATE TABLE `contacts` (
`id` int(11) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`title` varchar(100) NOT NULL,
`description` text,
`link` varchar(250) NOT NULL,
`tel` varchar(15) DEFAULT NULL,
`tel_toll_free` varchar(15) DEFAULT NULL,
`email_address` varchar(50) DEFAULT NULL,
`mail_address` varchar(500) DEFAULT NULL,
`reply_msg` text,
`image` varchar(255) DEFAULT NULL,
`relevant_links` text,
`fax` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `contacts` (`id`, `parent_id`, `title`, `description`, `link`, `tel`, `tel_toll_free`, `email_address`, `mail_address`, `reply_msg`, `image`, `relevant_links`, `fax`) VALUES
(1, NULL, 'title', 'description', 'link-1', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax'),
(2, 1, 'title', 'description', 'link-2', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax'),
(3, 2, 'title', 'description', 'link-3', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax'),
(4, 3, 'title', 'description', 'link-4', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax'),
(5, 4, 'title', 'description', 'link-5', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax'),
(6, NULL, 'title', 'description', 'link-6', 'tel', 'tel_toll_free', 'email_address', 'mail_address', 'reply_msg', 'image', 'relevant_links', 'fax');
build recursive selector
function contact_us_selector($array, $selected = NULL, $placeholder = false, $parent_id = 0){
if(is_array($array) && count($array) > 0) {
$select_box['#type'] = 'select';
$select_box['#attributes'] = array('class'=> 'jumper', 'onchange' => 'this.form.submit();');
if($placeholder){
$select_box['#options']['null'] = t('Please Choose...');
$select_box['#options_attributes']['null'] = array('selected' => 'selected', 'disabled' => 'disabled');
}
foreach($array as $row){
$select_box['#options'][$row['link']] = $row['title'];
if($row['link'] == $selected){
$select_box['#options_attributes'][$row['link']] = array('selected' => 'selected');
}
}
if($parent_id==NULL){
$parent_id = 0;
}
return array('selector_'.$parent_id => $select_box);
} else {
return null;
}
}
Display form function
function _contact_us_form($form_id, &$form_state, $conf) {
error_reporting(-1);
$form['#name'] = 'contact_selector';
$form['#prefix'] = '<h1>Contact Us</h1><br/>';
$form['#type'] = 'fieldset';
$form['contact_selector']['#type'] = 'fieldset';
$form['contact_selector']['#prefix'] = 'Who can we help you contact?';
// find out selector's current count
if(isset($form_state['values'])){
$counter = 0;
while ($form_state['values']['selector_'.($counter+1)]!=NULL){
$counter++;
}
$contact['link'] = $form_state['values']['selector_'.$counter];
// look up contact, if one is selected
if(isset($contact['link'])){
$results = db_query('SELECT `id`, `title`, `description`, `link`, `tel`, `tel_toll_free`, `email_address`, `mail_address`, `reply_msg`, `relevant_links`, `fax`
FROM `contacts`
WHERE `link` = :link
LIMIT 1',
array(':link' => $contact['link'])
);
if($results->rowCount()>0){
foreach($results as $row){
$contact['id'] = $row->id;
$contact['title'] = $row->title;
$contact['description'] = $row->description;
$contact['link'] = $row->link;
$contact['tel'] = $row->tel;
$contact['tel_toll_free'] = $row->tel_toll_free;
$contact['email_address'] = $row->email_address;
$contact['mail_address'] = $row->mail_address;
$contact['reply_msg'] = $row->reply_msg;
$contact['relevant_links'] = $row->relevant_links;
$contact['fax'] = $row->fax;
}
}
}
}
// generate select boxes for previous items
if(isset($contact['id'])){
// look up parents of selected contact
$results = db_query('SELECT `T2`.`id`, `T2`.`parent_id`, `T2`.`link`, `T2`.`title`
FROM (SELECT #r AS _id, (SELECT #r := `parent_id` FROM `contacts` WHERE `id` = _id) AS `parent_id`, #l := #l +1 AS `lvl` FROM (SELECT #r := :id, #l :=0) vars, `contacts` m WHERE #r <>0) `T1`
JOIN `contacts` `T2` ON T1._id = `T2`.`id`
ORDER BY `T1`.`lvl` DESC
LIMIT 10;',
array(':id' => $contact['id'])
);
// generate list of parent child elements
if($results->rowCount()>0){
$crumb_lvl = 0;
foreach($results as $row){
if($row->parent_id == NULL){
$results2 = db_select('contacts')
->fields('contacts', array('title','link'))
->isNull('parent_id')
->orderBy('title', 'ASC')
->execute();
} else {
$results2 = db_select('contacts')
->fields('contacts', array('title','link'))
->condition('parent_id',$contact['id'],'=')
->orderBy('title', 'ASC')
->execute();
}
if($results2->rowCount()>0){
$array = array();
foreach($results2 as $row2){
$array[] = array('title' => str_repeat('-',$crumb_lvl).' '.$row2->title, 'link' => $row2->link);
}
$form += contact_us_selector($array,$row->id,false,$row->parent_id);
}
unset($results2);
$crumb_lvl++;
}
}
}
// generate current selection
if($contact['id'] == NULL){
$results = db_select('contacts')
->fields('contacts', array('title','link'))
->isNull('parent_id')
->orderBy('title', 'ASC')
->execute();
} else {
$results = db_select('contacts')
->fields('contacts', array('title','link'))
->condition('parent_id',$contact['id'],'=')
->orderBy('title', 'ASC')
->execute();
}
if($results->rowCount()>0){
$array = array();
foreach($results as $row){
$array[] = array('title' => $row->title, 'link' => $row->link);
}
$form += contact_us_selector($array,null,true);
}
return $form;
}
The issue is with the selector pass. Using $_GET value worked nicely.
function contact_us_selector($array, $selected = NULL, $parent_id = 0){
if(is_array($array) && count($array) > 0) {
$select_box['#type'] = 'select';
$select_box['#attributes'] = array('class'=> 'jumper', 'onchange' => 'javascript:location.href = this.value;');
$select_box['#default_value'] = "?find={$selected}";
if($selected==NULL){
$select_box['#options']['null'] = t('Please Choose...');
$select_box['#options_attributes']['null'] = array('selected' => 'selected', 'disabled' => 'disabled');
}
foreach($array as $row){
$select_box['#options']["?find={$row['link']}"] = $row['title'];
}
if($parent_id==NULL){
$parent_id = 0;
}
echo '<pre>';
print_r(array('selector_'.$parent_id => $select_box));
echo '</pre>';
return array('selector_'.$parent_id => $select_box);
} else {
return;
}
}
Render
function _contact_us_form($form_id, &$form_state, $conf) {
error_reporting(-1);
//$form_state['config'] = $conf;
//$form_state['rebuild'] = TRUE;
//$form['#submit'][] = 'contact_us_form_submit';
$form['#name'] = 'contact_selector';
$form['#prefix'] = '<h1>Contact us</h1><br/>';
$form['#type'] = 'fieldset';
$form['contact_selector']['#type'] = 'fieldset';
$form['contact_selector']['#prefix'] = 'Who can we help you contact?';
// find out selector's current count
if(isset($_GET['find'])){
$contact['link'] = $_GET['find'];
// look up contact, if one is selected
if(isset($contact['link'])){
$results = db_query('SELECT `id`, `title`, `description`, `link`, `tel`, `tel_toll_free`, `email_address`, `mail_address`, `reply_msg`, `relevant_links`, `fax`
FROM `contacts`
WHERE `link` = :link
LIMIT 1',
array(':link' => $contact['link'])
);
if($results->rowCount()>0){
foreach($results as $row){
$contact['id'] = $row->id;
$contact['title'] = $row->title;
$contact['description'] = $row->description;
$contact['link'] = $row->link;
$contact['tel'] = $row->tel;
$contact['tel_toll_free'] = $row->tel_toll_free;
$contact['email_address'] = $row->email_address;
$contact['mail_address'] = $row->mail_address;
$contact['reply_msg'] = $row->reply_msg;
$contact['relevant_links'] = $row->relevant_links;
$contact['fax'] = $row->fax;
}
}
}
}
// generate select boxes for previous items
if(isset($contact['id'])){
// look up parents of selected contact
$results = db_query('SELECT `T2`.`id`, `T2`.`parent_id`, `T2`.`link`, `T2`.`title`
FROM (SELECT #r AS _id, (SELECT #r := `parent_id` FROM `contacts` WHERE `id` = _id) AS `parent_id`, #l := #l +1 AS `lvl` FROM (SELECT #r := :id, #l :=0) vars, `contacts` m WHERE #r <>0) `T1`
JOIN `contacts` `T2` ON T1._id = `T2`.`id`
ORDER BY `T1`.`lvl` DESC
LIMIT 10;',
array(':id' => $contact['id'])
);
// generate list of parent child elements
if($results->rowCount()>0){
$crumb_lvl = 0;
foreach($results as $row){
if($row->parent_id==NULL){
$results2 = db_select('contacts')
->fields('contacts',array('title','link'))
->isNull('parent_id')
->orderBy('title', 'ASC')
->execute();
} else {
$results2 = db_select('contacts')
->fields('contacts', array('title','link'))
->condition('parent_id',$row->parent_id,'=')
->orderBy('title', 'ASC')
->execute();
}
$array = array();
foreach($results2 as $row2){
$array[] = array('title' => str_repeat('-',$crumb_lvl).' '.$row2->title, 'link' => $row2->link);
}
$select_form_code = contact_us_selector($array,$row->link,$row->parent_id);
if(isset($select_form_code)){
$form += $select_form_code;
}
$crumb_lvl++;
}
}
}
// generate current selection
if($contact['id'] == NULL){
$results = db_select('contacts')
->fields('contacts', array('title','link'))
->isNull('parent_id')
->orderBy('title', 'ASC')
->execute();
} else {
$results = db_select('contacts')
->fields('contacts', array('title','link'))
->condition('parent_id',$contact['id'],'=')
->orderBy('title', 'ASC')
->execute();
}
if($results->rowCount()>0){
$array = array();
foreach($results as $row){
$array[] = array('title' => $row->title, 'link' => $row->link);
}
$form += contact_us_selector($array,null,$contact['id']);
}
return $form;
}
Related
I have missing variables when using a new email template.
I have not changed any core code for this email template.
Is anyone can help me on this ?
[ I'm using Prestashop 1.7.4.x ]
Finally i found one solution for this. Maybe someone will get help from my solution.
I've modified classes/order/OrderHistory.php and replace following code.
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{order_name}' => $order->getUniqReference()
);
Replaced above code with following one.
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
I have also added following function to current class file.
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
Bit late in the game, but I found this thread trying to do the same thing: use the "order_conf" template in a state where order details are not available.
Based on #viral answer to his own question, I had a few problems, so here is what I did to get things working in Presta Shop V1.7.3.2
Create file [WEBROOT]/override/classes/order/OrderHistory.php
Doing this, rather than changing core code will allow you to update Presta Shop without loosing your changes.
In that file I added the following content:
<?php
/**
* Make complete Order details available to email templates
*/
use PrestaShop\PrestaShop\Core\Stock\StockManager;
use PrestaShop\PrestaShop\Adapter\StockManager as StockManagerAdapter;
class OrderHistory extends OrderHistoryCore {
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)$this->id.' AND os.`send_email` = 1');
if (isset($result['template']) && Validate::isEmail($result['email'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
// JOHN
$this->context = Context::getContext();
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules_list = array();
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
$invoice = new Address((int)$order->id_address_invoice);
$delivery = new Address((int)$order->id_address_delivery);
$delivery_state = $delivery->id_state ? new State((int)$delivery->id_state) : false;
$invoice_state = $invoice->id_state ? new State((int)$invoice->id_state) : false;
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
// END JOHN
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!Mail::Send(
(int)$order->id_lang,
$result['template'],
$topic,
$data,
$result['email'],
$result['firstname'].' '.$result['lastname'],
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int)$order->id_shop
)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
/**
* Added by John
*/
protected function getEmailTemplateContent($template_name, $mail_type, $var) {
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
return '';
}
$pathToFindEmail = array(
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.'en'.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.'en'.DIRECTORY_SEPARATOR.$template_name,
);
foreach ($pathToFindEmail as $path) {
if (Tools::file_exists_cache($path)) {
$this->context->smarty->assign('list', $var);
return $this->context->smarty->fetch($path);
}
}
return 'Template Not Found';
}
}
f you search for "John" in that code, you will find the modifications from the standard "sendEmail" function and the over-ridden version.
Hope it's of help to someone.
Can't seem to make it work in 1.7.5.2..
Placed in /override/classes/order .
Erase the cache after that, every time you made changes. In prod/class_index.php. I made it work under 1.7.3.3
I was able to bring the variables to the shipped.html email template. The only problem is that the variables: {products} and {discounts} are not being displayed. Do you guys have any suggestion?
I´m using warehouse as theme and prestashop version is 1.7.8.7
HTML Preview: https://ibb.co/X8x91K6
Email Result: https://ibb.co/xSx5Pwb
As you can see in email result the variables aren´t fullfilled.
I want to upload an image via Kartik widget. After submitting the form, the $_FILE['Product'] has the data about the image but getInstance($model, 'images') returns null. Tried with images[], also null.
This is what I'm trying to var_dump in the controller:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post())) {
var_dump(UploadedFile::getInstance($model, 'images[]'));die;
And this is my model Product:
<?php
namespace app\models;
use backend\models\CActiveRecord;
use Yii;
use omgdef\multilingual\MultilingualQuery;
use omgdef\multilingual\MultilingualBehavior;
use yii\web\UploadedFile;
/**
* This is the model class for table "product".
*
* #property int $id
* #property int $category_id
* #property int $quantity
* #property double $price
* #property int $sort
*
* #property Productlang[] $productlangs
*/
class Product extends CActiveRecord
{
public $images;
public static function find()
{
return new MultilingualQuery(get_called_class());
}
public function behaviors()
{
$allLanguages = [];
foreach (Yii::$app->params['languages'] as $title => $language) {
$allLanguages[$title] = $language;
}
return [
'ml' => [
'class' => MultilingualBehavior::className(),
'languages' => $allLanguages,
//'languageField' => 'language',
//'localizedPrefix' => '',
//'requireTranslations' => false',
//'dynamicLangClass' => true',
//'langClassName' => PostLang::className(), // or namespace/for/a/class/PostLang
'defaultLanguage' => Yii::$app->params['languageDefault'],
'langForeignKey' => 'product_id',
'tableName' => "{{%productLang}}",
'attributes' => [
'title',
'description',
'meta_title',
'meta_desc',
'url'
]
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'product';
}
/**
* #inheritdoc
*/
public function rules()
{
$string = $this->multilingualFields(['description', 'url']);
$string_59 = $this->multilingualFields(['meta_title']);
$string_255 = $this->multilingualFields(['meta_desc', 'title']);
$string[] = 'description';
$string[] = 'url';
$string_59[] = 'meta_title';
$string_255[] = 'meta_desc';
$string_255[] = 'title';
return [
[['quantity', 'price', 'title', 'meta_title', 'meta_desc'], 'required'],
[['category_id', 'quantity', 'sort'], 'integer'],
[$string, 'string'],
[$string_59, 'string', 'max' => 59],
[$string_255, 'string', 'max' => 255],
[['price'], 'number'],
['images', 'file']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'category_id' => 'Category ID',
'quantity' => 'Quantity',
'price' => 'Price',
'sort' => 'Sort',
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->image as $file) {
$file->saveAs(\Yii::getAlias("#images") . "/products/" . $this->id . "_" . $this->image->baseName . '.' . $this->image->extension);
}
return true;
} else {
return false;
}
}
}
Tried with rules ['images', 'safe'] also ['images', 'file'] ( think the second one is not right because the attribute is an array, right ? ). The form is <?php $form = ActiveForm::begin(['options' => ['multipart/form-data']]); ?>.
Finally my input:
<?= $form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
]) ?>
Full controller action:
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post())) {
foreach (Yii::$app->params['languages'] as $language){
if(Yii::$app->params['languageDefault'] != $language){
$title_lang = "title_$language";
$model->$title_lang = Yii::$app->request->post('Product')["title_$language"];
$description_lang = "description_$language";
$model->$description_lang = Yii::$app->request->post('Product')["description_$language"];
$meta_title_lang = "meta_title_$language";
$model->$meta_title_lang = Yii::$app->request->post('Product')["meta_title_$language"];
$meta_desc_lang = "meta_desc_$language";
$model->$meta_desc_lang = Yii::$app->request->post('Product')["meta_desc_$language"];
}
}
if($model->save()){
$model = $this->findModel($model->id, true);
//Make urls
foreach (Yii::$app->params['languages'] as $language) {
if (Yii::$app->params['languageDefault'] != $language) {
$url_lang = "url_$language";
$title_lang = "title_$language";
$model->$url_lang = $model->constructURL(
$model->$title_lang,
$model->id
);
}else{
$model->url = $model->constructURL(
$model->title,
$model->id
);
}
}
//Upload Images
$model->images = UploadedFile::getInstance($model, 'images');
if (!($model->upload())) {
Yii::$app->session->setFlash('error', Yii::t('app', 'Some problem with the image uploading occure!'));
return $this->redirect(['create']);
}
if($model->update() !== false){
return $this->redirect(['view', 'id' => $model->id]);
}else{
Yii::$app->session->setFlash('error', Yii::t('app', 'Something went wrong. Please, try again later!'));
return $this->redirect(['create']);
}
}
}
return $this->render('create', [
'model' => $model,
]);
}
What looks like you are trying to upload a single image you should remove the [] from the input field name from the ActiveForm field declaration, and from models rules.
Single File
<?= $form->field($model, 'images')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*' ] ,
]) ?>
and from the following line
UploadedFile::getInstance($model, 'images');
Multiple Files
For multiple files you need to add 'options' => ['multiple' => true] for the field and change the attribute name to images[]
<?= $form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*' ,'multiple'=>true] ,
]) ?>
and for receiving the uploaded files you should not specify the attribute as an array just change getInstance to getInstances and then try printing, it will show you all the images use foreach() to save all of them.
UploadedFile::getInstances($model, 'images');
I personally prefer to use a separate model for file uploading rather than using the ActiveRecord model.
Note: When using multiple files upload, you can also specify the 'maxFiles'=>1000 inside you model rules to limit the number of files to be uploaded
EDIT
For troubleshooting your code you should comment out the actionCreate from the controller and replace with the one i added below
public function actionCreate() {
$model = new Product();
if ( $model->load ( Yii::$app->request->post () ) ) {
foreach ( Yii::$app->params['languages'] as $language ) {
if ( Yii::$app->params['languageDefault'] != $language ) {
$title_lang = "title_$language";
$model->$title_lang = Yii::$app->request->post ( 'Product' )["title_$language"];
$description_lang = "description_$language";
$model->$description_lang = Yii::$app->request->post ( 'Product' )["description_$language"];
$meta_title_lang = "meta_title_$language";
$model->$meta_title_lang = Yii::$app->request->post ( 'Product' )["meta_title_$language"];
$meta_desc_lang = "meta_desc_$language";
$model->$meta_desc_lang = Yii::$app->request->post ( 'Product' )["meta_desc_$language"];
}
}
$transaction = Yii::$app->db->beginTransaction ();
try {
if ( !$model->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $model->errors , 0 , false ) ) );
}
//Make urls
foreach ( Yii::$app->params['languages'] as $language ) {
if ( Yii::$app->params['languageDefault'] != $language ) {
$url_lang = "url_$language";
$title_lang = "title_$language";
$model->$url_lang = $model->constructURL (
$model->$title_lang , $model->id
);
} else {
$model->url = $model->constructURL (
$model->title , $model->id
);
}
}
//save the new urls
if ( !$model->save () ) {
throw new \Exception ( implode ( "<br />" , \yii\helpers\ArrayHelper::getColumn ( $model->errors , 0 , false ) ) );
}
//Upload Images
$model->images = UploadedFile::getInstances ( $model , 'images' );
$model->upload ();
//commit the transatction to save the record in the table
$transaction->commit ();
Yii::$app->session->setFlash ( 'success' , 'The model saved successfully.' );
return $this->redirect ( [ 'view' , 'id' => $model->id ] );
} catch ( \Exception $ex ) {
$transaction->rollBack ();
Yii::$app->session->setFlash ( 'error' , Yii::t ( 'app' , $ex->getMessage () ) );
}
}
return $this->render ( 'create' , [
'model' => $model ,
] );
}
And comment out the upload() function of your model and add below function
public function upload() {
$skipped = [];
foreach ( $this->images as $file ) {
if ( !$file->saveAs ( \Yii::getAlias ( "#images" ) . "/products/" . $this->id . "_" . $this->image->baseName . '.' . $this->image->extension ) ) {
$skipped[] = "File " . $file->baseName . " was not saved.";
}
}
if ( !empty ( $skipped ) ) {
Yii::$app->session->setFlash ( 'error' , implode ( "<br>" , $skipped ) );
}
}
And for the ActiveForm make sure your input matches the following
$form->field($model, 'images[]')->widget(FileInput::class, [
'showMessage' => true,
'pluginOptions' => [
'showCaption' => false ,
'showRemove' => false ,
'showUpload' => false ,
'showPreview' => false ,
'browseClass' => 'btn btn-success btn-block' ,
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ' ,
'browseLabel' => 'Select Profile Image'
] ,
'options' => ['accept' => 'image/*','multiple'=>true ] ,
]) ;
If I do this http://www.website.com/index.php?page=search&sCategory=123&sFeed=rss
I can create a RSS feed for a particular category. But what if I want to create a RSS feed for several selected categories? is it possible? OSClass version is 3.3.2
I didnt find a short or integrated way to do it, so I coded it.
<?php
define('ABS_PATH', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME']) . '/'));
if(PHP_SAPI==='cli') {
define('CLI', true);
}
require_once ABS_PATH . 'oc-load.php';
$mSearch = Search::newInstance();
$array_categorias = array("16","22","23","24","31","33","43","102","119","121","122","123","124");
$aItems = $mSearch->doCustomSearch($array_categorias);
View::newInstance()->_exportVariableToView('items', $aItems);
// FEED REQUESTED!
header('Content-type: text/xml; charset=utf-8');
$feed = new RSSFeed;
$feed->setTitle(__('Latest listings added') . ' - ' . osc_page_title());
$feed->setLink(osc_base_url());
$feed->setDescription(__('Latest listings added in') . ' ' . osc_page_title());
$contador_items = osc_count_items();
if(osc_count_items()>0) {
while(osc_has_items()) {
if(osc_count_item_resources() > 0){
osc_has_item_resources();
$feed->addItem(array(
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url(), ENT_COMPAT, "UTF-8" ),
'description' => osc_item_description(),
'dt_pub_date' => osc_item_pub_date(),
'image' => array( 'url' => htmlentities(osc_resource_thumbnail_url(), ENT_COMPAT, "UTF-8"),
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url() , ENT_COMPAT, "UTF-8") )
));
} else {
$feed->addItem(array(
'title' => osc_item_title(),
'link' => htmlentities( osc_item_url() , ENT_COMPAT, "UTF-8"),
'description' => osc_item_description(),
'dt_pub_date' => osc_item_pub_date()
));
}
}
}
$feed->dumpXML();
?>
I also had to add a couple of custom methods to the search model
public function _makeSQLCustomCategories($categories)
{
$cadena_select = DB_TABLE_PREFIX."t_item.*, ".DB_TABLE_PREFIX."t_item.s_contact_name as s_user_name,";
$cadena_select = $cadena_select . DB_TABLE_PREFIX. "t_item_description.s_title, ";
$cadena_select = $cadena_select . DB_TABLE_PREFIX. "t_item_description.s_description";
$this->dao->select($cadena_select);
$this->dao->from( DB_TABLE_PREFIX.'t_item' );
$this->dao->from( DB_TABLE_PREFIX. 't_item_description');
$this->dao->where(DB_TABLE_PREFIX. 't_item_description.fk_i_item_id = '. DB_TABLE_PREFIX. 't_item.pk_i_id');
//$this->dao->where(DB_TABLE_PREFIX. 't_item.b_premium = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_enabled = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_active = 1');
$this->dao->where(DB_TABLE_PREFIX. 't_item.b_spam = 0');
$where_categorias = "(";
$contador_categorias = 0;
$tamano_categories = sizeof($categories);
foreach ($categories as $categoria)
{
$contador = $contador + 1;
$where_categorias = $where_categorias. DB_TABLE_PREFIX. 't_item.fk_i_category_id = ' . $categoria ;
if ($contador == $tamano_categories)
break;
$where_categorias = $where_categorias . " OR ";
}
$where_categorias = $where_categorias . ")";
$this->dao->where($where_categorias );
$this->dao->groupBy(DB_TABLE_PREFIX.'t_item.pk_i_id');
$this->dao->orderBy(DB_TABLE_PREFIX. 't_item.pk_i_id', 'DESC');
$sql = $this->dao->_getSelect();
// reset dao attributes
$this->dao->_resetSelect();
return $sql;
}
public function doCustomSearch($categories, $extended = true, $count = true)
{
$sql = $this->_makeSQLCustomCategories($categories);
$result = $this->dao->query($sql);
if($count) {
$sql = $this->_makeSQLCustomCategories($categories);
$datatmp = $this->dao->query( $sql );
if( $datatmp == false ) {
$this->total_results = 0;
} else {
$this->total_results = $datatmp->numRows();
}
} else {
$this->total_results = 0;
}
if( $result == false ) {
return array();
}
if($result) {
$items = $result->result();
} else {
$items = array();
}
if($extended) {
return Item::newInstance()->extendData($items);
} else {
return $items;
}
}
I would like to add a variable to paypal payment form. Then I would like it to be added to the database . The variable is called "membre_id" (user ID) and is found in the $_SESSION['membre_id'].
Here's the code of form processing :
<?php
require 'lib/init.php';
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');
if ( !empty($action) ) {
switch ( $action ) {
/***********************************************************************************************************************/
case 'paypal_ipn':
require ('lib/vendor/ipnlistener.php');
$listener = new IpnListener();
try {
$verified = $listener->processIpn();
if ( $verified ) {
// parse our custom field data
$custom = post('custom');
if ( $custom ) {
parse_str(post('custom'), $data);
} else {
$data = array();
}
// pull out some values
$payment_gross = post('payment_gross');
$item_name = post('item_name');
// build customer data
$name = isset($data['name']) && $data['name'] ? $data['name'] : null;
$name_arr = explode(' ', trim($name));
$first_name = $name_arr[0];
$last_name = trim(str_replace($first_name, '', $name));
$email = isset($data['email']) && $data['email'] ? $data['email'] : null;
$description = $item_name ? $item_name : 'no description entered';
$address = isset($data['address']) && $data['address'] ? $data['address'] : null;
$city = isset($data['city']) && $data['city'] ? $data['city'] : null;
$state = isset($data['state']) && $data['state'] ? $data['state'] : null;
$zip = isset($data['zip']) && $data['zip'] ? $data['zip'] : null;
$country = isset($data['country']) && $data['country'] ? $data['country'] : null;
// check for invoice first
if ( isset($data['invoice_id']) && $data['invoice_id'] ) {
$invoice = Model::factory('Invoice')->find_one($data['invoice_id']);
$amount = $invoice->amount;
$type = 'invoice';
$description = $invoice->description;
// now check for item
} elseif ( isset($data['item_id']) && $data['item_id'] ) {
$item = Model::factory('Item')->find_one($data['item_id']);
$amount = $item->price;
$type = 'item';
// check for input amount
} elseif ( $payment_gross ) {
$amount = $payment_gross;
$type = 'input';
// return error if none found
} else {
$amount = 0;
$type = '';
}
switch ( post('txn_type') ) {
case 'web_accept':
// save payment record
$payment = Model::factory('Payment')->create();
$payment->invoice_id = isset($invoice) ? $invoice->id : null;
$payment->name = $name;
$payment->email = $email;
$payment->amount = $amount;
$payment->description = isset($item) ? $item->name : $description;
$payment->address = $address;
$payment->city = $city;
$payment->state = $state;
$payment->zip = $zip;
$payment->country = $country;
$payment->type = $type;
$payment->paypal_transaction_id = post('txn_id');
$payment->save();
// update paid invoice
if ( isset($invoice) ) {
$invoice->status = 'Paid';
$invoice->date_paid = date('Y-m-d H:i:s');
$invoice->save();
}
// build email values first
$values = array(
'customer_name' => $payment->name,
'customer_email' => $payment->email,
'amount' => currency($payment->amount) . '<small>' . currencySuffix() . '</small>',
'description_title' => isset($item) ? 'Item' : 'Description',
'description' => $payment->description,
'payment_method' => 'PayPal',
'transaction_id' => $payment->paypal_transaction_id,
'url' => url(''),
);
email($config['email'], 'payment-confirmation-admin', $values, 'You\'ve received a new payment!');
email($payment->email, 'payment-confirmation-customer', $values, 'Thank you for your payment to ' . $config['name']);
break;
case 'subscr_signup':
try {
$unique_subscription_id = uniqid();
// save subscription record
$subscription = Model::factory('Subscription')->create();
$subscription->unique_id = $unique_subscription_id;
$subscription->paypal_subscription_id = post('subscr_id');
$subscription->name = $name;
$subscription->email = $email;
$subscription->address = $address;
$subscription->city = $city;
$subscription->state = $state;
$subscription->zip = $zip;
$subscription->country = $country;
$subscription->description = isset($item) ? $item->name : $description;
$subscription->price = post('amount3');
$subscription->billing_day = date('j', strtotime(post('subscr_date')));
$subscription->length = $config['subscription_length'];
$subscription->interval = $config['subscription_interval'];
$subscription->trial_days = $config['enable_trial'] ? $config['trial_days'] : null;
$subscription->status = 'Active';
$subscription->date_trial_ends = $config['enable_trial'] ? date('Y-m-d', strtotime('+' . $config['trial_days'] . ' days')) : null;
$subscription->save();
$trial = $subscription->date_trial_ends ? ' <span style="color:#999999;font-size:16px">(Billing starts after your ' . $config['trial_days'] . ' day free trial ends)</span>' : '';
$values = array(
'customer_name' => $name,
'customer_email' => $email,
'amount' => currency(post('amount3')) . '<small>' . currencySuffix() . '</small>' . $trial,
'description_title' => isset($item) ? 'Item' : 'Description',
'description' => isset($item) ? $item->name : $description,
'payment_method' => 'PayPal',
'subscription_id' => $subscription->paypal_subscription_id,
'manage_url' => url('manage.php?subscription_id=' . $unique_subscription_id)
);
email($config['email'], 'subscription-confirmation-admin', $values, 'You\'ve received a new recurring payment!');
email($email, 'subscription-confirmation-customer', $values, 'Thank you for your recurring payment to ' . $config['name']);
} catch (Exception $e) {
}
break;
case 'subscr_cancel':
$subscription = Model::factory('Subscription')->where('paypal_subscription_id', post('subscr_id'))->find_one();
if ( $subscription ) {
$subscription->status = 'Canceled';
$subscription->date_canceled = date('Y-m-d H:i:s');
$subscription->save();
// send subscription cancelation email now
$values = array(
'customer_name' => $subscription->name,
'customer_email' => $subscription->email,
'amount' => currency($subscription->price) . '<small>' . currencySuffix() . '</small>',
'description' => $subscription->description,
'payment_method' => 'PayPal',
'subscription_id' => $subscription->paypal_subscription_id
);
email($config['email'], 'subscription-canceled-admin', $values, 'A recurring payment has been canceled.');
email($subscription->email, 'subscription-canceled-customer', $values, 'Your recurring payment to ' . $config['name'] . ' has been canceled.');
}
break;
case 'subscr_eot':
$subscription = Model::factory('Subscription')->where('paypal_subscription_id', post('subscr_id'))->find_one();
if ( $subscription && $subscription->status == 'Active' ) {
$subscription->status = 'Expired';
$subscription->date_canceled = null;
$subscription->save();
}
break;
}
} else {
die();
}
} catch (Exception $e) {
die();
}
break;
/***********************************************************************************************************************/
case 'paypal_success':
go('index.php#status=paypal_success');
break;
/***********************************************************************************************************************/
case 'paypal_subscription_success':
go('index.php#status=paypal_subscription_success');
break;
/***********************************************************************************************************************/
case 'paypal_cancel':
msg('You canceled your PayPal payment, no payment has been made.', 'warning');
go('index.php');
break;
/***********************************************************************************************************************/
case 'delete_payment':
if ( isset($_GET['id']) ) {
$payment = Model::factory('Payment')->find_one($_GET['id']);
$payment->delete();
}
msg('Payment has been deleted successfully.', 'success');
go('admin.php#tab=payments');
break;
/***********************************************************************************************************************/
case 'delete_subscription':
if ( isset($_GET['id']) ) {
$subscription = Model::factory('Subscription')->find_one($_GET['id']);
$subscription->delete();
}
msg('Subscription has been deleted successfully.', 'success');
go('admin.php#tab=subscriptions');
break;
/***********************************************************************************************************************/
case 'create_invoice':
if ( post('email') && post('amount') && post('description') ) {
$unique_invoice_id = uniqid();
$invoice = Model::factory('Invoice')->create();
$invoice->unique_id = $unique_invoice_id;
$invoice->email = post('email');
$invoice->description = post('description');
$invoice->amount = post('amount');
$invoice->number = post('number');
$invoice->status = 'Unpaid';
$invoice->date_due = post('date_due') ? date('Y-m-d', strtotime(post('date_due'))) : null;
$invoice->save();
}
$number = $invoice->number ? $invoice->number : $invoice->id();
if ( post('send_email') && post('send_email') ) {
$values = array(
'number' => $number,
'amount' => currency($invoice->amount) . '<small>' . currencySuffix() . '</small>',
'description' => $invoice->description,
'date_due' => !is_null($invoice->date_due) ? date('F jS, Y', strtotime($invoice->date_due)) : '<em>no due date set</em>',
'url' => url('?invoice_id=' . $unique_invoice_id)
);
email($invoice->email, 'invoice', $values, 'Invoice from ' . $config['name']);
$msg = ' and sent';
}
msg('Invoice has been created' . (isset($msg) ? $msg : '') . ' successfully.', 'success');
go('admin.php#tab=invoices');
break;
/***********************************************************************************************************************/
case 'delete_invoice':
if ( isset($_GET['id']) ) {
$invoice = Model::factory('Invoice')->find_one($_GET['id']);
$invoice->delete();
}
msg('Invoice has been deleted successfully.', 'success');
go('admin.php#tab=invoices');
break;
/***********************************************************************************************************************/
case 'add_item':
if ( post('name') && post('price') ) {
$item = Model::factory('Item')->create();
$item->name = post('name');
$item->price = post('price');
$item->save();
}
msg('Item has been added successfully.', 'success');
go('admin.php#tab=items');
break;
/***********************************************************************************************************************/
case 'edit_item':
if ( post('id') && post('name') && post('price') ) {
$item = Model::factory('Item')->find_one(post('id'));
$item->name = post('name');
$item->price = post('price');
$item->save();
}
msg('Item has been edited successfully.', 'success');
go('admin.php#tab=items');
break;
/***********************************************************************************************************************/
case 'delete_item':
if ( isset($_GET['id']) ) {
$item = Model::factory('Item')->find_one($_GET['id']);
$item->delete();
}
msg('Item has been deleted successfully.', 'success');
go('admin.php#tab=items');
break;
/***********************************************************************************************************************/
case 'save_config':
if ( post('config') && is_array(post('config')) ) {
foreach ( post('config') as $key => $value ) {
$config = Model::factory('Config')->where('key', $key)->find_one();
if ( $config ) {
$config->value = $value;
$config->save();
}
}
}
msg('Your settings have been saved successfully.', 'success');
go('admin.php#tab=settings');
break;
/***********************************************************************************************************************/
case 'login':
if (
post('admin_username') && post('admin_username') == $config['admin_username'] &&
post('admin_password') && post('admin_password') == $config['admin_password']
) {
// login successful, set session
$_SESSION['admin_username'] = $config['admin_username'];
} else {
// login failed, set error message
msg('Login attempt failed, please try again.', 'danger');
}
go('admin.php');
break;
/***********************************************************************************************************************/
case 'logout':
unset($_SESSION['admin_username']);
session_destroy();
session_start();
msg('You have been logged out successfully.', 'success');
go('admin.php');
break;
/***********************************************************************************************************************/
case 'install':
$status = true;
$message = '';
try {
$db = new PDO('mysql:host=' . $config['db_host'] . ';dbname=' . $config['db_name'], $config['db_username'], $config['db_password']);
$sql = file_get_contents('lib/sql/install.sql');
$result = $db->exec($sql);
} catch (PDOException $e) {
$status = false;
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
header('Content-Type: application/json');
die(json_encode($response));
break;
/***********************************************************************************************************************/
}
}
There is a parameter in the API request called "custom". That's what you need to pass your data in and then it will come back within IPN as $_POST['custom']
I followed a tutorial to create report module and the tutorial show me exactly what I wanted. Now, I would like to modify the database into my database. There are two tables that I want to join (member_download and sales_payment). What should I modify from this code to link it into my database?
Here is the code:
<?php
class Wcl_ReportNewOrders_Model_Reportneworders extends Mage_Reports_Model_Mysql4_Product_Ordered_Collection
{
function __construct() {
parent::__construct();
}
protected function _joinFields($from = '', $to = '')
{
$this->addAttributeToSelect('name')
->addAttributeToSelect('increment_id')
->addOrderedQty($from, $to)
->setOrder('sku', self::SORT_ORDER_ASC);
//Mage::log('SQL: '.$this->getSelect()->__toString());
return $this;
}
public function addOrderedQty($from = '', $to = '')
{
$adapter = $this->getConnection();
$compositeTypeIds = Mage::getSingleton('catalog/product_type')->getCompositeTypes();
$orderTableAliasName = $adapter->quoteIdentifier('order');
$addressTableAliasName = 'a';
$downloadTableAliasName = 'download';
$orderJoinCondition = array(
$orderTableAliasName . '.entity_id = order_items.order_id',
$adapter->quoteInto("{$orderTableAliasName}.state = ?", Mage_Sales_Model_Order::STATE_PROCESSING),
);
$addressJoinCondition = array(
$addressTableAliasName . '.entity_id = order.shipping_address_id'
);
$downloadJoinCondition = array(
$downloadTableAliasName . '.order_id = order_items.order_id'
);
$productJoinCondition = array(
//$adapter->quoteInto('(e.type_id NOT IN (?))', $compositeTypeIds),
'e.entity_id = order_items.product_id',
$adapter->quoteInto('e.entity_type_id = ?', $this->getProductEntityTypeId())
);
if ($from != '' && $to != '') {
$fieldName = $orderTableAliasName . '.created_at';
$orderJoinCondition[] = $this->_prepareBetweenSql($fieldName, $from, $to);
}
$this->getSelect()->reset()
->from(
array('order_items' => $this->getTable('sales/order_item')),
array(
'qty_ordered' => 'order_items.qty_ordered',
'order_items_name' => 'order_items.name',
'order_increment_id' => 'order.increment_id',
'sku' => 'order_items.sku',
'type_id' => 'order_items.product_type',
'shipping_address_id' => 'order.shipping_address_id'
))
->joinInner(
array('order' => $this->getTable('sales/order')),
implode(' AND ', $orderJoinCondition),
array())
->joinLeft(
array('a' => $this->getTable('sales/order_address')),
implode(' AND ', $addressJoinCondition),
array(
'shipto_name' => "CONCAT(COALESCE(a.firstname, ''), ' ', COALESCE(a.lastname, ''))"
),
array())
->joinLeft(
array('e' => $this->getProductEntityTableName()),
implode(' AND ', $productJoinCondition),
array(
'created_at' => 'e.created_at',
'updated_at' => 'e.updated_at'
))
->where('parent_item_id IS NULL')
//->group('order_items.product_id')
->having('order_items.qty_ordered > ?', 0);
return $this;
}
public function addItem(Varien_Object $item)
{
$itemId = $this->_getItemId($item);
if (!is_null($itemId)) {
if (isset($this->_items[$itemId])) {
// Unnecessary exception - http://www.magentocommerce.com/boards/viewthread/10634/P0/
//throw new Exception('Item ('.get_class($item).') with the same id "'.$item->getId().'" already exist');
}
$this->_items[$itemId] = $item;
} else {
$this->_items[] = $item;
}
return $this;
}
}
Please tell me how to modify the database. I am new with magento. Thanks!
i checked your link that you provided. open file at below location
Wcl_ReportNewOrders_Block_Adminhtml_ReportNewOrders_Grid
below is the function where you can modify the database
protected function _prepareCollection() {
parent::_prepareCollection();
// Get the data collection from the model
$this->getCollection()->initReport('reportneworders/reportneworders');
return $this;
}
Replace the above code with below code
protected function _prepareCollection() {
parent::_prepareCollection();
$collection = $this->getCollection()->initReport('reportneworders/reportneworders');
/*
perform your desired operation here
// print_r((string)$collection->getSelect();
*/
$this->setCollection($collection);
return $this;
}