Facets with default

1 week ago

Anybody know how to set a default facet value?

I have facets set up and working using facet_api blocks alongside a view in a panel. Is there a (hopefully easy) way to set one of the facets have a value selected by default on an initial page render?

//fyi Drupal 7.

Thanks.

jessehensold

Adding value to multi-delta textfield programmatically

1 week ago

I have a phone field in a form, which is just a textfield with its default widget. I'm trying (and failing) to add values to this field programmatically through ajax calls.

I have an ajax call elsewhere on the form, the purpose of which is to add several values to the phone (text) field, and let the user continue to edit them or add more.

My strategy in the ajax callback function has been to take the first textfield delta as a template, and reproduce it to add more. That's not working, because there are too many values to set that have side effects, like ['#delta'] or ['#max_delta']. The modules that manage this even seem to use #id suffixes to control behaviours.

The code below loads the values all right (3 of them show up on the form after the call), but when I press "Add another item", the field collapses from 3 values to 2. A subsequent "Add another item" call then opens up a blank new item, ie starts to behave normally. So something amiss after my ajax operation on the form structure, but gets reset with the first subsequent "Add another item" call. But I haven't been able to isolate what the problem is.

In any case, I think I'm using a bad strategy, and instead need some kind of helper function, or at least a strategy that conforms to Drupal-wide patterns.

So, how do I do this? I need a strategy or an example.

Here's my current ajax callback. The parts other than phone update are working, but the phone part is a mess. The phone part demonstrates what I want to do with updating phones, and the complexity shows why my current strategy isn't working for that phone part.

