I want to know the procedure of creating a new cart in prestashop programatically.
I am in myprestashopproject/override/controllers/admin/AdminReturnController.php.
Here I am in function postprocess().
Can anyone please help me in creating one this?
You can create cart object and can add the products to the newly created cart by calling updateQty method of the cart object
$new_cart = new Cart();
$new_cart->id_currency = $this->context->cookie->id_currency;
$new_cart->id_lang = $this->context->cookie->id_lang;
$new_cart->save();
$quantity_to_add = 1; //qty you want to add
$id_product = 1; // id of the product, which you wish to add to cart
$new_cart->updateQty($quantity_to_add, $id_product);
if you want to add multiple products, use loop and place the above updateQty method calling code inside loop and modify accordingly
Prestashop current cart id is stored in $this->context->cart->id so we have to set our newly created cart object id as the current cart
$this->context->cookie->id_cart = $new_cart->id;
$this->context->cookie->write();
$this->context->cookie->update();
If you want to regenerate cart with id_order, use the submitReorder functionnality in ParentOrderController.
$oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id));
$duplication = $oldCart->duplicate();
if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
$this->errors[] = Tools::displayError('Sorry. We cannot renew your order.');
} elseif (!$duplication['success']) {
$this->errors[] = Tools::displayError('Some items are no longer available, and we are unable to renew your order.');
} else {
$this->context->cookie->id_cart = $duplication['cart']->id;
$context = $this->context;
$context->cart = $duplication['cart'];
CartRule::autoAddToCart($context);
$this->context->cookie->write();
if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
Tools::redirect('index.php?controller=order-opc');
}
Tools::redirect('index.php?controller=order');
}
Related
I am using a hook function to create a commerce product when a node type of PL is created.
I have 2 Entity Reference fields:
Name of Project - Which references content
Type of Use - Which references a taxonomy term
Everything works and the title field is set correctly except for the 2 field values, field_name_of_project and field_type_of_use.
What could I be doing wrong.
Here's my code:
<?php
/**
* #file
* file for the PL Product Creation module, which creates a product and product variations when a Pl node is created.
*
*/
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Implementation of hook_entity_insert().
*/
function pl_product_creation_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'pl_node') {
// Get the pl node properties
$name_of_project = $entity->field_name_of_project->entity->getTitle();
$type_of_use = $entity->field_type_of_use->entity->getName();
// Load the product
$pl_product_title = 'Products at ' . $name_of_project;
// Load the product storage.
$entity_type_manager = \Drupal::service('entity_type.manager');
$product_storage = $entity_type_manager->getStorage('commerce_product');
// Load the product by title.
$pl_product = $product_storage->loadByProperties(['title' => $pl_product_title]);
// Check if the Pl product exists
if (!empty($pl_product)) {
// Load the Pl product
$pl_product = reset($pl_product);
}
else {
// Create a new Pl product
$pl_product = Product::create([
'type' => 'pl',
]);
// Set the title field.
$pl_product->setTitle($pl_product_title);
// Set the values of the custom fields.
$pl_product->set('field_name_of_project', $name_of_project);
$pl_product->set('field_type_of_use', $type_of_use);
// Save the product entity.
$pl_product->save();
}
}
}
I was finally able to figure it out. Posting here in case someone needs this in the future.
// Set the values of the custom fields.
$pl_product->set('field_name_of_project', $entity->field_name_of_project->entity);
$pl_product->set('field_type_of_use', $entity->field_type_of_use->entity);
I am trying to get the array for all the shipping forms with a new custom element that I already added. This code is not working:
$newObj = new WC_Checkout();
$shipping_fields = $newObj->get_checkout_fields($fieldset = 'shipping');
Woocommerce WC_Checkout methods:
Visit https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#197-281 for more info!
https://superuser.com?
I get NULL so the object is not existing
In detail:
I'm developing a website, where the total price is calculated according to a delivery area in some city. I decided to create a custom field within the shipping-form:
// Adding districts for the city of Lima on shipping form
add_filter('woocommerce_checkout_fields', 'custom_district_checkout_field');
function custom_district_checkout_field($fields) {
//the list for this example was shortened
$option_cities = array(
'' =>__('Select your district'),
'chorrillos' =>'Chorrillos',
'miraflores' =>'Miraflores'
};
$fields['shipping']['shipping_district']['type'] = 'select';
$fields['shipping']['shipping_district']['options'] = $option_cities;
$fields['shipping']['shipping_district']['class'] = array('update_totals_on_change');
$fields['shipping']['shipping_district']['input_class'] = array('wc-enhanced-select');
$fields['billing']['billing_district']['type'] = 'select';
$fields['billing']['billing_district']['options'] = $option_cities;
$fields['billing']['billing_district']['input_class'] = array('wc-enhanced-select');
wc_enqueue_js("jQuery( ':input.wc-enhanced-select' ).filter( ':not(.enhanced)' ).each( function() {var select2_args = { minimumResultsForSearch:5};jQuery( this ).select2( select2_args ).addClass( 'enhanced' );})");
return $fields;
I can confirm that the custome field is working. For other hand I'm trying to change the way the WooCommerce Advance Shipping plugin works as Jeroen Sormani (who is the developer) explain in his blogs:
How the plugin works!
and WAS Shipping fields conditions
The idea is to add to the condition list the shipping fields, the plugin shows by default this fields: WC Advanced Shipping Fields by Default
The goal is to been able to select the newly created field in the conditions (for example: "districts") so the price would appear in the cart when the user select the correct option, the plugin already has a list of the different districts with their respective prices. However, there is an error in the plugin because this line is not working (check the Github for the WAS Shipping fields conditions inside the first function:
$shipping_fields = WC()->checkout()->checkout_fields['shipping'];
I have been trying to solve this for weeks, hence the original ask in this post.
/**
* WAS all checkout fields
*/
add_filter('was_conditions', 'was_conditions_add_shipping_fields', 10, 1);
function was_conditions_add_shipping_fields($conditions) {
$newObj = new WC_Checkout();
$shipping_fields = $newObj->get_checkout_fields($fieldset = 'shipping');
debugToConsole($shipping_fields);
foreach ($shipping_fields as $key => $values) :
if (isset($values['label'])) :
$conditions['Shipping Fields'][$key] = $values['label'];
endif;
endforeach;
return $conditions;
}
The above results in a NULL with the debugToConsole function.
following this article:
http://techslides.com/editing-gravity-forms-entries-on-the-front-end
trying to get gravity forms to update a submission rather than create a new one.
problem is that in the
/* https://www.gravityhelp.com/documentation/article/gform_pre_submission */
add_action("gform_pre_submission", "pre_submission_handler");
function pre_submission_handler($form){
if ( strpos($_SERVER['REQUEST_URI'], 'application-edit', 0) !== false ) {
//Get original entry id
parse_str($_SERVER['QUERY_STRING']); //will be stored in $entry
//get the actual entry we want to edit
$editentry = GFAPI::get_entry($entry);
//make changes to it from new values in $_POST, this shows only the first field update
$editentry[1]=$_POST['input_1'];
//update it
$updateit = GFAPI::update_entry($editentry);
header("Location: http://yourdomain.com/apply/application-thank-you/");
//dont process and create new entry
die();
}
}
section of the code, the header redirect is not functioning. Any suggestions?
What I am trying to do is to enable/disable revision according to the selected taxonomy term in the content type that I have created i.e. when a user add the content the user can select the taxonomy term field(may be a select field) according to the selected option I want to enable/disable the revision. How can I do this?
Turn off the create new revision setting for the content type.
Then in hook_form_alter add a new submission handler before the main one:
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
//drupal_set_message("Form ID is : " . $form_id);
switch($form_id) {
case 'CONTENT_TYPE_node_form':
//dpm($form);
$form['actions']['submit']['#submit'][] = 'revision_control_node_form_submit';
$form['actions']['submit']['#submit'] = array_reverse($form['actions']['submit']['#submit']); // reverse array to put our submit handler first
break;
}
}
Then in the new submit handler check if the taxonomy term has the correct value to save a new revision. I've not tried this next bit but according to this page putting
$node->revision = 1;
before node save will create a new revision.
node_save is called in node_form_submit and the node object is built in node_form_submit_build_node.
Looking at the other attributes like vid that belong to $form_state I would say an good educated guess would be to put $form_state->revision = 1; and see if that comes out as a property of the node after node_form_submit_build_node.
So you final new submit handler will look something like:
function revision_control_node_form_submit($form, &$form_state) {
if($form_state['values']['your_taxonomy_field'] == 'your_value') {
$form_state->revision = 1;
}
}
Now I've not actually tried any of this but even if it doesn't work I'm sure you will be on the right track... Good luck!
i am currently using contact form 7 for wordpress. i would like a unique id for every form filled in and sent.
i have had a look around the internet but cant find anything, although i did find the following:
http://contactform7.com/special-mail-tags/
would there be any easy way to make my own function to do something similar to the above tags? i would need it to be a function to go into my themes function file, so that plugin updates wont affect it.
Cheers Dan
[_serial_number] field is an auto-incremented form submission ID. You just have to have Flamingo plugin installed as well. See http://contactform7.com/special-mail-tags/
(It's the same link as in the question, I guess the field wasn't there when the question was asked).
To generate ID for the Contactform7 you need to hook the 'wpcf7_posted_data'.
However, to generate incremental ID you need to save the forms in database so you can retrieve which ID should be next on next Form submit. For this you will need CFDB plugin (https://cfdbplugin.com/).
If you dont want to put the code inside theme functions.php file, you can use this plugin instead: https://wordpress.org/plugins/add-actions-and-filters/
Example code:
function pk_generate_ID($formName, $fieldName) {
//Retrieve highest ID from all records for given form stored by CFDB, increment by 1 and return.
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBFormIterator.php');
$start = '001';
$exp = new CFDBFormIterator();
$atts = array();
$atts['show'] = $fieldName;
$atts['filter'] = "$fieldName>=$start&&$fieldName<999999999999"; //is_numeric() is not permitted by default for CFDB filter
$atts['limit'] = '1';
$atts['orderby'] = "$fieldName DESC";
$atts['unbuffered'] = 'true';
$exp->export($formName, $atts);
$found = $start;
while ($row = $exp->nextRow()) {
$row2 = $row[$fieldName];
$row2 += 1;
$found = max($found,$row2);
}
return $found;
}
function pk_modify_data( $posted_data){
$formName = 'Form1'; // change this to your form's name
$fieldName = 'ID-1'; // change this to your field ID name
//Get title of the form from private property.
$cf_sub = (array) WPCF7_Submission::get_instance();
$cf = (array) $cf_sub["\0WPCF7_Submission\0contact_form"];
$title = (string) $cf["\0WPCF7_ContactForm\0title"];
if ( $posted_data && $title == $formName) ) { //formName match
$posted_data[$fieldName] = pk_generate_ID($formName, $fieldName);
}
return $posted_data;
}
add_filter('wpcf7_posted_data', 'pk_modify_data');