Nested form elements in Drupal 8 - drupal

I'm trying to wrap checkboxes element in details by doing something like this:
function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$config = \Drupal::config('pf.settings.notifications');
$form['pf'] = [
'#type' => 'details',
'#title' => t('Notification for updates in specific languages'),
'#description' => t('Expect getting one to two emails weekly'),
'#open': true,
];
$form['pf']['pf.notifications.checkboxes'] = [
'#type' => 'checkboxes',
'#title' => t('Check the ones you\'d like to recieve!'),
'#options' => [
'de' => t('german'),
'en' => t('english'),
],
'#default_value' => [
'de' => $config->get('de'),
'en' => $config->get('en'),
],
];
$form['actions']['submit']['#submit'][] = 'pf_form_user_form_submit';
}
but on submit, I get constantly back $values = ['de'=>0, 'en'=>0]:
function pf_form_user_form_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$values = $form_state->getValue('pf.notifications.checkboxes');
$config = \Drupal::config('pf.settings.notifications');
$config
->set('de', $values['de'])
->set('en', $values['en'])
->save()
;
}
As soon as I don't use the wrapping details form element, data (value==key for checked elements) is there. Like this:
function pf_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
....
// $form['pf'] = [ commented out
$form['pf.notifications.checkboxes'] = ...
....
Inspecting $form_state with debugger shows the same. Zeroes in first case, ok data in second.
Am I missing something? How does grouping of form elements work?

I inspected the $form_state through the debugger more thoroughly, and I noticed some of the keys were in original, with dots 'pf.notifications.checkboxes' while in other places, substitution for underscores took place and the key was 'pf_notifications_checkboxes'.
Works with underscores.

Related

Drupal 9 How to add pager with entityQuery

We've a Drupal 9 installation and are trying to add a pager using the pagerer module for articles entityQuery, the aim is to list tagged articles in a tag page, but it’s not working. It returns null.
When we dump the data without the pager, using default drupal query, it returns the data of all tagged articles properly.
The code is added in the theme file themeName_preprocess_page hook and being called in page--page.html.twig template file.
Here’s our code:
$query = \Drupal::entityQuery('node')
->condition('status', 1)
->condition('type', 'article');
->pager(2);
$nids = $query->sort('created', 'DESC')
->execute();
if($nids):
$nodesNews = \Drupal\node\Entity\Node::loadMultiple($nids);
$pathNews = base_path();
$pager = [
'articles_data' => $nodesNews,
'results' => [
'#theme' => 'news_pagination',
'#items' => $nodesNews,
'#path' => $pathNews,
'#tag' => $tag
],
'pager' => [
'#type' => 'pager',
'#quantity' => 5
],
];
return $pager;
endif;
And here is the code that calls the query:
<div>
{{ articles_data }}
{{ pager }}
</div>
The above code returns only one page in the navigation and we’ve 10 articles, so given that we set 2 articles per page, the output should be 5 pages instead of 1.
Also articles_data attribute returns null. Could you please help me to find what’s wrong with the code? Happy to share more information as needed, thank you.
Just reading the docs for this module here,
it would seem that you are missing at least the #theme and #style keys in your render array for the pager.
A more likely to succeed version of the above render array would be
$pager = [
'articles_data' => $nodesNews,
'results' => [
'#theme' => 'news_pagination',
'#items' => $nodesNews,
'#path' => $pathNews,
'#tag' => $tag
],
'pager' => [
'#type' => 'pager',
'#theme' => 'pagerer_base',
'#style' => 'standard',
'#config' => [
'display_restriction' => 0,
],
'#quantity' => 5
],
];

Why is the invoice page different for another user?