function rc_business_card_populate_from_staff($form,&$form_state) { // =============================================== // THIS PART WORKS $selected_staff_id = $form_state['values']['line_item_fields']['field_staff']['und'][0]['profile_id']; if (is_null($selected_staff_id)) return $form; // do nothing // assemble input fields for data $address = &$form['line_item_fields']['field_recipient_address']['und'][0]; $street_block = &$address['street_block']; $locality_block = &$address['locality_block']; $organisation_block = &$address['organisation_block']; $name_block = &$address['name_block']; $values = array( // address field: 'name_line' => &$name_block['name_line']['#value'],// Full Name 'organisation_name' => &$organisation_block['organisation_name']['#value'], // Company 'thoroughfare' => &$street_block['thoroughfare']['#value'], // Address 1 'premise' => &$street_block['premise']['#value'],// Address 2 'locality' => &$locality_block['locality']['#value'], // City 'administrative_area' => &$locality_block['administrative_area']['#value'], // Province 'postal_code' => &$locality_block['postal_code']['#value'],// Postal Code // independent fields: 'field_designation' => &$form['line_item_fields']['field_designation']['und'][0]['value']['#value'], // Designation 'field_email' => &$form['line_item_fields']['field_email']['und'][0]['email']['#value'],// Email 'field_website' => &$form['line_item_fields']['field_website']['und'][0]['value']['#value'], // Website // phone field, independent: ); // =============================================== // THIS PART DOESN'T WORK $field_phone = &$form['line_item_fields']['field_phone']['und']; $field_phone_template = $form['line_item_fields']['field_phone']['und'][0]; // assemble input data $entities = entity_load('commerce_customer_profile',array($selected_staff_id)); if (empty($entities)) return $form; $entity = reset($entities); $source_phones = $entity->field_phone['und']; $source_phones[2] = $source_phones[1]; $source_phones[2]['value'] = 'test'; // ADD A THIRD VALUE FOR TESTING PURPOSES $phones = array(); $length = count($source_phones); // HACKING - TRYING TO SET VALUES THAT MAKE THE TEXTFIELD BEHAVE - NOT WORKING foreach ($source_phones as $key => $source_phone) { $phones[$key] = $field_phone_template; $phones[$key]['value']['#value'] = $source_phone['value']; $phones[$key]['#delta'] = $phones[$key]['#weight'] = $phones[$key]['value']['#delta'] = $phones[$key]['value']['#weight'] = $phones[$key]['_weight']['#default_value'] = $phones[$key]['_weight']['#value'] = $key; $phones[$key]['_weight']['#delta'] = $length + 1; $phones[$key]['value']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-value--' . ($length + 1); $phones[$key]['value']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][value]'; $phones[$key]['_weight']['#id'] = 'edit-line-item-fields-field-phone-und-' . $key . '-weight--' . ($length + 1); $phones[$key]['_weight']['#name'] = 'line_item_fields[field_phone][und][' . $key . '][weight]'; $phones[$key]['#id'] = 'edit-line-item-fields-field-phone-und-' . $key; } // THIS SUCCESSFULLY LOADS THE DATA FOR PRESENTATION, BUT DOESN'T BEHAVE PROPERLY ON "Add another item" if (!empty($phones)) { foreach ($phones as $key => $phone) { $field_phone[$key] = $phone; } $form['line_item_fields']['field_phone']['und']['#max_delta'] = $length + 1; // $form['line_item_fields']['field_phone']['und']['add_more']['#id'] = // 'edit-line-item-fields-field-phone-und-add-more--' . ($length + 1); $form['line_item_fields']['field_phone']['#id'] = 'edit-line-item-fields-field-phone--' . $length; } // =============================================== // THIS REMAINING PART WORKS $source_address = $entity->commerce_customer_address['und'][0]; $values['name_line'] = $source_address['name_line']; $values['organisation_name'] = $source_address['organisation_name']; $values['thoroughfare'] = $source_address['thoroughfare']; // Address 1 $values['premise'] = $source_address['premise'];// Address 2 $values['locality'] = $source_address['locality']; // City $values['administrative_area'] = $source_address['administrative_area']; // Province $values['postal_code'] = $source_address['postal_code'];// Postal Code // dpm($entity); // apply input data to input fields // $value = 'something'; // $form['line_item_fields']['field_designation']['und'][0]['email']['#value'] = $value; dpm($form); $form['line_item_fields']['#suffix'] = rconnection_get_debug_data(); return $form; }
HenrikBechmann

Align fields in created webforms

1 week ago

I am new to drupal, and currently i am creating a webpage in drupal from html . i have almost completed. I have created web form for "Contact us" form, after creation it is not in proper alignment. So, my form should be look like the picture shown as below.

So, right now it is like as below image.

So, please someone help me to get out of this issue.

Karthik

php.ini opcache path for multiple websites with shared code base

1 week ago

I have a D9 website set up already and I want to add another that shares the same code base. (This is on a shared hosting environment)

Below is an example my current php.ini settings for the opcache with 'MyWebSite1.com' as the initial website cache directory path. I want to have the two sites cached in different directories.

How do I specify the path in this php.ini set up for the second 'MyWebSite2.com' website? Or, does this cache directory contain generic php info that can be shared between multiple sites so that only one directory can be specified?

Thank you.

date.timezone = 'America/City' zend_extension=opcache.so; opcache.enable=1; opcache.memory_consumption=32; opcache.interned_strings_buffer=8; opcache.max_accelerated_files=3000; opcache.revalidate_freq=180; opcache.fast_shutdown=0; opcache.enable_cli=0; opcache.revalidate_path=0; opcache.validate_timestamps=2; opcache.max_file_size=0; opcache.file_cache=/AbsoluteDirectoryPath/sites/MyWebSite1.com/.opcache; opcache.file_cache_only=1;
corE

Couldn't avoid duplicates and merge rows on my views

1 week ago

I have a view of list of contents referenced in many others content types in my site. Lets talk about just 2 content types :
A content type called container is referenced in a content type position, so we say that the container has many positions.
Container position is a select list field in Position, for every item in this select list, there are some fields to fill.for example if I select 'on board' I have to fill the field 'date of loading', If I select 'in the shipper' I have to fill the field 'name of shipper'.
So in my view I want to display the list of containers with informations from the positions where they were: container;date of loading;port of loading; shipper.
When I created the view I get duplicated results for every container. I tried aggregation and distinct option, It not works, or it removes duplicates without merging the rows if use them both.



Update: My question is similar to this Views - adding relationship adds duplicate row for each relation

learner123

How to display entity reference field in User Profile Twig

1 week ago

I asked this over on the Drupal.org forum, but I thought I'd give it a try here too.

I am using an taxonomy entity reference field to display author names on our site. I added a 'published_name' field and referenced it to the Author taxonomy. What I'd like to do is make a custom user profile twig that shows that entity reference field value on the author's profile page, including it's link, so when the displayed name is clicked, it shows all the books connected to that author. I made two different profile types using the Profile Module. Everyone gets a Public Profile, and the authors get a second one just for their custom information. The Writer Profile (machine name writer_profile) is the one with the field 'field_published_name'.

On the writer's profile page, In the manage display of admin/config/people/profile-types/manage/writer_profile, I added the Published name field, I set it as Format: Label; Link to the referenced entity. The field does show, and work when clicked on the User page, but I can't control where, and how, it looks without using a twig. I want to customize when, where, and how it would be displayed on the page.

I have tried in the user.html.twig:

{% for item in items %} {{ item.content['#user'].field_published_name.value }} {% endfor %}

Also:

<article{{ attributes.addClass('profile') }}> {% if content %} {{- content.field_published_name -}} {% endif %} </article>

On admin/config/people/accounts/display I have it set to show the 'Public Profile profiles' and 'Writer Profile profiles' format as Rendered entity.

So far it just comes up empty while showing the rest of the user's info on their profile page.

TomP

Export translations of field labels

1 week ago

Drupal 7. I work on multi language site. I have a content type with entity translation fields. I've added translation to field labels and settings on my DEV copy of site and now I need to export and import it to Production.

Is there any module in Drupal 7, that helps me to export and import field labels/settings? Or maybe someone tell me, how to export values from "locales_source" and "locales_target" tables and import it to my Production database? Because I see only "lid" auto increment field in both tables.

Locales Source table

Locales Target table

dark_kz

How to use drush site-lists alias?

1 week ago

I several folders containing symlinks to my drupal sites. I'd like to use this folder structure to create an alias so I can run commands on each group of sites.

I'm trying to do what "drush @sites status" will do, but on a smaller subset.

I wrote the following based on the docs

// List the instances from the OU instances folder $full_path = "/opt/drupal/sites/instances"; if ($handle = opendir("$full_path")) { while (false !== ($file = readdir($handle))) { if(is_dir($full_path."/".$file)) { if ($file != '.' && $file != '..') $instances[] = $file; } } } // Turn them into aliases so we just have to type @instance foreach ($instances as $instance) { $site_list = []; // Look at each instance $site_paths = $full_path . "/" . $instance; if ($file_handle = opendir("$site_paths")) { // List out the folders in this instance while (false !== ($site_folder = readdir($file_handle))) { if(is_dir($site_paths."/".$site_folder)) { // If the folder represents a drupal site if ($site_folder != '.' && $site_folder != '..') // Add it to this instances list $site_list[] = '@' . $site_folder; } } } $aliases[$instance] = array( 'site-list' => $site_list, ); } print_r($aliases);

The cheeky print_r on the end shows my array as

[partnership] => Array ( [site-list] => Array ( [0] => @www.1.co.uk [1] => @www.2.org [2] => @www.3.org.uk [3] => @www.4.org [4] => @www.5.eu [5] => @www.6.net [6] => @www.7.com [7] => @www.8-ri-2020.eu [8] => @www.9.edu [9] => @www.10.ac.uk [10] => @www.11.org [11] => @www.12.ac.uk [12] => @www.13.co.uk [13] => @www.14.org.uk [14] => @www.15.ac.uk ) )

I've changed the names to protect the innocent, but they are valid aliases.

When I run "drush @partnership status" I get

drush @partnership status You are about to execute 'status' non-interactively (--yes forced) on all of the following targets: Continue? (y/n): y Invalid argument supplied for foreach() backend.inc:661

How do I get drush to actually run through this alias list telling me the status of each site?

Stuart Crouch

How can I change the default system message shown on form submission

1 week ago

I've created a business card request form as an EntityForm and am scratching my head trying to figure out where in the module i can find the line - ( " The submission has been saved " ) .

This message displays after every form submission/edit/save, and I would like to get rid of it but cant figure out where its coming from ! :)

