I have successfully able to create an order through functions.php file.
I need help adding the free_shipping into the order. Can you please help with this one line?
The code I used to create an order on functions.php:
$lp_order = wc_create_order();
$lp_order->add_product( get_product( $lp_product_id ), 1 ); //(get_product with id and next is for quantity)
$lp_order->set_address( $lp_address_full, 'billing' );
$lp_order->set_address( $lp_address_full, 'shipping' );
$lp_order->update_status('processing');
$lp_order->add_shipping();
On the last line, what array should I pass to the add_shipping function? I tried using
$lp_order->add_shipping('free_shipping');
but it does not work.
Full code on functions.php
function lp_create_order() {
$lp_email = $_POST["lp_email"];
$lp_firstname = $_POST["lp_firstname"];
$lp_lastname = $_POST["lp_lastname"];
$lp_phone = $_POST["lp_phone"];
$lp_address_1 = $_POST["lp_address_1"];
$lp_address_2 = $_POST["lp_address_2"];
$lp_city = $_POST["lp_city"];
$lp_state = $_POST["lp_state"];
$lp_postcode = $_POST["lp_postcode"];
$lp_product_id = $_POST["lp_product_id"];
if ( isset( $lp_product_id ) ) {
$lp_address_full = array(
'first_name' => $lp_firstname,
'last_name' => $lp_lastname,
'company' => '',
'email' => $lp_email,
'phone' => $lp_phone,
'address_1' => $lp_address_1,
'address_2' => $lp_address_2,
'city' => $lp_city,
'state' => $lp_state,
'postcode' => $lp_postcode,
'country' => 'CA'
);
$lp_order = wc_create_order();
$lp_order->add_product( get_product( $lp_product_id ), 1 ); //(get_product with id and next is for quantity)
$lp_order->set_address( $lp_address_full, 'billing' );
$lp_order->set_address( $lp_address_full, 'shipping' );
$lp_order->update_status('processing');
//$lp_order->add_shipping('free_shipping',0);
//$lp_order->calculate_shipping();
$lp_order->calculate_totals();
print "Order is placed";
} // end if
} // end lp_create_order
add_action( 'init', 'lp_create_order' );
For the order's add_shipping method, this is what i was able to successfully pass through on Woo-Commerce 2.6
$ship_rate_ob = new WC_Shipping_Rate();
$ship_rate_ob->id=0;
$ship_rate_ob->label='Free Shipping';
$ship_rate_ob->taxes=array(); //not required in your situation
$ship_rate_ob->cost=0; //not required in your situation
$lp_order->add_shipping($ship_rate_ob);
I am setting the shipping rate's id to 0. It is working for now but I would recommend setting it to an existing free_shipping rate in your database. You can find your shipping rate's ID in the url of it's edit page.
add_shipping() expects WC_Shipping_Rate array, Use Woocommerce default free shipping package for this.
do some thing like this.
$lp_order->add_shipping(
array (
'id' => 'free_shipping',
'label' => "Free Shipping",
'cost' => 0.00,
'taxes' => array(),
'calc_tax' => 'per_order'
)
);
Try this for the shipping:
$shippingAddress = array(
'first_name' => $lp_firstname,
'last_name' => $lp_lastname,
'company' => '',
'address_1' => $lp_address_1,
'address_2' => $lp_address_2,
'city' => $lp_city,
'state' => $lp_state,
'postcode' => $lp_postcode,
'country' => 'CA'
);
Just remove email and Phone and you're good.
Not sure where the problem is in the following form used in a template file in Drupal7. Help is highly appreciated. The problems are the following:
1. The variables $title and $surname are not passed over to the form's default value.
=> Error Message: Notice: Undefined variable: title in form_user_information()
=> Error Message: Notice: Undefined variable: surname in form_user_information()
2. There's a Warning: strpos() expects parameter 1 to be string, array given in drupal_strip_dangerous_protocols()
Thanks in advance.
<?php
//Load User data:
global $user;
$uid = $user->uid;
$account = user_load($uid);
//Get User data:
$title = 'Mrs.';
print $title . '<br><br>'; //Result: Value is printed and not empty!
$surname = check_plain($account->field_vorname['und']['0']['value']);
//$surname = 'Tom';
print $surname . '<br><br>'; //Result: Both values are printed and are not empty!
function form_user_information($form, &$form_state) {
//Form
$form['#action'][] = request_uri();
$form['#id'][] = 'form_user_information';
$form['#validate'][] = 'form_user_information_validators';
$form['#submit'][] = 'form_user_information_submit';
$form['#prefix'] = '<div id="form_user_information">';
$form['#suffix'] = '</div>';
//Select-Field: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#select
$form['Title'] = array(
'#type' => 'select',
'#title' => t('Title'),
'#options' => array(
'Frau' => t('Mr.'),
'Herr' => t('Mrs.'),
),
'#default_value' => $title,
);
$form['surname'] = array(
'#type' => 'textfield',
'#maxlength' => 50,
'#size' => 40,
'#required' => TRUE,
'#title' => t('Surname'),
//'#attributes' => array('placeholder' => $surname),
'#default_value' => $surname,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Confirm data');
return $form;
}
//print form
$form = drupal_get_form('form_user_information');
print drupal_render($form);
//Form Validation:
function form_user_information_validators($form, &$form_state) {
if ($form_state['values']['surname'] == '') {
form_set_error('surname', t('Please enter your surname.'));
}
}
//Form Submit:
function form_user_information_submit($form, &$form_state) {
//...
}
//get form information
echo "<pre>".print_r($form,true)."</pre>";
?>
1) Set the global variables $title and $surname with global scope:
//Get User data:
$global $title = ...
$global $surname = ...
Otherwise set all these variables (including $user) inside the function form_user_information which is the best practice.
I would also suggest not use $title as variable name because it may cause problems with already defined $title of the $page variable. Instead use something like $user_title.
2) Which line does this come from?
Guess this issue can be closed. See the 2 comments. Thanks Theodoros for your help.
I try to get the selected value of my select in Drupal (7), but the value of the select is always empty in my hook_submit() :| !
Below my code :
<?php
function gestionvideos_players_form() {
//I get my list of players from my database
$aPlayers = EasyVod_db::get_players();
$options = array();
if( empty($aPlayers) ) {
$options[] = "no available player";
}else{
foreach( $aPlayers as $player ){
$options[$player->iPlayer] = ucfirst($player->sName);
}
}
$form['gestionvideos_player'] = array(
'#type' => 'fieldset',
'#title' => t('Integration par defaut des videos'),
'#description' => t('Selection du player par defaut : '),
);
$form['gestionvideos_player']['selectplayer'] = array(
'#type' => 'select',
'#options' => $options,
);
$form['gestionvideos_player']['submit'] = array(
'#type' => 'submit',
'#value' => t('Choisir ce player'),
);
return $form;
}
function gestionvideos_players_form_submit($form, &$form_state){
drupal_set_message("test ".$form_state['values']['selectplayer']);
//I set my player in my session variable
$oPlayer = EasyVod_db::get_player( intval($form_state['values']['selectplayer']) );
$_SESSION['player'] = $oPlayer ->player;
}
?>
I would really appreciate some help because I really don't understand what it doesn't work...
Have you tried putting
$form['#tree'] = true;
inside your form builder function then try dumping:
$form_state['values']['gestionvideos_player']['selectplayer']
I'm working on a Drupal 6 module which I want to generate a table with checkboxes in each row from data I have saved in a database. The table is being generated fine, but the checkboxes are not rendering in the table but are instead having their node id's put below the table. See the screenshot below:
"21" is the node id of "Test Question 01", and "19" is the node id of "Test Question 02".
The code I'm using (yes, it is all in a theme function which isn't ideal. I'm planning on moving stuff around once the checkboxes problem is resolved):
function theme_qt_assignment_questions_table($form) {
// Get the questions from the database
$db_results = db_query('SELECT {qt_questions}.nid, title, lesson, unit FROM node INNER JOIN {qt_questions} on {node}.nid = {qt_questions}.nid WHERE lesson = %d AND unit = %d',
$form['#lesson'], $form['#unit']);
// Define the headers for the table
$headers = array(
theme('table_select_header_cell'),
array('data' => t('Title'), 'field' => 'title'/*, 'sort' => 'asc'*/),
array('data' => t('Lesson'), 'field' => 'lesson'),
array('data' => t('Unit'), 'field' => 'unit'),
);
while($row = db_fetch_object($db_results)) {
$checkboxes[$row->nid] = '';
$form['nid'][$row->nid] = array(
'#value' => $row->nid
);
$form['title'][$row->nid] = array(
'#value' => $row->title
);
$form['lesson'][$row->nid] = array(
'#value' => $row->lesson
);
$form['unit'][$row->nid] = array(
'#value' => $row->unit
);
}
$form['checkboxes'] = array(
'#type' => 'checkboxes',
'#options' => $checkboxes,
);
// Add the questions to the table
if(!empty($form['checkboxes']['#options'])) {
foreach(element_children($form['nid']) as $nid) {
$questions[] = array(
drupal_render($form['checkboxes'][$nid]),
drupal_render($form['title'][$nid]),
drupal_render($form['lesson'][$nid]),
drupal_render($form['unit'][$nid]),
);
}
} else {
// If no query results, show as such in the table
$questions[] = array(array('data' => '<div class="error">No questions available for selected lesson and unit.</div>', 'colspan' => 4));
}
// Render the table and return the result
$output = theme('table', $headers, $questions);
$output .= drupal_render($form);
return $output;
}
Turns out my attempt at simplification of the problem was, in fact, the problem. Namely, doing everything in hook_theme isn't correct. Rather, I defined a function that pulls the info from database and creates the checkboxes array and call it in hook_form as such:
$form['questions_wrapper']['questions'] = _qt_get_questions_table($node->lesson, $node->unit);
At the end of this function (_qt_get_questions_table()), I specify the theme function which put everything into the table as such:
$form['#theme'] = 'qt_assignment_questions_table';
I'm still very new to Drupal so this explanation may not be the best to someone having the same problem, but hopefully it will help.
So I've been going at this one for a while now. I'm trying to create a draggable table that has a parent-child relationship, but where the children cannot be moved out of the parent group, and all of the parents are sortable among each other. I've modeled my form and theme off of the admin menu code, and I have it duplicating that functionality. The problem is that I can move the children to another parent, or let it become a parent. As an illustration:
Category 1
|
|--Item 1
|--Item 2
Category 2
|
|--Item 3
|--Item 4
|--Item 5
I would like to be able to sort Item 1 and Item 2 with each other, and Item 3, Item 4, and Item 5 with each other, but not move them between Category 1 and Category 2. I also need to be able to sort Category 1 and Category 2 with one another, taking the children with them. I've went through so many combinations of $action, $group, $subgroup settings mixed with $class settings for the categories and items that I've lost track. Nothing I have tried so far has produced the desired result. Here's the relevant bits of my code as it is currently:
In my form:
$form['#tree'] = true;
foreach($categories as $cat) {
if(!isset($form['categories'][$cat->cid])){
$form['categories'][$cat->cid] = array(
'weight' => array(
'#type' => 'weight',
'#delta' => 25,
'#attributes' => array('class' => array('item-weight', 'item-weight-' . $cat->cid)),
),
'cid' => array(
'#type' => 'hidden',
'#value' => $cat->cid,
'#attributes' => array('class' => array('cid')),
),
);
foreach($cats[$cat->cid] as $item) {
$form['categories'][$cat->cid]['items'][$item->id] = array(
'weight' => array(
'#type' => 'weight',
'#delta' => 25,
'#default_value'=> $item->weight,
'#attributes' => array('class' => array('item-weight', 'item-weight-' . $cat->cid)),
),
'cid' => array(
'#type' => 'hidden',
'#value' => $cat->cid,
'#attributes' => array('class' => array('cid')),
),
);
}
}
}
In my theme:
$children = element_children($form['categories']);
$rows = array();
if(count($children) > 0) {
foreach($children as $cid) {
$row = array(
drupal_render($form['categories'][$cid]['weight']) .
drupal_render($form['categories'][$cid]['cid']),
);
$rows[] = array(
'data' => $row,
'class' => array('draggable', 'tabledrag-root'),
);
foreach(element_children($form['categories'][$cid]['items']) as $id) {
$row = array(
theme('indentation', array('size' => 1)) . drupal_render($form['categories'][$cid]['items'][$id]['name']),
drupal_render($form['categories'][$cid]['items'][$id]['weight']) .
drupal_render($form['categories'][$cid]['items'][$id]['cid']),
);
$rows[] = array(
'data' => $row,
'class' => array('draggable', 'tabledrag-leaf'),
);
}
drupal_add_tabledrag('cat-table', 'order', 'sibling', 'item-weight', 'item-weight-' . $cid);
}
}
drupal_add_tabledrag('cat-table', 'match', 'parent', 'cid', 'cid', 'cid', true, 1);
$output = theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => 'cat-table')));
$output .= drupal_render_children($form);
return $output;
I've read over the documentation for drupal_add_tabledrag(), looked at the code, looked at example code, and searched around drupal.org and Google, but haven't come up with anything.
My only solution so far is to copy and modify the tabledrag.js file to just eliminate those capabilities, but while stopping the indent problem with the items (meaning, not letting them be on the same as the categories), keeping them in the same category has been Not Fun.
I suppose the most important question is, using standard Drupal is this possible?
I know you've already done a lot of coding so you might not want to give it up at this point, but DraggableViews is great to accomplish this. You can set up a normal view and add this draggableviews filter, it adds a weight and optionally a parent reference. The view itself uses the same drag-n-drop system as the rest of Drupal's backend tables.
Alternatively you can use a term reference and tie taxonomy terms to nodes, and just use that drag-n-drop.
If I'm missing something in your needs, my apologies, just thought I'd offer this simpler solution as it has definitely served me well in the past. Best of luck either way.
Just finished adding this functionality to my module
https://github.com/player259/ajax_table
There is no help, demo is outdated, but I'm working on it from time to time
Sections support was achieved by overriding tabledrag.js functions
Use this snippet to insert table
$form['map'] = array(
'#type' => 'ajax_table',
'#header' => array(t('Element'), t('Settings'), t('Weight')),
'rows' => array(),
'#draggable' => array(
// drupal_add_tabledrag will be called in theme layer
// NULL first arg to apply to this table
array(NULL, 'match', 'parent', 'perfect-form-parent', 'perfect-form-parent', 'perfect-form-index'),
array(NULL, 'depth', 'group', 'perfect-form-depth', NULL, NULL, FALSE),
array(NULL, 'order', 'sibling', 'perfect-form-weight'),
),
'#draggable_groups' => array(),
);
foreach ($map as $i => $element) {
// ... some logic
$form['map']['rows'][$i] = array(
'data' => array(
'element' => array(),
'settings' => array(),
'tabledrag' => array(
'index' => array(
'#type' => 'hidden',
'#value' => $element['data']['tabledrag']['index'],
'#attributes' => array('class' => array('perfect-form-index')),
),
'parent' => array(
'#type' => 'hidden',
'#default_value' => $element['data']['tabledrag']['parent'],
'#attributes' => array('class' => array('perfect-form-parent')),
),
'depth' => array(
'#type' => 'hidden',
'#default_value' => $element['data']['tabledrag']['depth'],
'#attributes' => array('class' => array('perfect-form-depth')),
),
'weight' => array(
'#type' => 'weight',
'#delta' => $max_weight,
'#default_value' => $weight,
'#attributes' => array('class' => array('perfect-form-weight')),
),
),
),
'#attributes' => array('class' => array($row_class_current, $row_class_child)),
);
// This means that row with $row_class_child class could have as parent
// only row with $row_class_parent class
// NULL means root - there are no parents
$form['map']['#draggable_groups'][$row_class_child] =
$depth ? $row_class_parent : NULL;
}
I had a similar problem at work so posting here my solution since none i found worked correctly in all situation. It is done 100% in javascript, on the php side you just have to set tabledrag in match with parent on pid and sort with siblings on weight.
The current code work on the example module (tabledrag parent/child) to adapt it to your need, change the .example-item-pid by your class for the PID input field. You just need to add it to the example code to have it working and see if it corresponds to your need.
First function invalidate any attempt to drop elements that don't have the same parent (PID) than the target element.
Second Function bypass the dragRow function to drop the element in the correct place (= the last children of the target row) and at the right depth ( = same depth than the target row).
/**
* Invalidate swap check if the row target is not of the same parent
* So we can only sort elements under the same parent and not move them to another parent
*
* #override Drupal.tableDrag.row.isValidSwap
*/
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype.row.prototype._isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) {
if (this.indentEnabled) {
if (row && $('.example-item-pid', this.element).val() !== $('.example-item-pid', row).val()) {
return false;
}
}
// Return the original result.
return this._isValidSwap(row);
}
/**
* Position the dragged element under the last children of the element target for swapping when moving down our dragged element.
* Removed the indentation, since we can not change parent.
* #override Drupal.tableDrag.row.dragRow
*/
Drupal.tableDrag.prototype.dragRow = function (event, self) {
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
/**
* When going down we want to position the element after the last children and not right under the currentRow
*/
// create a new row prototype with currentRow
var rowObject = new self.row(currentRow, 'mouse', self.indentEnabled, self.maxDepth, false);
// extract all children
var childrenRows = rowObject.findChildren();
// if we have children
if (childrenRows.length > 0) {
// we change the row to swap with the last children
currentRow = childrenRows[childrenRows.length - 1];
}
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
/**
* We have disabled the indentation changes since it is not possible to change parent.
*/
return false;
}
};