When I go to admin/store/orders/50457/invoice as the administrator, I see the following:
Notice how it has a payment method of "Free order" and the total at the bottom is $0.00.
When I go to the same page as a non-administrator, I see the following:
Notice how Payment Method is empty and the total for the order is $8.21.
The correct one is what the administrator sees, so what is going on that makes the two behave differently?
EDIT: It turns out in a module I created (a long time ago) called tf_store_credit.module, I have the following:
function tf_store_credit_line_item(){
global $user;
$total_credit= uc_store_credit_f_get_user_credit($user->uid);
if ($total_credit>0){
$items[] = array
(
'id' => 'store-credit', // You will use this ID in the javascript
'title' => t('Store Credit'), // This is the text that will be displayed on the line item in the subtotal
'callback' => 'tf_store_credit_line_item_callback', // This is the callback function
'stored' => TRUE,
'default' => FALSE,
'calculated' => TRUE,
'display_only' => FALSE,
'weight' => 15,
);
}
return $items;
}
The problem is that it is getting the currently logged in user's store credit instead of the user who placed the order. So how would I go about getting the correct user?
In tf_store_credit.module, I modified it like this:
function tf_store_credit_line_item(){
global $user;
$total_credit= uc_store_credit_f_get_user_credit($user->uid);
if ($total_credit>0 || in_array("view_orders", $user->roles)){
$items[] = array
(
'id' => 'store-credit', // You will use this ID in the javascript
'title' => t('Store Credit'), // This is the text that will be displayed on the line item in the subtotal
'callback' => 'tf_store_credit_line_item_callback', // This is the callback function
'stored' => TRUE,
'default' => FALSE,
'calculated' => TRUE,
'display_only' => FALSE,
'weight' => 15,
);
}
return $items;
}
In uc_free_order.module, I did a similar thing so that "Payment method" showed up:
function uc_free_order_payment_method() {
global $user;
if ($user->name=='blah' || $user->name=='blah2' || in_array("view_orders", $user->roles)){
$methods[] = array(
'id' => 'free_order',
'name' => t('Free order'),
'title' => t('Free order - payment not necessary.'),
'desc' => t('Allow customers with $0 order totals to checkout without paying.'),
'callback' => 'uc_payment_method_free_order',
'checkout' => TRUE,
'no_gateway' => TRUE,
'weight' => 10,
);
return $methods;
}
}

cannot get checkboxes value using drupal form api

i have form in drupal which uploads images and has got few checkboxes in it.
Here is the form:
$form['checklist_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Check List'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['checklist_fieldset']['heating'] = array(
'#type' => 'checkboxes',
'#title' => t('Heating options'),
'#options' => array(
'0' => t('Yes'),
'1' => t('No')
),
'#description' => t('Heating details.')
);
and here is my submit function where i am processing image upload and grabbing the checkboxes value as well. I am getting the success message and image is getting uploaded but not getting the value of check boxes.
function property_add_view_submit($form,&$form_state){
$validators = array();
if($file = file_save_upload('p_file1',$validators,file_direcotry_path)){
$heating = array_keys($form_state['values']['heating']);
drupal_set_message(t('Property Saved! '.$heating));
dpm( $form_state['values']['heating']);
}
When you use #options on a FAPI element the value passed to the $form_state is the array key, so you don't need to use array_keys().
I'm not sure why you're using checkboxes for a yes/no, usually one would use a simple checkbox element. However if that's really what you want to do:
Your #options can't contain on option with 0 as the array key, it will be automatically filtered out and you'll never know if that option has been checked.
You should use $heating_options_chosen = array_filter($form_state['values']['heating'] to get the selected checkbox options.
I honestly think your code should look like this though:
$form['checklist_fieldset']['heating'] = array(
'#type' => 'checkbox',
'#title' => t('Heating options'),
'#options' => array(
'1' => t('Yes'),
'0' => t('No')
),
'#description' => t('Heating details.')
);
$heating_checked = $form_state['values']['heating'] == 1;
If I have checkbox Friends and options are like
[ ] abc
[ ] def
[ ] ghi
[ ] jkl
And I want to know which options user have marked, then use below function.
if ($form_state->getValue('friends') != NULL) {
foreach ($form_state->getValue('friends') as $key => $value) {
if ($value != 0) {
$friends = $friends . ", " . $key;
$friends = substr_replace($friends, "", 0, 1);
}
}
}
If user has chosen abc and ghi then you will get 1,3 as result in $friends
If you wanted to know the value then use $friends = $friends.", ".$value;
it worked for me..hope it will help you as well :)

Drupal: Parent-child draggable table

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;
}
};

hook_load/hook_view not called