Manny Adumbire

Receiving notifications when user edits a node?

1 week ago

Newbie here! I'm running a site on Drupal 7 (iloveqatar.net) and users have the ability to submit their own content (News, Events, etc...).

I'm facing a couple of issues.

1) When users submit new content that's in moderation to be approved, I don't get any notification. What's the best module to a) send emails to moderators / admins so they're aware there is content that needs to be approved and b) Display the notification on the site (like an unread message counter).

Right now I click on "Needs Review" on the admin bar on the top of the site every few hours just in case theres new content.

2) This one is the more problematic issue. When a user submits an event for example, and it's then approved, the user still has the ability to edit his/her post, which then creates a draft that needs to moderated and approved. However since it's creating a draft of an existing note, I'm not seeing it under the 'needs review' table. I actually have to go to that specific event and then edit it to approve the changes. Of course that's no good for me, because I can't go around checking every single post just in case there's an edit.

Does anyone know of a solution for this so that I can get notified and/or it shows up in 'needs review' ?

Please do let me know if I need to include any additional information to get help.

Thank you so much in advance!

amnesia

How to display custom fields of taxonomy in field twig

1 week ago

In my content type for Event, I have an entity reference called Speakers which refers to a taxonomy called Team Members. It's set to multiple so I can say which speakers belong to my event. On the event detail page, I want to list the speakers out with all of their fields.