I have a module with four node types declared. My problem is, hook_load, hook_view is never called. I used drupal_set_message to find out if certain hook is being called. And I found out hook_load, hook_view isn't. Just to give you clear picture, here's my structure of hook_load
HERE'S UPDATED ONE
function mymodule_node_info(){
return array(
'nodetype1' => array(
'name' => t('nodetype1'),
'module' => 'mymodule_nodetype1',
'description' => t('....'),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => TRUE,
'body_label' => t('Body'),
),
'nodetype2' => array(
......
'module' => 'mymodule_nodetype2',
......
),
'nodetype3' => array(
......
'module' => 'mymodule_nodetype3',
......
),
'nodetype4' => array(
......
'module' => 'mymodule_nodetype4',
.......
),
);
}
function mymodule_nodetype1_load($node){
$result = db_query('SELECT * from {nodetype1table} WHERE vid = %d'
$node->vid
);
drupal_set_message("hook_load is provoked.","status");
return db_fetch_object($result);
}
I don't know why it is not called. I wrote this code base on drupal module writing book and follow the instructions. I've tried sample code from that book and it works ok. Only my code isn't working. Probably because of multiple node types in one module. Any help would be highly appreciated.
Your code doesn't work because hook_load() and hook_view() aren't module hooks: they're node hooks. The invocation is based off of content type names, not module names.
So, first you need to have declared your content types using hook_node_info():
function mymodule_node_info() {
$items = array();
$items['nodetype1'] = array(
'name' => t('Node Type 2'),
'module' => 'mymodule_nodetype1',
'description' => t("Nodetype 1 description"),
);
$items['nodetype2'] = array(
'name' => t('Node Type 2'),
'module' => 'mymodule_nodetype2',
'description' => t("Nodetype 2 description"),
);
$items['nodetype3'] = array(
'name' => t('Node Type 2'),
'module' => 'mymodule_nodetype3',
'description' => t("Nodetype 3 description"),
);
return $items;
}
Then, you need to use the name of the module you specified for each content type declared in hook_node_info() for your node hooks. That is, mymodule_nodetype1_load(), mymodule_nodetype2_view(), etc.
Edit
If you're trying to have a non-node based module fire when a node is viewed or loaded, you need to use hook_nodeapi():
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
switch ($op) {
case 'view':
mymodule_view_function($node);
break;
case 'load':
mymodule_load_function($node);
break;
}
}
Replace mymodule_load_function() and mymodule_load_function() with your own custom functions that are designed to act on the $node object.
Edit 2
Besides the syntax error in your hook_load() implementations, there's a piece of your code outside of what you're providing that's preventing the correct invocation. The following code works (if you create a nodetype1 node, the message "mymodule_nodetype1_load invoked" appears on the node): perhaps you can compare your entire code to see what you're missing.
function mymodule_node_info() {
return array(
'mymodule_nodetype1' => array(
'name' => t('nodetype1'),
'module' => 'mymodule_nodetype1',
'description' => t('....'),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => TRUE,
'body_label' => t('Body'),
),
'mymodule_nodetype2' => array(
'name' => t('nodetype2'),
'module' => 'mymodule_nodetype2',
'description' => t('....'),
'has_title' => TRUE,
'title_label' => t('Title'),
'has_body' => TRUE,
'body_label' => t('Body'),
),
);
}
function mymodule_nodetype1_form(&$node, $form_state) {
// nodetype1 form elements go here
return $form;
}
function mymodule_nodetype2_form(&$node, $form_state) {
// nodetype2 form elements go here
return $form;
}
function mymodule_nodetype1_load($node) {
$additions = new stdClass();
drupal_set_message('mymodule_nodetype1_load invoked');
return $additions;
}
function mymodule_nodetype2_load($node) {
$additions = new stdClass();
drupal_set_message('mymodule_nodetype2_load invoked');
return $additions;
}
If you're not reseting your environment after changes to your module, you might be running into caching issues. You should test your code in a sandbox environment that can be reset to a clean Drupal installation to ensure you're not focusing on old cruft from previous, incorrect node implementations.
Additionally, you should only be using hook_nodeapi() if you are trying to act on content types that are not defined by your module. Your content types should be using the node hooks (hook_load(), hook_view(), etc.).
Finally, it may be the case that you're using the wrong hooks because you're expecting them to fire in places they are not designed to. If you've gone through everything above, please update your post with the functionality you're expecting to achieve and where you expect the hook to fire.
I found the culprit why your code doesn't work. It's because I was using the test data created by the old codes. In my old codes, because of node declaration inside hook_node_info uses the same module value, I could only create one hook_form implementation and use "switch" statement to return appropriate form. Just to give you clear picture of my old codes-
function mymodule_node_info(){
return array(
'nodetype1' => array(
.....
'module' => 'mymodule',
.....
),
'nodetype2' => array(
......
'module' => 'mymodule',
......
),
.......
);
}
function mymodule_form(&$node, $form_state){
switch($node->type){
case 'nodetype1':
return nodetype1_form();
break;
case 'nodetype2':
return nodetype2_form();
break;
.....
}
}
When I created new data after I made those changes you have provided, hook_load is called. It works! I've tested several times(testing with old data created by previous code and testing with new data created after those changes) to make sure if that's the root cause and, I got the same result.I think drupal store form_id or module entry value of node declaration along with data and determine the hook_load call. That's probably the reason why it doesn't think it's a data of this node and thus hook_load isn't invoked.
And Thank you so much for your help.

Resources