I have a field hook called field-field-speakers.html which lists all of the speakers. I can't seem to get any of the fields within the taxonomy. (ex: item.content.field_job_title ). It doesn't display any content.

{% for item in items %} <div class="member"> <div class="name-box"> <div class="name"> {{ item.content }}</div> <div class="position">{{ item.content.field_job_title }}</div> </div> </div> {% endfor %}

How do I do this? I think the answer might be in a View but not sure how to map it dynamically based on which event I am in.

bb2j3z

Access field formatter settings in a field type plugin

1 week ago

How can I get the field formatter settings inside a field plugin? The field plugin extends FieldItemBase and the corresponding field formatter plugin extends FormatterBase.

If there is no direct way, maybe I could use the entity_display.repository service. But to use the getViewDisplay I need to know which view mode is used. I don't know either how to get the current view mode in the field plugin.

The field plugin is a computed field that makes a calculation depending on some variables. I wanted to set theses variables as the formatter settings. But maybe this is the wrong approach. Maybe it would be better to use module settings for this purpose?

Mike

How do you override the add or edit node for a particular content type

1 week ago

I want to format the editing or adding form for the article content type. i.e. node/add/article path and editing the same article.
I copied over the node-edit-form.html.twig template from core/modules/node/template and renamed it node-edit-form--article.html.twig.
I also tried node--article-edit-form.html.twig and some other flavors.
I can override the node.html.twig file by simply copying it to my themes template folder.
But since I couldn't get the edit file to work I also tried overriding the form alter function by adding this in my theme file.

use Drupal\Core\Form\FormStateInterface; function newsass_form_node_form_alter(&$form, FormStateInterface $form_state) { $form['#theme'] = ['node_edit_form']; }

This code is from here- How to override node add template for custom content type?

I added some text on top of the code, but I still can't get the article 'edit' or article 'add' page to display the text.

Drupal 8.6.1, and have debugging enabled. Full explanation of requirement: I have a user entity reference field in the article content type with a list of users that the article can be assigned to. For the most part they have an 'article' role. But if the person leaves, their role will be changed to 'Away'. The article can/will still be assigned to them but I need to indicate that they are no longer with the company or 'Away'. Within views entity reference I am able to re-write the user with the users role but this information doesn't get back to the entity reference field in the editing node. I thought of editing the article node and adding a hook to call the assigned users role..... Which I still need to figure out how to do. With debugging I tried suggested template page--node--add--article.html.twig but I still couldn't get the content revealed and yes I cleared cache. Using page level though doesn't allow granularity for each field.

QUESTION: By mytype is that the machine name of the entity reference field in the content type? I am also not quite understanding this function, where is the call to query the roles? I enabled kint and added this to the function.

kint($elements); die();

but get nothing returned. How do I check if this function is actually being called.
I tried something else also. I have users in the entity reference and in the entity reference views for users I added the roles, made them hidden and rewrote the users to include the roles. I works nicely in the views preview, but the roles detail doesn't get carried back to the content type add/edit pages.

Dupls

Change field value with hook_views_pre_render()

1 week ago

I'm using Views in 8.4.0 and attempting to change the output of a field value with hook_views_pre_render(). The default value of the field is a node ID. The intent is to replaced the value with a static string depending on a whether or not it's contained in a predefined array using in_array().

The aforementioned is relatively straightforward.

I begin by looping through the results:

for ($i = 0; $i < count($view->result); $i++) { if (isset($view->result[$i]->node_field_data_node__field_lesson_nid)) { $viewed = in_array($view->result[$i]->node_field_data_node__field_lesson_nid, $viewed) ? 'yes' : 'no'; // Replace the default Node ID value with $viewed. ... } }

The array $viewed contains a list of predefined node IDs. If the node ID exists in the array "yes" is output otherwise "no".

The problem is how to output the value for each row of results within the View object.

I tried the following at the above ellipsis:

$view->field['nid_2']->options['alter']['text'] = $viewed; $view->field['nid_2']->options['alter']['alter_text'] = TRUE;

"nid_2" is the token for node_field_data_node__field_lesson_nid.

The problem is this changes the field value for every row. The last row in the results determines the value. (The View also has multiple joins (relationships) which further compounds the complexity.)

So my dilemma is where to replace the value within each row of the $view->result.

bacteriaman

Is there a way to remove cache tags from a render array

1 week ago

When I turn on cache debugging, I see a lot of cache tags for render arrays that don’t make sense.

I don’t see an obvious way to remove these cache tags. For example, they don’t seem to appear in the $vars for the render array during a preprocess hook.

Are there ways to remove these cache tags?

miwayha

how to get all options values of simple hierarchical select in drupal $form?

1 week ago

i have writed this code to unset empty terms :

function shs_selective_form_alter(&$form, &$form_state, $form_id) { if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-projet-immobilier-page-1') { foreach ($form['field_r_t_tid']['#options'] as $tid => $term_name) { if (is_numeric($tid)) { $result_count = db_select('taxonomy_index', 'ti') ->fields('ti') ->condition('ti.tid', $tid, '=') ->execute() ->rowCount(); // Removing the option for tags with no-content if (!$result_count) { unset($form['field_r_t_tid']['#options'][$tid]); } } } } }

but is not worked, he show me this error : Undefined index : #options ... how can i resolve this error?

Salaktarus

Content type not responding to AJAX callback

1 week ago

I am using a ctools content type plugins to render a custom form that will have only one submit button.

The submitbutton will switch an eck entity field (boolean) from 0 to 1 and back (if pressed again, of course).

I have defined my ctools content type plugin, form (with ajax callback) and a submit handler

When i tested it with a hook_menu path, all was fine and it worked.

Since i have put it in a ctools content type, no luck.

Any help would be very much appreciated!

Ps: What would be the best place to put my database logic? The submit handler?

Thanks a million!

$plugin = array( 'single' => TRUE, 'title' => t('Project isClient'), 'description' => t('Project isClient AJAX plugin'), 'category' => t('Project'), 'render callback' => 'project_isclient_ajax', 'defaults' => array(), ); function project_isclient_ajax() { $pane = new stdClass(); $pane->title = t('Project isClient'); $pane->content = drupal_get_form('project_isclient_form'); return $pane; } function project_isclient_form($form, &$form_state) { return array( 'submit' => array( '#type' => 'submit', '#value' => t('Subscribe'), '#ajax' => array( 'callback' => 'project_isclient_ajax_submit', 'wrapper' => 'project-isclient-form', 'method' => 'replace', 'effect' => 'fade', ), ), ); } /** * Ajax callback function. */ function project_isclient_ajax_submit($form, $form_state) { // Dummy/dumb validation for demo purpose. return 'works!'; }

A little after posting this, i found AJAX calls in CTools Content Type Plugin? which states that ctools handles ajax forms differently. I checked using blocks, and this appears to be correct. In a block my callback works.

Guardian

Add class to field parent with a preprocess hook in a custom module?

1 week ago
Background:

I would like to alter the classes that are added to a rendered field in Drupal 9 in a custom module. I'm trying to use hook_preprocess_field and I'm not sure if this will work or if there is a better alternative.

based on: https://www.drupal.org/forum/support/module-development-and-code-questions/2017-03-31/add-class-to-field-in-drupal-8

I have the following: function my_module_preprocess_field__field_pricing_grid_items(&$vars) { foreach(array_keys($vars['items']) as $delta) { $vars['items'][$delta]['attributes']->setAttribute('class', 'my-class'); } }

This works for adding a class but I can't figure out how to add a class to the parent div.

Result <div class ="field__items"> <div class ="field__item CUSTOM-CLASS"></div> </div> Desired result: <div class ="field__items CUSTOM-CLASS"> <div class ="field__item></div> </div> Questions:
  1. How can I add a class to the parent div? Is that possible with this hook?
  2. Would an alternative approach of maybe overriding the field with a template in my module work? The theme template would be field--field-pricing-grid-items.html.twig Is there a way to override the theme with a module?
  3. If neither of these approaches make sense what would be a possible way of achieving this.
matts213

Querystring in Views ajax_view.js

1 week ago

I'm using Views 7.x-3.11 with Better Exposed Filters and Ajax auto-submit in a panels page, and running into some issues that seem to be stemming from code in Views/js/ajax_view.js. I want to make the exposed filters bookmarkable, and I also need to deep link to certain result sets. Because of this, I added some custom js to add the selected form parameters to the URL as the user selects them.

I also have a section that lists all the currently active terms, where a user can click to remove them. In order to update the results from here, I'm calling $('.view-my-view').trigger('RefreshView');.

By default, from here I can see that the ajax_path for submitting the form has been set to the URL with the query string, which doesn't work. From what I can tell, the native ajax behavior is trying to submit the serialized form data to an already-parameterized URL. To change this behavior, at line 38 of ajax_view.js I've changed var queryString = window.location.search || ''; to var queryString = '';

It's pretty apparent that this is going to cause issues with some sort of intended functionality, but I can't determine what that is. I'm afraid I'm losing sight of something bigger-picture here, or not aware of something about how Views handles ajax submission typically.

Can anyone provide an example of a situation where you'd need the original code? Or what the intended purposed of it is?

Edit: Follow-up question that's a little more practical - is there a way I can make an equivalent change in my custom js that would override the default code in ajax_view.js, so that I don't need to alter the module?

nkanderson
Checked
6 hours 3 minutes ago
most recent 30 from drupal.stackexchange.com
Subscribe to Drupal StackExchange feed