How to set value in form validate for later validation functions Problem

I'm adding the user register form onto the node create form with hook_form_alter.

The problem is the first step of account validation always fails because Drupal doesn't save Username to form_state['values']['name']. (I think because I'm combining two entity forms (user and node) and perhaps because it's not needed for the default entity node form?)

Either way I have 4 validation functions that run in $form['validate'];

0 (String, 18 characters ) node_form_validate | (Callback) node_form_validate();
1 (String, 39 characters ) commercecurrency_node_form_validate | (Callback) commercecurrency_job_advert_form_validate();
2 (String, 22 characters ) _editnode_validate | (Callback) editnode_validate();
3 (String, 26 characters ) user_account_form_validate | (Callback) user_account_form_validate();

I'm trying to set the value in _editnode_validate so $form_state['values']['name'] is set when user_account_form_validate runs.

However the following code although it changes the value in _editnode_validate, doesn't save the value for the other validation functions. How can I get it to store the new value?

function _editnode_validate ($form, $form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;

(Both _editnode_validate and user_account_form_validate are added in hook_form_alter, and the code for _editnode_validate is in the hook_form_alter module.)

Is the problem just that your not passing $form_state by reference in your _editnode_validate validation function?

// note the & before $form_state to pass by reference
function _editnode_validate ($form, &$form_state)

   $test_value = $form_state['input']['name'];
   $form_state['values']['name'] = $test_value;


Can you customize the User Edit page without editing the theme? Is there a way to customize what appears on the user profile edit page without editing the theme? I'd much rather use blocks or hooks to accomplish this task.

Is this possible?

You can use panels. It has a panel page for the 'user edit page' that you can edit, put blocks, views, etc.


Page to show submenu items I have this kind of menu set up in my Drupal 8 project.

Level 1 item A1
    Level 2 item A2
    Level 2 item B2
    Level 2 item P2
    Level 2 item Q2
Level 1 item B1
    Level 2 item D2
    Level 2 item E2
Level 1 item C1
    Level 2 item Z2
    Level 2 item X2

Is there any way to create a page containing all the submenu links on a page. The desired result would be:

Click on "A1" menu link
Display a page containing A2, B2, P2 and Q2 in a list(the direct children of A1)

I've tried setting this up using views, the problem with that is i don't find a way to filter based on the parent menu item. Only the type of the node and therefor it shows all my content.

Is it possible to use views to achieve this, or is there a better way?

I'm trying to solve the same problem and one part of a possible solution would be to assign every linked page (A2, B2, etc.) to taxonomy terms based on the menu structure. This way you can get a list of all items linked under A1. The problem is to bring it in the same order as the menu links...


Export themes from my site? Someone gave me access to a website of theres, and they want me to export the theme from one Drupal 7 install to another.
(I couldn't find any export links on the /admin/appearance page.)
How do I export a theme?

You will need to have access to the web servers folder structure. You will find the themes inside sites/all/themes, sites/default/themes, sites/YOURSITE/themes or profiles/YOURPROFILE/themes. Once copied to the other Drupal installation it can be enabled under admin/appearance. More on installing a Drupal theme can be found here.

It might be that the theme you are going to copy is a subtheme of another theme. In this case you need both themes. Look inside the THEMENAME.info in your theme and look for the line that starts with base theme =

If a base theme is defined there you need that as well on your target installation.


Is it possible to custom Event Date format? On the Drupal 7 Upcoming Event, I would like to show the Event Date with abbreviated "Day, Month date, Year - Time". However, There an option that I like, which is "Fri, Mar 28, 2014 @ 4:55pm", but it contained with the "@" symbol. Is there a way to custom this being "Fri, Mar 28, 2014 - 4:55pm"?

PS: I know there is a way to add new date type, by going to "Administration/Configuration/Regional and Language". But none of them work like the way I wanted.

You can add a new date/time format by going to Administration > Configuration > Regional and Language > Date and Time. In the upper right corner of the screen you see two tabs: Types & Formats. First go to Formats and add your desired date format there (according to PHP date formatting). In your case, this will probably be something like

D, M j, Y - g:i a

Next, you go to Types and create a new date type. You can assign your custom date format to this new date type.


How to trigger an email for a buyer or seller who has not performed any activity for 30 days or more? Is there any way to trigger an email for any buyer or seller who have not had any activity for 30 days or something like that.

Also
Sending reminders to users that haven't logged in for 30 days.

Unpublishing content after user has not logged in for 30 days.

Deactivate accounts after user has not logged in for 30 days.

Finally i got the answer here:
https://www.drupal.org/project/inactive_user

The inactive_user module provides Drupal administrators with a way to automatically manage inactive user accounts. This module has two goals: to help keep users coming back to your site by reminding them when they've been away for a configurable period of time, and to cleanup unused accounts.

And another possible solution is:
Using rules for more advanced functionality would involve something similar to the following

Create a new Rule Set that passes the User and (possibly) a Date argument

Add a Check a truth value condition that verifies something like [user:user-last-login-raw] + 2592000 < [user:date-in-tz] (2592000 is 30 days in seconds)

Add a Send a mail to a user action

Save that rule set and then do the following:

Create a new triggered rule for User has logged out event
Add a Schedule "your rule set" action and pass +30 days as the Scheduled evaluation date


How can we autocreate an organic group during registration How can I do this using the rules module?:
User registers (as profile type a) -> create organic group using field value from registration and make the user the manager/admin of the group

I have also the modules Profile 2 and Profile2 Registration Path.

Creating a group is really just creating a node.

Create a rule that reacts on "After saving a new user account".
Add Action: Create a new entity.

Set content type to: Group.

You can set the title of the node (the name of the group) to the new user's name or any value you want using available tokens.

Set the author of the node to the new user (it's usually called "account" in rules) and the new user will be the owner/manager of the group.


Can an identical profile and theme name cause conflict during installation? I recently purchased a theme to install it on an Aegir hosting environment, which is a multi-site installation system. Does identical profile and theme names cause conflict or errors in Drupal?

Yes.  Modules, themes, and profiles must have unique names.


How can I remove duplicate value? I have used custom code. I want to remove duplicate value using distinct, how can I do this? My code is like this.

$media_query = db_select('node','n');
    $media_query->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
    $media_query->fields('n',array('nid'));
    $media_query->fields('mtype',array('field_media_room_type_tid'));
    $media_query->condition('n.type','media_room_page','=');
    $media_query->condition('mtype.field_media_room_type_tid',$media_id,'=');
    $media_res = $media_query->execute();
    while($media_fetch = $media_res->fetchObject()){
     $media_year = '';
        if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
            $media_year = $media_node->field_year['und'][0]['value'];
        }
      echo'<pre>';print_r($media_year);
    }

Output like this:

2011

2011

2011

2011

2011

2011

2012

2012

2013

I want to remove duplicate values so how can I remove it?

You can try like

 $media_query = db_select('node','n')
         ->distinct()->innerJoin('field_data_field_media_room_type','mtype','mtype.entity_id = n.nid');
        ->fields('n',array('nid'));
        ->fields('mtype',array('field_media_room_type_tid'));
        ->condition('n.type','media_room_page','=');
        ->condition('mtype.field_media_room_type_tid',$media_id,'=');
        $media_res = $media_query->execute();
        while($media_fetch = $media_res->fetchObject()){
         $media_year = '';
            if(isset($media_node->field_year['und'][0]) && $media_node->field_year['und'][0] !=''){
                $media_year = $media_node->field_year['und'][0]['value'];
            }
          echo'<pre>';print_r($media_year);
        }

or

you can use Group By for that particular column.


Sorting entities in a view by a field in a 'sibling' entity At its most general, my question is how you can sort entities in a view by a field in a related entity. This is best illustrated with a lengthy example which is more specific, though still quite abstract. It describes sorting by 'sibling' or 'child' entities (depending on what you count the view as showing).

Suppose that you have entities in the following structure:

Entity A1 (of entity type A*) related to (colloquially, a 'child' of) entity U1 (of type U*)
Entity B1 (or type B*) is also a child of the same entity U1

Here is my particular example:

User P has 2 profile2 profiles, A and B

Now suppose you have a view of entities of type U* (in my example, a view of users) - i.e. when first creating the view, you chose U* (here, users) from the 'Show' menu. You've added relationships to A* and B* in this view, and made it show the name field of U* (here, 'User: name') and the fields of A*, filtered by a field in A*. Given our specific entities, the view would show:

U1
A1 field 1
A1 field 2

This means that though this is a view of U* entities in the 'i.e.' sense above, it could also be called a view of A* entities in the sense that if you'd added B* fields they'd show under a duplicate of the U* name. Given our specific entities, the view would show:

U1
A1 field 1
A1 field 2

U1
B1 field 1
B1 field 2

This makes my example either about 'child' or 'sibling' entities.

Sorting the view by a field of B* (e.g. B* field 1) doesn't work. Applied to this abstract example, my question is how to make it work.

As requested in comments, here is the SQL query and results for an instance of this example. The SQL:

SELECT users.name AS users_name, users.uid AS uid, profile_users.pid AS profile_users_pid, profile_users__field_data_field_weighting.field_weighting_value AS profile_users__field_data_field_weighting_field_weighting_va, 'profile2' AS field_data_field_do_you_plan_to_donate_a_ce_profile2_entity_, 'profile2' AS field_data_field_if_so_to_which_causes__profile2_entity_type, 'profile2' AS field_data_field_if_so_until_when__profile2_entity_type, 'profile2' AS field_data_field_would_you_like_to_give_any_profile2_entity_
FROM
{users} users
LEFT JOIN {profile} profile_users ON users.uid = profile_users.uid
LEFT JOIN {field_data_field_do_you_plan_to_donate_a_ce} profile_users__field_data_field_do_you_plan_to_donate_a_ce ON profile_users.pid = profile_users__field_data_field_do_you_plan_to_donate_a_ce.entity_id AND (profile_users__field_data_field_do_you_plan_to_donate_a_ce.entity_type = 'profile2' AND profile_users__field_data_field_do_you_plan_to_donate_a_ce.deleted = '0')
LEFT JOIN {field_data_field_weighting} profile_users__field_data_field_weighting ON profile_users.pid = profile_users__field_data_field_weighting.entity_id AND (profile_users__field_data_field_weighting.entity_type = 'profile2' AND profile_users__field_data_field_weighting.deleted = '0')
WHERE (( (profile_users__field_data_field_do_you_plan_to_donate_a_ce.field_do_you_plan_to_donate_a_ce_value IS NOT NULL ) ))
ORDER BY profile_users__field_data_field_weighting_field_weighting_va ASC

The results:

Tom Ash
Do you plan to donate a certain amount either until you retire or until you die?:
Everything over £14,000 (~$22,000), and at least 10% of income
Weighting:
NO RESULT, BECAUSE SHOWING DIFFERENT

Tom Ash
NO RESULT, BECAUSE SHOWING DIFFERENT PROFILE
Weighting:
432

My research so far (~3 hours): Googling; looking through dozens of StackExchange answers; searching the Views issue queue; as had no responses here yet, added a support request in the Views issue queue.

(1) you cannot do this simply by editing the view, but (2) you can do this with a custom module. I expand on (1) and (2) below.

(1) holds because there is no single ;-terminated SQL query which will do this. The reason is that when you have 2 profile2 profiles the data you're fetching is spread across 4 tables structured like this. As you can see from that, the 2 profile2 tables reside in separate tables, and you can't tell that they belong to the same user except by checking a 3rd table. SQL queries simply can't manage this.

(2) is possible because a custom module lets you run multiple lines of PHP, drawing on additional query to fetch the field you want to sort by. You want to do this in hook_views_pre_render. Here's a module I created to do something similar on an existing site I had: http://www.pastebucket.com/40183


How can I set the email sender name? below code is not working in our custom module.

$site_name = \Drupal::config('system.site')->get('name');
$site_mail = \Drupal::config('system.site')->get('mail');

$message['headers']['From'] = $site_name . ' <' . $site_mail . '>';
$message['headers']['Sender'] = $message['headers']['Return-Path'] = $site_mail;
$message['from'] = $site_name . ' <' . $site_mail . '>';

It gives the output like this :

 MailSender <MailSender> <email@example.com>

and I want the output like this :

MailSender <email@example.com>

How can I do this?

If you look at your code and the output you wrote, it come clearly out, that either:

$message['headers']['From'] = $site_name . ' <' . $site_mail . '>';
$message['from'] = $site_name . ' <' . $site_mail . '>';

is not working at all.

I would get rid of the unnecessary code first, and then trying to modify the working line.


Add extra obligatory fields when editing a node as anonymous user I need a way to either add extra fields or make two fields obligatory when an anonymous user is editing a node. I'll explain:
There is a node type in my site that can be freely edited, modifications are saved as new revisions. To know who edited a node i want to add a mail field and other extra fields that require other info from the anonymous user but these fields don't need to be obgligatory when the nodes are edited by registered users.

I was thinking about using the module suggested in this discussion: How can anonymous users be allowed to post while still maintaining content integrity?
but i require that the mail entered from the user is saved inside the node and also i require an extra field other than the mail.

Is there any way to achieve that?

You could use a the hook_form_alter to get the desired function:

function mymodule_form_alter(&$form, &$form_state) {
  if($form['type']['#value'] == 'DESIRED_CONTENT_TYPE') {
    if( user_is_anonymous() ){
      //Fields are required for anonymous users
      $form['field_ABC'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
      $form['field_DEF'][LANGUAGE_NONE]['0']['value']['#required'] = TRUE;
    }
    else{
      //Hide fields for logged in users
      $form['field_ABC']['#access'] = FALSE;
      $form['field_DEF']['#access'] = FALSE;
    }
  }
}


Fatal error: Unsupported operand types in form.inc I'm getting the following error message:

  Fatal error: Unsupported operand types in /var/www/public_html/domain.com/includes/form.inc on line 1079

It seems to be because the following code for an admin menu.

function MY_MODULE_admin_menu() {
  $menu_items = db_query("SELECT * FROM my_module")->fetchAll();
  $header = array('Template ID', 'Name', 'Type', 'Template');
  $rows = array();
  if (!empty($menu_items)) {
    foreach ($menu_items as $menu_item) {
      $rows[] = array($menu_item->tid, $menu_item->name, $menu_item->type, $menu_item->template);
    }
  }
  return theme_table(array(
    "header" => $header,
    "rows" => $rows,
    "attributes" => array(),
    "sticky" => true,
    "caption" => "",
    "colgroups" => array(),
    "empty" => t("Table has no rows"),
      )
  );
}

What's causing this? As far as I can tell, this is how it is supposed to look for Drupal 7.

Duplicate of this question:

Db_Query Fatal error: Unsupported operand types

It turns out that I was setting my page callback to a drupal_get_form with no form present.

I changed my hook_menu to:

function MY_MODULE_menu() {
  $items = array();

  $items['admin/structure/module'] = array(
    'title' => 'description of module',
    'description' => 'Configure settings for module',
    'page callback' => 'MY_MODULE_admin_menu',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

And it worked fine.


User Profile Edit workflow any module available, to implement a work flow when user is trying edit the user profile fileds (custom fields). Following is my use case

1) User can edit the profile field , but admin approval is required to update it
2) Admin can either approve or reject the profile update
3) If it is approved need to change the user role , and need to send an email to the user
4) If rejected , need to trigger an email again

Thanks

There is need to work with Rules module make such action, "send email", "change role".

The workbench module is very popular, but is for Drupal 7 only. can be achieved good results using the revisioning module, which has a release for Drupal 6.


What is the correct way to exclude certain CSS files for anonymous, but include for authenticated users? We have a subtheme, mytheme that is based off of the classy base theme. We have set Aggregate CSS Files = true and when the pages load we end up with many aggregated CSS files.

One issue is that we don't need all the CSS for anonymous users, only authenticated users since most of them are for logged in users.

How would I only add the following CSS for only authenticated users, but not anonymous users using the mytheme.libraries.yml?

Goal:

We do not want to override anything in those libraries, but rather remove them all together from render based on if the user is authenticated or not.

CSS files included in local development:

<styles media="all">
@import url("/core/themes/classy/css/components/progress.css?pe4tq3");
@import url("/core/themes/classy/css/components/dialog.css?pe4tq3");
@import url("/core/themes/classy/css/components/action-links.css?pe4tq3");
@import url("/core/themes/classy/css/components/button.css?pe4tq3");
@import url("/core/themes/classy/css/components/collapse-processed.css?pe4tq3");
@import url("/core/themes/classy/css/components/container-inline.css?pe4tq3");
@import url("/core/themes/classy/css/components/details.css?pe4tq3");
@import url("/core/themes/classy/css/components/exposed-filters.css?pe4tq3");
@import url("/core/themes/classy/css/components/field.css?pe4tq3");
@import url("/core/themes/classy/css/components/form.css?pe4tq3");
@import url("/core/themes/classy/css/components/icons.css?pe4tq3");
@import url("/core/themes/classy/css/components/inline-form.css?pe4tq3");
@import url("/core/themes/classy/css/components/item-list.css?pe4tq3");
@import url("/core/themes/classy/css/components/link.css?pe4tq3");
@import url("/core/themes/classy/css/components/links.css?pe4tq3");
@import url("/core/themes/classy/css/components/more-link.css?pe4tq3");
@import url("/core/themes/classy/css/components/pager.css?pe4tq3");
@import url("/core/themes/classy/css/components/tabledrag.css?pe4tq3");
@import url("/core/themes/classy/css/components/tableselect.css?pe4tq3");
@import url("/core/themes/classy/css/components/tablesort.css?pe4tq3");
@import url("/core/themes/classy/css/components/textarea.css?pe4tq3");
@import url("/core/themes/classy/css/components/ui-dialog.css?pe4tq3");
@import url("/core/themes/classy/css/components/messages.css?pe4tq3");
</styles>

We initially thought to do the following in the mytheme.info.yml file, but that would mean we have to exclude every single CSS manually (line by line).

name: 'mytheme'
type: theme
base theme: classy
package: custom
core: 8.x
libraries:
  - mytheme/library1
stylesheets-remove:
  - core/assets/vendor/normalize-css/normalize.css

You should use hook_library_info_alter.

In which, you check is the user is logged in, or the logged in user roles, then simply unset the CSS files you don't want.


Publisher and Editor only without publishing rights role possible? I want to have 2 user roles in the site:
one that can create content but not being able to publish
and the other just a supervisor that can (aprove-publish)

What you want is a workflow, for example "Draft", "Requires Review" and "Published". The Editor can only take content to "requires review" while the publisher has permissions to change the workflow state to Published which is then visible to all users on the site.

http://drupal.org/project/workflow

If you want to get really fancy you could use Rules to automatically email the publisher when content goes into "requires review" so the Publisher gets a notification. or you could setup a view for them...


Drupal 7 change default user login functionality I want to change the default login functionality to look at a web service and if true log in else do not log in.

I have tried to use in hook_form_alter

 $form['#submit'] = 'user_change_login_submit';
  $form['actions']['submit']['#submit'][]= 'user_change_login_submit';

But it doesn't call this function.

I had a similar functionality in a project a while ago and I solved it by adding a validation handler and doing the check in that.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Replace the drupal authenticate function is it's used as validation.
  if (isset($form['#validate']) && is_array($form['#validate']) && ($key = array_search('user_login_authenticate_validate', $form['#validate']))) {
    $form['#validate'][$key] = 'mymodule_login_authenticate_validate';
  }
}

function mymodule_login_authenticate_validate($form, &$form_state) {
  // Set
  $account = mymodule_authenticate($form_state);
  if ($account) {
    $form_state['uid'] = $account->uid;
  }
}

function mymodule_authenticate($form_state) {
  // Your magic code here
  // In my project I either created a new user or updated an existing user and set $account as that.

  // And if everything went well in your code, finalize login and return account
  user_login_finalize($form_state['values']);
  return $account;
}


Send Bulk emails as bcc in Drupal I am using Drupal 7. I have used Views Bulk Operations (VBO) module  to send an email, which is working fine.
Now Problem is that email is going as TO , all other user are able to see other emails id.

I want to send as Blind carbon copy (bcc). Can anybody tell, how we can do this?

Thanks

Simply you can do this by using Blind Carbon Copy module.

  The BCC module injects a BCC header in all e-mails sent by Drupal,
  which allows you to receive copies of all e-mails sent by your
  website.


Drupal 7, login, "form_build_id" not used? I write some functional tests for my website.
I have this test :

go to login page
post username/pass/form_build_id
check if the user is connected

In the test script, my form-build-id is "hardcoded". So, I run the connection test severals times and...The user connects each run (whereas the form-build-id does not change)

I don't understand, why the form-build-id is ignored ?
I check with my web browser, each time I refreshed my page, the form generate a new form-build-id.

As drupal_prepare_form() notes:

  The form_build_id is used as key to cache a particular build of the
  form. For multi-step forms, this allows the user to go back to an
  earlier build, make changes, and re-submit.

More than anything else, form_build_id is for maintaining the form state through page requests. As you can see in some of the core processing functions (e.g. drupal_build_form(), drupal_rebuild_form(), & drupal_process_form()), form_build_id isn't required for form processing.

In some instances (e.g. multi-step forms) breaking the form_build_id would break the behavior of the form since there is previous data to retrieve, but for the login form there's no state needed to be preserved.


How to import Term reference (autocomplete term widget) inside field collection with Feeds & feeds tamper I would like to be able to import content from CSV using Feed.
My content type are like this :
-Titre

-Field Collection :

--Name (simple text)

--Term (Term reference of type Autocomplete term widget (tagging)

For begin able to import field collection i have applied the #16 patch https://drupal.org/node/1063434#comment-5217400

Everything is working fine exept the insert of my Term field in my fieldcollection because is it of type Autocomplete term widget and if its a new term.
I want to keep this type of widget because i want to be able to create new term if they doesnt exist already.
I confirm that if i enter a existing term value for my Term field in my csv, my term is succesfuly added.

I am using :

Feeds : 7.x-2.0-alpha8+7-dev

Feeds Tamper : 7.x-1.0-beta3+56-dev

Field collection : 7.x-1.0-beta5

I dont know what i have missed... i am lost and blocked on this bug since 2 weeks.

I hope someone will help me,

Best regards

Jérôme

A couple of things.

You are using a very old patch. In my implementation I am using the one in #102 (I see its now up to #119)
https://drupal.org/node/1063434#comment-7395840
You need to tell feeds that it is ok to create new terms for you. Once you've added the target in Node processor > mapping for the term reference you can change it's target configuration (the cog icon). There is a checkbox there 'Auto create'

[edit] Please use the new patch in #121 https://drupal.org/node/1063434#comment-7792223 which corrects your issue.


Hiding a field title label of a field collections field? I have created several fields using the field collection module, but I cannot hide one of the field labels (within a collection). I've tried it in the UI and I've tried hiding it programmatically with hook_form_alter, but it continues to be displayed.

Is their a 'trick' to hiding the field labels created by this module? Thanks.

After our discussion, these are the steps to clear the labels from a published node field collection field.

Head to Structure > Field Collections > Manage Display (For your collection)
Under the label column, make sure all select boxes are set to "Hidden".
Next, head to Structure > Content Types > Your Content Type > Manage Display (For your collection)
Same as before, Under the label column, make sure all select boxes are set to "Hidden".

This wont hide the labels in the admin node/add/yourcontenttype page, but when you save the node, and look at the published page, the labels will be gone.

To remove the edit, delete and add links, Structure > Content Types > Your Content Type > Manage Display and click the settings icon on your field collection field. Then simply delete the edit, delete and add text from the text fields. Click update. Then save the content type.


Commerce - Theme Add-to-Cart form on Product Display page I have a Drupal Commerce project setup on top of D7-22. I've overridden the template file for my product display (node--product-display.tpl.php), and have managed to render the product fields, as well as the Add-to-cart form with all of the attributes. I know that <?php print render($content)?> will actually render the <form> for the attributes and Add-to-Cart button, but I would like to customize the HTML layout of the form and add some other elements to it. For example:

I'd like to position the Add to Wishlist button next to the Add to Cart button
I'd like to add some HTML next to one of the attribute fields that is rendered (the Size select box).

Using the Devel module, I was able to pick up fields like product:commerce_price and product:sku, but none of the attributes or buttons within the actual <form>. I'm currently using jQuery to inject HTML into the form...but it's a hack am not all that comfortable with pushing into production.

Is there any way in my tpl.php file to print out the form attributes, quantity textbox and buttons individually?

Cheers!

Here's a good start on your first form alter for add to cart:

function MODULENAME_form_alter(&$form, &$form_state, $form_id){
  // Add to cart form overrides
  if(substr($form_id, 0, 30) == 'commerce_cart_add_to_cart_form'){
    kpr($form);
  }
}


How do I display an image using the Dynamic Background module? I have been struggling to get the Dynamic Background module working for users' profiles. The profiles are displayed in a panel.

I enabled the Panel and User sub-module and after hours of trial and error I found a CSS combination that seems to work: #page #main-wrapper.

So the image displays as a background. But if I go to /user/[uid]/backgrounds to enable a background image for that user, it works but the image displays for ALL users, even when the other users have not enabled a background image.

I am at a loss because I thought that everything after user/[uid] only affected that user.

Any idea what I am doing wrong?

Make sure you also completed the required configuration steps as described in the Readme.txt of this module. I.e.:

Enable the modules/extensions that you want to use and go to the administration interface at /admin/config/user-interface/backgrounds/settings. Start by filling out the form and remember to fill out the CSS behaviour section. Then go into the configuration tab for each module/extension that you have enabled and as a minimum filling out the CSS behaviour fields.
Go to /admin/config/user-interface/backgrounds and select some images to upload after pressing "Save configuration" the form will change and allow you to select a default image. If you have enabled some of the extensions go to their location and select one of the uploaded images. See the extension descriptions above for information on where to select images for each extension.


how can I get a list of all of the permissions a user has? if I have the current user object, how can i get a list of all of the permissions he has in drupal 8 custom module ?  I dont want to check for one particular permission which would be $current_user->hasPermission("permission_name").

I want to get the entire list of his permissions.

thanks

Can you try the following snippet:

$user = \Drupal::currentUser();
$user_roles = $user->getRoles();
$roles_permissions = user_role_permissions($user_roles);

This will give you permissions grouped by roles.
But most likely you want them in one array.

Therefore you can use this

$final_array = array();
foreach ($roles_permissions as $role_key => $permissions) {
  foreach ($permissions as $permission) {
    $final_array[] = $permission;
  }
}

In case you want to load different user than the currently logged-in user, you can use

$some_user = \Drupal\user\Entity\User::load(123);

Where 123 stands for the user id.
For more information:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3Aload/8.2.x

Best regards,

Oleg


date_popup element not working when the form is rendered with ajax How to attach javascripts to form rendered with ajax?

In particular, I have problem with popup calendars in my form. They are not showing, when my form is rendered with ajax.

I am rendering form with javascript as follows:

$.get('/event-form', {}, function(data) {
$('#event-popup-container').html(data);

This code calls ajax callback "/event-form". returned variable 'data' containes my form. This form is displayed on web page in HTML element $('#event-popup-container'). It works OK, just date_popup elements in form don't show popup calendars. Propably I  have to attach some javascripts somehow, when the form is not loaded with page load, but with ajax call. But I have no clue how.

I have such a code in my menu callback of path '/event-form':

<?php
  //...
  $event_form = drupal_get_form('ef_event__form', $event_id, NULL);
  $output .= drupal_render($event_form);
  drupal_json_output($output);
?>

Can anybody help, how to make work all needed javascripts, when the form is loaded with ajax?

The problem is that you are not using any of AJAX helpers provided by Drupal. When you are using Form API AJAX, for example, all behaviors are re-initialised and functionalities like calendar added to new elements.

If you are not using Drupal-provided AJAX functionality, you need to manually call all behaviors with a proper context after your request is finished and DOM tree updated, probably by calling

Drupal.attachBehaviors(element)

on added DOM element.


How to hide user picture based on the value of a field in their profile This last bug is the only thing between be and launching this site.  Please help!

I have a field called publish photo? that is a checkbox in the user's profile.  For users with this box unchecked, I would like to hide the user picture for users that are not logged in. I would like it to be hidden everywhere, in a display suite view and in the views view.  I had the following in my template.php, which I could have sworn was working, back before I added on display suite, but it seems not to be working now.

function MYMODULE_preprocess_user_picture(&$variables) {
    if ((!isset($variables['account']->field_user_publish_photo) || $variables['account']->field_user_publish_photo[LANGUAGE_NONE][0]['value'] == '0') && $variables['logged_in'] != 1) { // hide user photo when Publish photo is turned off
        $variables['user_picture'] = '';
    }
}

What is the proper way to do this?

template_preprocess_user_picture seems to be fair enough approach to me, the hook should be able to unset profile picture from any instance including views etc.

Only thing I doubt could go wrong in your code is conditional unsetting of images. To make sure could you comment out the condition

function MYMODULE_preprocess_user_picture(&$variables) {
        $variables['user_picture'] = '';
}

If that unset your field than problem can be narrowed to make the condition working.

Probable problem with your condition
Can you check if you are getting fields in $variables['account'] object$variables['account'], if not you might need to object the user account and check the field conditions

$uid = $variables['account']->uid;
$account = user_load($uid);
function MYMODULE_preprocess_user_picture(&$variables) {
  if ((!isset($account->field_user_publish_photo) || $account->field_user_publish_photo[LANGUAGE_NONE][0]['value'] == '0') && $variables['logged_in'] != 1) { // hide user photo when Publish photo is turned off
      $variables['user_picture'] = '';
  }
}


How to escape single quote from a token to use it in SQL query? Working on Drupal 7.54

I am using a custom PHP/SQL Rules to synchronize Drupal field values with an external database.

I am trying to export a text field value but sometimes I have single quotes in these values.

Consequently, when I try to use a field token in my SQL query, it fails because of this single quote that is not escaped.

I have read a few things about replacing strings and escaping quotes but I did not manage to get my query working (replace? str_replace? addslashes? htmlspecialchars? decode_entities?...).

Here is an example :

Let's say I have a Drupal field called "Text-Drupal" in a content type A.

Each time a content of type A is updated, I need to export the Text-Drupal value in an external database in the column text_database

The little code :

db_set_active('database_local');
db_query("UPDATE table
SET text_database=NULLIF('[node:field-text-drupal]','')
WHERE title=[node:title]");
db_set_active();

This code works fine with any text without special characters but each time I have a single quote, it fails (and I guess it would be the same with double quotes).

I am quite sure this is something really simple for experienced users so I hope someone could point me to the right direction. Thanks.

Disclaimer: you shouldn't be using the PHP filter module, ever, it's very bad practice and can open your site up to security holes. Adding a custom rules action is very easy and should always be the preferred implementation method for something like this.

As a technical exercise, though, something like this might work:

$text = <<<EOF
[node:field-text-drupal]
EOF;

$title = <<<EOF
[node:title]
EOF;

$args = [':text' => $text, ':title' => $title];
$sql = "UPDATE table SET text_database = NULLIF(:text, '') WHERE title = :title";
db_query($sql, $args);


Can I control the weight of a library loaded through a theme preprocess function? I have a base theme that loads several libraries, some through the libraries.yml file and some loaded conditionally in a preprocess function. I also have a base theme with its own library loaded through libraries.yml.

This is the order they are loading in:

Libraries loaded in base theme's libraries.yml
Libraries loaded in sub theme's libraries.yml
Libraries loaded in base theme's preprocess function

This is a problem because I need to override some CSS from the libraries loaded in the base theme's preprocess function in my subtheme. I want it to load like this:

Libraries loaded in base theme's libraries.yml
Libraries loaded in base theme's preprocess function
Libraries loaded in sub theme's libraries.yml

They are loading in that order regardless of the CSS weights defined in the libraries file (base, theme etc.).

Is there anything I can do about this? This is the relevant code from the base theme, used in hook_preprocess_html().

  if (\Drupal::moduleHandler()->moduleExists('module')) {
    $variables['#attached']['library'][] = 'basetheme/library';
  }

Will libraries loaded through a preprocess function always load later than the libraries loaded through libraries.yml? Are there any resources that explain this? And as an aside, where would libraries loaded through twig go?

Can you define your subtheme's library as extending or overriding your base theme's library. You'd have to do that in your subtheme's .info.yml. I think that should work. I think if you went this route you would just have a .css file in your subtheme that entends -- gets added whenever -- your basetheme's library is loaded. In this case you're override wouldn't be a "library" in your subtheme. Drupal should be smart enough to load your css file whenever the basetheme's library is loaded.


Views aggregation summary I am creating a stats page for a football (american) team in Drupal 7 and I am having issues summarizing the data.  I have the following fields aggregated in a views table. Each is a summary of the individual players for each game.

Game 1 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc

Game 2 , Passing Yards, Long Pass, Rushing Yards, Long Rush, etc

I want to print a summary line at the bottom that totals up the season.

I have tried the views_calc module, but I would rather print the summary as one line instead of a separate line for the sum and max fields.

Any help would be greatly appreciated

Late but might be useful for someone, you can use views_summarize module.
Note: If you want to take export of your views using views_data_export module than views_summarize will create issues.


Paragraph's fields value loaded in a custom controller are in the default language instead of the current language I made a custom controller that load a paragraph field from a node and then render some part in a template. The paragraph field field_title and field_description are translatable.
The translation works fine on the admin side. I followed https://www.drupal.org/docs/8/modules/paragraphs/multilingual-paragraphs-configuration and I can see the content is translated from the admin. But my controller only loads the default language value instead of the current language.
<?php

/**
 * @file
 * Contains \Drupal\MyModule\Controller\MyModuleController.
 */

namespace Drupal\MyModule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class MyModuleController extends ControllerBase {

    /**
     * Controller load the game
     *
     * @return \Drupal\MyModule\Controller\RedirectResponse
     */
    public function gameView() {

        $nid = 1;

        // Load the game
        $game = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

        $stages = [];

        // Get all the stages of the game
        $paragraph_field_items = $game->get('field_stages')->getValue();
        if (!$paragraph_field_items) {
            throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('This game has no level');
        }

        // Get storage for paragraph
        $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
        // Collect paragraph field's ids.
        $ids = array_column($paragraph_field_items, 'target_id');
        // Load all paragraph objects.
        $paragraphs_objects = $paragraph_storage->loadMultiple($ids);

        /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
        foreach ($paragraphs_objects as $paragraph) {
          // Get field from the paragraph.

          $description = [
              '#type' => 'processed_text',
              '#text' => $paragraph->get('field_description')->value,
              '#format' => 'basic_html',
          ];

          $stages [] = [
              'title' => $paragraph->get('field_title')->value,
              'image' => $paragraph->get('field_image'),
              'description' => $description,
              'east_lv95' => $paragraph->get('field_east_lv95')->value,
              'north_lv95' => $paragraph->get('field_north_lv95')->value,
          ];
        }

        return [
            '#theme' => 'game_map',
            '#party' => $party,
            '#stages' => $stages,
            '#game' => $game,
        ];
    }

Based on the comments I changed $game->get('field_stages')->getValue(); for $game->get('field_stages')->referencedEntities();. This allow me to greatly simply a part of the code.
To load the correct language I added $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph); inside the loop. Using getTranslationFromContext on the $game didn't works for the paragraph.
I'm not 100% satisfied as I feel translation should be loaded directly when all the fields are loaded with referencedEntities(). But it works and perhaps caching do some magic behind the scene.
This answer helped a lot https://drupal.stackexchange.com/a/269493/1761
// Load the game
$game = \Drupal::entityTypeManager()->getStorage('node')->load($gameID);

$stages = [];

// Get all the stage of the game
$paragraph_field_items = $game->get('field_stages')->referencedEntities();

if (!$paragraph_field_items) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('This game has no level');
}

/** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
foreach ($paragraph_field_items as $paragraph) {

  // Get the translation
  $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph);

  $description = [
      '#type' => 'processed_text',
      '#text' => $paragraph->get('field_description')->value,
      '#format' => 'basic_html',
  ];

  $stages [] = [
      'title' => $paragraph->get('field_title')->value,
      'image' => $paragraph->get('field_image'),
      'description' => $description,
      'east_lv95' => $paragraph->get('field_east_lv95')->value,
      'north_lv95' => $paragraph->get('field_north_lv95')->value,
  ];
}


basic question: fast mobile site with omega I would like to propose our company to make our site responsive. I thought to use the Omega theme as a basis. But one question before I dig deeper:

I would like to have a fast mobile version of the site that does not load all blocks and that just loads a few images and these ones in a small resolution.

Can I do this with Omega? Which other modules do I need?

Adaptive Image is great for loading a smaller version of the images on smaller devices. It determines breakpoints, or you can set them, and saves an image into different sizes. Then automatically loads smaller images on smaller screen sizes.

For hiding content, you need to decide if you want the website to be adaptive or responsive. If you are hiding block regions on a tablet view (<768px), and someone who had their window size reduced makes their browser window full screen on a desktop, are they suddenly going to be missing blocks and regions?

I tend to just use CSS media queries, and re-arrange the content on smaller devices, and If I really have to, then hide content with display:none when the browser window, or device screen size gets reduced to a certain width.


How to create page and restrict it to authenticated users? I'm using the empty_page module to create "myhome" page and show blocks with a user's own content. That page throws an error for authenticated users.

How can I create an empty page in code and throw a 403 error when a visitors tries to access it?

You should try the Frontpage module - it allows you to set different home pages for authenticated and unauthenticated users.


Give user empty form on form validation error I'm using braintree.js with a custom form.  For those not familiar, braintree.js does client side encryption of the form fields before submission to the server.  On my end I get a bunch of gibberish (this is expected).  If a form validation error occurs, I want the form displayed again alerting the user of the error but I don't want any of the fields pre-populated because the pre-populated values are now the client side encrypted gibberish.  Is there a method of doing this in the _validate function?

I was able to unset the value from within the form validation function. In my case the element is named foo and it only validates if it's set to bar:

function mymodule_myform_validate($form, &$form_state) {
  if ($form_state['input']['foo'] != 'bar') {
    unset($form_state['complete form']['foo']['#value']);
    form_error($form['foo'], 'foo is not equal to bar');
  }
}

If the user enters anything but bar in foo, we set a form error and they presented with the form again without anything in the foo field.

I'm not sure how/if the form state array is affected by, for example, the i18n or locale modules, but this should get you started.


Cannot create users as administrator. Users can register by themselves but I can't add users (site exported directly from Drupal Gardens) I have a weird problem with my user registration in 2 of my sites. When I go to the "Add User" link under "People" menu, I fill in the information of the user and press the "Sign Up" button. The page refreshes, there is no error message or a confirmation message that the user has been added and the user is not added. I have checked the error messages in the "Reports" section and no entry is created there either.

When I turn on the user registration from "Configuration - Account Settings" a user can create a new account and I can edit the account as admin but I still can't create new user accounts.

Some extra information:

The site that I created is a direct export from Drupal Gardens. I did not mess with any code. It's pretty clean, direct export.

Any ideas on how to troubleshoot this and find out what is causing this strange issue?

Edit: for the time being I use the workaround to manually register through the regular user registration form and then disable the manual user registration and edit the users as admin but I'd prefer the normal functionality for obvious reasons.

I had the same problem. However, once I disabled three Drupal Gardens custom modules, I was able to add users. The modules are:

Gardens Features
Gardens Feedback
Gardens Required Features


Drush out of memory when php memory limit is 1024M on my dedicate server. (CentOS) This happened when I restarted Apache because my site was down. Normally restarting Apache or other service doesn't break Drush, but today it happened.

I'm sure on my server my php.ini has memory limit set to 1024M, this is my own dedicate server, and the Drupal installation runs well, I check the status report on Drupal (admin/reports/status), the PHP memory limit is set to 1024M.

This happened on my Drupal sites on my server.

When I...

[root: sites]# drush st

I got

Drush command terminated abnormally due to an unrecoverable error.       [error]
Error: Out of memory (allocated 10485760) (tried to allocate 122880
bytes) in /home/mywebsite/public_html/modules/system/system.module, line 1336

I also tried...

[root: sites]#  php -i | grep memory_limit

And I got

memory_limit 1024M

Is there anyone has some ideas?

My Server:

CENTOS 5.9 x86_64
WHM 11.36.0 (build 14)
PHP 5.2.17
Drush 5.8

I've tried drush status --debug and it gave me :

  Bootstrap to phase 0. [0 sec, 3.02 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drush() [0.01
  sec, 3.23 MB] [bootstrap] Cache HIT cid:
  5.8-commandfiles-0-15880291c3f5c759ee66bf106fd77cbd [0.01 sec, 3.24 MB]        [debug] Bootstrap to phase 0. [0.04 sec, 7.43 MB]
  [bootstrap] Drush bootstrap phase : _drush_bootstrap_drupal_root()
  [0.05 sec, 7.49 MB]                [bootstrap] Drush command
  terminated abnormally due to an unrecoverable error.
  [error] Error: Out of memory (allocated 10485760) (tried to allocate
  122880 bytes) in
  /home/mywebsite/public_html/modules/system/system.module, line 1336 [0.06
  sec, 9.28 MB]

Your particular setup might be one that (deliberately) has 2 php.ini files:

for Apache, e.g. on your server at: /etc/php5/apache2/php.ini (or similar path depending on your distro)
for command line (i.e. for drush) e.g. on your server at: /etc/php5/cli/php.ini (or similar path depending on your distro)

(I believe that this is perfectly normal kind of setup to have 2 files, I have this myself.)

You need to ensure that memory_limit is 1024M is set for /etc/php5/cli/php.ini(or similar path depending on your distro) php executed in the command line/terminal/console i.e. drush. You could also try memory_limit is -1 which allows the server to allocate as much memory as is available.


db_affected_rows() return "1" when the query is wrong I have a query like UPDATE user SET creator = 'creator'". The "user" table has not the "creator" column, so db_affected_rows() shoud return −1, not 1.

Why?

Update: mysql_affected_rows() returns -1 for this query. I created a "creator" column (unique); after I update the user table, I get the error "User warning: Duplicate entry," but db_affected_rows() still returns 1.

Edit:
db_affected_rows() returns an unexpected value because watchdog is turned on. I watched to see if there was another query after the one I ran and before my db_affected_rows() call, and sure enough:

  INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (1, 'php', '%message in %file on line %line.', 'a:4:{s:6:\"%error\";s:12:\"user warning\";s:8:\"%message\";s:104:\"Unknown column 'name2' in 'field list'\nquery: UPDATE users SET name2 = 'a'\"; [...]

So, db_affected_rows() is returning 1 because watchdog is logging an error. Thus, the proper way to see if a query had an error or not -- and count the rows affected if it was successful -- is:

$result = db_query("UPDATE users SET name2 = 'a'");
if ($result) {
  printf("Records affected: %d\n", db_affected_rows());
}
else {
  print "Query not successful";
}

Hope this helps!

Original answer for posterity:

I'd have to see the code around your query. Try running this:

<?php
function db_affected_rows() {
  global $link;
  return mysql_affected_rows($link);
}

$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('d6.devl');

/* this should return the correct numbers of deleted records */
mysql_query("UPDATE user SET creator = 'creator'");
printf("Records affected: %d\n", mysql_affected_rows());

printf("Records affected: %d\n", db_affected_rows());

I did and it worked alright:

  $ php -f test.php

  Records affected: -1

  Records affected: -1


Load a view with parameters I got a question regarding the loading of a view within a preprocess function of Drupal 8.

The only working solution I found is this one here:

$_block_level_1 = \Drupal::entityManager()->getStorage('block')->load('views_block__myview_ov_block_1');

So by using the entity manager.

The view is expecting parameters. How do I send them?

If you prepare a render element of the view

$variables['view_block_1'] = [
  '#type' => 'view',
  '#name' => $name,
  '#display_id' => $display_id,
  '#arguments' => $args,
];

you can then render this view in twig:

{{ view_block_1 }}


Site UUID in source storage does not match the target storage When I run drush cim -y on my staging instance of my site I get the following error:

  Drupal\Core\Config\ConfigImporterException: There were errors
  validating the config synchronization. in Drupal\Core\Config\ConfigImporter->validate() (line 728 of /var/www/xeno/docroot/core/lib/Drupal/Core/Config/ConfigImporter.php).
  The import failed due for the following reasons: Site UUID in source storage does not match the target storage. Entities exist of type Paragraph and Paragraph type Image. These entities need to be deleted before importing.

This is what I did:

Copied the database from staging and pulled the latest code
Ran drush cex -y
Committed configuration
Went to staging and pull latest code
Ran drush cim -y and get the error stated above

When I run drush cget system.site uuid on local and staging I get the same uuid so I am not sure why I am getting this error.

How can I fix the error?

You can fix this by changing your local site UUID using drush.

I also needed to run a mix of drush entity-updates -y and installing specific modules with drush en <module_name> -y before the configs would import on a new fresh database.

Update: you shouldn't use drush entity-updates -y anymore.  See https://www.drupal.org/node/3034742


Scheduler module- How is the check for publishing done? I just installed the scheduler module and now I was wondering how the check for publising/unpublishing is done. Is it done by a cron task or is a database query executed at every page load or perhaps something else?

It is executed by the cron. The cron triggers a query to check wether something should be published.
It is a bit contraintuitive though. If your cron runs every hour and you want something published on 22:35 and it is past that time it will be actually published the next time your cron runs. So if your cron runs at 22:30 and 23:30 the publish will be at 23:30.


Speeding up page loading of custom view Right now I have a custom view template created where I have a left sidebar and a main content area.

In the left sidebar I have taxonomy menu running to show my taxonomy terms.

I then have a custom view in my main content region filtering the nodes related to the taxonomy term. When I click on each term, the whole page has to load. It's just a bit too slow.

I've turned Ajax ON for my view, but it's not working (probably because I am not using it right).

Would using exposed filters be my answer to this? Or is there any way to keep my format and somehow pass the information to the views without having to load the entire page?

An example of a site doing what I would like can be found here.

You're going to have to attach view filter "actions" to your menu items.  That way your view results will load with ajax.

this is probably the fastest way to do this, though I've never done it I think it's possible (theoretically).

Of course you could also just create Ajax functions that queried your view with the arguments when you click a menu item.


How could I change webform submission tags to common html email tags? I have a webform submission style to display the submission ,like this

but when I send Html Email to others, it didn't show the way we want,it seems to didn't support fieldset and some css elements in some Email client. Now I am here for help that is there some ways or some modules to change the tags to common html email tags like  and add some css to it?
I'll appreciate anyone who help me solve this problem.

I think you want HTML format template option to send an email with HTML format.

For this, you can use  htmlmail and mailsystem module and enable it and select "HTMLMailSystem" option at admin/config/system/mailsystem.

Now check step 3 at admin/config/system/htmlmail and select "Full HTML".

Now you can config you webform mail setting and select custom mail template and add your HTML tags and inline CSS in div.


restrict profile field to module and admin in drupal 6 I am using profile for storing some more information for users. but I want one field of profile be only editable by administrator and my own module code and viewable by own user and administrator.

I guess I have to set visibility of field to '  Hidden profile field, only accessible by administrators, modules and themes. '

but I don't know if it is right or not.

Thank you.

Yep, you got it right.

Inside the profile.module's profile_view_profile() function, it uses the following logic when modifying $user to include the additional fields for viewing...

// Show private fields to administrators and people viewing their own account.
if (user_access('administer users') || $GLOBALS['user']->uid == $user->uid) {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d ORDER BY category, weight', PROFILE_HIDDEN);
}
else {
  $result = db_query('SELECT * FROM {profile_fields} WHERE visibility != %d AND visibility != %d ORDER BY category, weight', PROFILE_PRIVATE, PROFILE_HIDDEN);
}

...so yes, settings fields to PROFILE_HIDDEN will show them only to users with the administer users permission and/or to the user who is viewing his/her own account.

When editing a user, the module calls upon the _profile_get_fields() function to present the fields to be edited on the resulting form, and there, it uses the logic...

if (!user_access('administer users')) {
  $filters[] = 'visibility != %d';
  $args[] = PROFILE_HIDDEN;
}

...to restrict the editing of these fields to just users with the administer users permission by filtering out those fields from users without that permission.

And, of course, if your module or theme wants to edit anything in the database directly, there is nothing to really stop it.


How to create multiple slideshows on my front page? I am new to Drupal and I don't know how can I create multiple slideshows on my front page.

I am developing an image sharing website where users will upload their images. I want that when a user adds a gallery a slideshow is made on the front page. Like if I have four users means I will give four different slideshows on the front page.

Any help?

I would recommend using Views Slideshow as it is a very easy to install and configurable module if you are used to using Views in Drupal.

All you would have to do then is intwine your logic, looping through users and their associated uploaded images and place the block on your front page.

Here is a tutorial for drupal 8 and drupal 7 using views slideshow:

I hope this helps.


Make a field specific to a user I would like to make a field that is specific to a single user, similar to a
non-global flag but allowing more field types than just boolean. Is there a way to do this? For example, if User A sets this field on Node B to 5, then User C looks at that node, he won't see User A's value. If User C then edits the field to another value, then he will see that value instead, and User A will still see his value of 5.

Yes, you can add fields to the user entity with the Field API to

Admin > Config > Account settings > Manage fields

The variety of field types are available and each user has their own field value


How to send password expire notification to users regularly? Working on Drupal 7, I want to get an alert every 3 months to users saying that:

  Password will expire in next 5 days, please change it.

I found a module called Password Expire (fulfill requirement but only in D6).

Is there any alternate of this module for Drupal 7?

(There is anothor module Force Password Change but this module do not send notification.)

Password Policy is by far the best module in D7 to manage your password requirements.

You can use this module to set an expiration time and send a notification email.


Possible to use PDO inside a custom module in Drupal 6? I'm about to build some new functionality on an old Drupal 6 site which will be upgraded to D7 or D8 within a year or so. This new module is heavy on the SQL and I'm building many complex SQL queries. I'd love to use PDO with named parameters to make the code readable.

Is it possible for me to initialize my own PDO connection to MySQL inside the module or will this break the rest of the Drupal environment somehow?

You definitely could (Drupal is just a a PHP application, nothing special in that respect). But you'd lose support for stuff like table prefixing.
If you're looking to use PDO, and stay within the bounds of normal Drupal practices, you should install the DBTNG module:

This is a backport of the Drupal 7 PDO database compatibility layer for use with Drupal 6 modules.
...
This module does not override the existing database functionality but makes the new compatibility layer available under a series of functions identical to their Drupal 7 counterparts named dbtng_ instead of db_. For example with this module, use dbtng_set_active instead of db_set_active, with the exception of the following functions that funciton identically to their Drupal 7 conterparts: db_insert, db_merge, db_update, db_delete, db_truncate, db_select, db_transaction, db_close, db_condition, db_xor, db_and, db_or, db_next_id, and db_like.

That should let you write code that won't need to be changed for Drupal 7 and 8 (unless table/field names change of course).


How can I delete my own node comments? How can I delete my own node comments without installing modules?

Googling, I found the Comment Access module. I don't want to install it.

There is no permission in a default D7 configuration to only delete one's own comment. To get this you must install Comment Access (or another contributed module with a similar function).

If you add the permission "Administer comments and comment settings" (navigate to Administration » People » Permissions), to a role, that role get access to a "Delete" tab for comments, but that lets the user holding this permission delete everbody's comments - not only his/her own.

Installing a module is no big deal in Drupal.  If you want this, I am afraid you need to install a module.


How can the Panels IPE "add content" modal be customized? I have a content type rendered via Panels IPE (In Place Editor) which allows authenticated users to customize the layout of their node. When users click to "add content" I would like to be able to control what appears in the modal dialogue. By default it is not very user friendly:

Ideally I would like to be able to choose what can be added, for example only "nodes", or only "views" and "widgets". I'm not sure where this can be changed or if a module exists that does this already. The only module I have found that attempts to do this is Panopoly Magic which requires an entire suite of modules called Panopoly to be installed. I don't need the majority of the functionality that Panopoly adds and hence I don't think it is a very light solution. Here is the result that can be achieved:

Is there a way the IPE add content modal can be customized?

You can do that for all panels pages from
admin/structure/panels/settings/panel-page

Also if you use panelizer you can customize what appear in IPE for every content type.
admin/structure/types/manage/[content-type]/panelizer

Also you can install panopoly_magic module without other panopoly features, only the module "panopoly_magic.info" since it does not deponent on any thing in panopoly distribution.


How to put page-title inside of my content's first panel? Using a custom theme, pretty basic (so far):

    <?php if ($title): ?>

            <?php print $title; ?>

    <?php endif; ?>

    <?php if ($tabs): ?>

            <?php print render($tabs); ?>

    <?php endif; ?>

    <?php print render($page['content']) ?>

That standalone
 is the problem, though. I want it to appear inside the first panel of content (I'm using Panopoly), but since all the panels are generated by render($page['content']), it's not clear to me how I should do this.

My first solution was to use CSS, positioning the title relatively and adding some padding to the first panel to give it room. However, this only works as long as the title is one line of text. So a pure CSS solution appears to be out.

Given the theme's use of Panels, I would suggest looking into the default panels it uses and whether or not the title field can be manipulated in that way, so that the title could be placed in any given section you want.

EDIT from OP

"Just so. For future readers: I accessed Panopoly > Pages under the admin menu to alter the default page templates. Then for the generic Content Page, set "Title type" to "No title" and edit the settings for the content panel to "Override title" as "%node:title", "h1"."


Selector bulk action missing In the media library, I should see a dropdown selector that allows me to delete bulk items. Is there a way to turn this off and on? I've inherited this site and I'm not sure if the original owner has turned this option off somewhere.

Here is the code that should appear:

        Action
        <select data-drupal-selector="edit-action" id="edit-action" name="action" class="form-select">
          <option value="media_delete_action">Delete media</option>
          <option value="media_publish_action">Publish media</option>
          <option value="media_save_action">Save media</option>
          <option value="media_unpublish_action">Unpublish media</option>
       </select>

  <input data-drupal-selector="edit-submit" type="submit"
      id="edit-submit--2" name="op"
      value="Apply to selected items"
      class="button js-form-submit form-submit" />

I've finally found a solution.

I needed to go to Views/Media and add Bulk update to the Fields, but it was missing. Once I realised that I needed to restore it I found this drush command.

* drush cim --yes --partial --source=core/modules/media/config/optional && cr

Which updates the following:

+------------+--------------------------------------+-----------+
| Collection | Config                               | Operation |
+------------+--------------------------------------+-----------+
|            | system.action.media_delete_action    | Create    |
|            | system.action.media_publish_action   | Create    |
|            | system.action.media_save_action      | Create    |
|            | system.action.media_unpublish_action | Create    |
|            | views.view.media                     | Update    |
+------------+--------------------------------------+-----------+

Then clear cache and Bulk update has now been restored to the Fields section.


Zurb Foundation 4 jquery conflict I am working on a Drupal 6 theme which uses the Zurb Foundation 4 framework. The problem I have is ideally Foundation 4 requires jQuery version 1.10.2.

Drupal 6 only supports up to jQuery version 1.3.2 using the jQuery Update module. Upgrading site to Drupal 7, unfortunately isn't an option.

I have search through forums and tried a number  of the suggested solutions but I can't seem to get both versions of jQuery to function without either breaking Core or Zurb Foundation  functionality.

You can use jQuery Multi module which provide functionality to load multiple jquery in Drupal site.

  jQuery Multi allows you to load an extra version of the jQuery library in parallel to Drupal's version, without conflicting with Drupal's version. You can then choose any
  JavaScript library or files to use the new version of jQuery. No
  need to alter packaged jQuery plugins!

  run a newer version of jQuery in parallel to Drupal's without    interfering with things that use the default jQuery version, using
  jQuery's built in noConflict mode
  use the newer version of jQuery in custom scripts using the provided    alias
  configure specific libraries to use the newer jQuery
  configure any JS file in the system to load using the newer jQuery


On hook_entity_presave how do I now if it is a new node? I'm using the hook

function nvgh_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
}

but I only need to do something when the node is new (not when it is edited). How to do this? I'm inspecting the entity with kint but cannot find a good indicator for this... also kint is disappearing as the node view is redirected into view modes.

How to do this?

Use the Entity::isNew() method:

if ($entity->isNew()) {
  // ...
}


Unresolved dependency Invite (Version 3.x required) I have upgraded drupal , but when i am running update.php I am getting this error .
I have tried after disable invite but still no luck.

Unresolved dependency   Invite (Version 3.x required)
User Relationships Invites requires this module and version. Currently using Invite version 4.0-beta2

Sorry i just found solution . I have have disabled User Relationships Invites using db from system table and it works .


Rewriting the pager of Views in Drupal 7 I have a Views which I am calling via views_get_view and view->preview. I am feeding the Views with a form via Form API - with no exposed filters - and the problem is that while the number of pages is correct, obviously, when I click on a page, I loose the POST variables and the pagination shows results which are not filtered. How can I rewrite the pager so I simply add as GET the parameters to the URL, so I can filter again when the user selects another page? I would prefer not to use exposed filters as I have some heavy PHP processing and would prefer just to make this modification which I would expect it to be easy but cannot find anything.

I found a way, by using the template_pager function in the template.php ( sites/all/themes/mytheme ) and modifying the core behaviour to this:

function template_pager($variables) {
    $tags = $variables['tags'];
    $element = $variables['element'];
    // next line is modified
    //$parameters = $variables['parameters'];
    $parameters = process_post();
    ...
 } // function template_pager

 function process_post(){
    // specific function
    $parameters = array();
    $parameters_sent = array("param1", "param2");
    foreach($parameters_sent as $key => $value){
    if(isset($_POST[$value]) ){
        if($_POST[$value] != ""){
            $parameters[$value] = $_POST[$value];
        }else{
            $parameters[$value] = 'all';
        } // if
    } // if
  } // if
  if(count($parameters) > 0){
    return $parameters;
  }else{
    return NULL;
  } // if
} // function process_post


how to get nid of a node when user is not on a node page I had made a custom form and want a field in it that would work as a node reference field. Currently iam not on the node page but i want the nid of nodes of a content type to be the options of the select field which is my node reference field. here is the code for the select field that should work as node reference field.

function formModule_form($form, &$form_state) {

    $form['selectbox'] = array(
    '#type' => 'select',
    '#title' => t('What is your Qualification?'),
    '#required' => TRUE,
    '#options' => array(
      '1' => 'UnderGraduate',
      '2' => 'Graduate',
      '3' => 'Post Graduate',
         ),
    '#description' => t('Choose an option.'),
  );

return $form
}

the #option in the above code should have the nid of nodes.

You'll want to Query the database for the nodes you need and then use the results of that query to populate the #options property. Something like this:

<?php
    $result = db_select('node', 'n')
    ->fields('n')
    ->condition('type', 'node_type_name','=')
    ->condition('status', 0,'>')
    ->execute()
    ->fetchAssoc();
?>

You can then use the results of that query easily since it comes back as an associative array. You'll want to specify exactly which fields you want (in your case, probably just title and node. See http://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7 for how to do a proper select.


Setting a Warning message in the Page.tpl.php file I'm trying to set a warning message based on a PHP if statement in my page.tpl.php file. I can get a message out using $messages but I cannot using drupal_set_message(). Should I be using the latter before page.tpl.php?

The problem is the $messages variable comes out as plain text, I'd like to use Drupal's message system if possible:

drupal_set_message(t('Don\'t panic!'), 'warning');
$messages = t('Don\'t panic!');

If you want to use Drupal's message system, and you want to do this at the theme-level, as opposed to writing a module, you would enter the code

drupal_set_message(t('Don\'t panic!'), 'warning');

into your theme's template.php file as a preprocess function.  For instance, if you wanted to display this message on all content of the type 'page'

function YOURTHEME_preprocess_node(&$variables) {
 if ($variables['node']->type = 'page') {
  drupal_set_message(t('Don\'t panic!'), 'warning');
 }
}

It should then automatically show up in the $messages area whenever someone visits a 'page' content type.

Note: You might also need to flush your theme cache after making these changes.


Do views filter plugins not apply to base field definitions? I created a custom entity type that has a base field definition like this:

$fields['start_date'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Start Date'))
  ->setDescription(t('The date and time to start.'))
  ->setDisplayOptions('view', array(
    'type' => 'datetime_default',
    'weight' => 3,
  ))
  ->setDisplayOptions('form', [
    'type' => 'datetime_default',
    'weight' => 3,
  ])
  ->setRequired(TRUE);

When I create a view that displays entities of this type, and try to create a filter on this base field, I get the generic filter provided by views, instead of the one defined in Drupal\datetime\Plugin\views\filter\Date.

Why is that?

Looks like this is a known major issue. Here's the main "parent" issue where most of the work is going down: https://www.drupal.org/node/2337515

I think, by default, there is some basic views integration for all entities, but it's not that robust.

As a workaround, I was able to implement hook_views_data_alter to tell views to use the 'datetime' filter plugin instead of the default 'string' plugin it had.

function MY_MODULE_views_data_alter(array &$data) {
  $data['my_entity_type']['start_date']['filter']['id'] = 'datetime';
}


Override theme css with custom styles I built a site with the theme Corporate Clean. I wanted to add some custom CSS (override some colors, fonts etc.) so I added this to the files in the folder /sites/all/themes/corporateclean/...). Now an update for the theme became available and I lost all my custom styles (I have them in source control so no panic).

What is the best way to add custom css that doesn't disappear when a new theme version is published? I prefer file based. I've seen CSS Injector but that CSS would also be gone if I start from a new database.

What you want to do is create a sub-theme so that updating your contributed theme does not overwrite custom changes you've made.


Hide the title or Change the Title style of one page based on page Title Multi site I know that I can hide the title by using:

.page-node-43 h1
{ display: none;}

The problem with that is that I am using this css file for all of the websites that I am using. The websites have different node numbers for sometimes the same kind of page.
So there is the catch.

I want something like

.page-practial h1
{ display: none;}

But that doesn't work.
Do I have to use to achieve this? :)

Thanks in advance!

If you're on a multi-site, you could just use the domain and add it to the body class. That way you can target the same content type differently on each site.

Using preprocess_html...

function THEMENAME_preprocess_html(&$vars) {
  global $base_url;

  // Split the URL
  $site_host = explode('/', $base_url);

  // Split the root domain from the TLD (.com).
  $site_host = explode('.', $site_host[2]);

  // Add it to your body class.
  $vars['classes_array'][] = drupal_clean_css_identifier($site_host[0]);
}

You might have to alter it a bit, but you get the idea. So if your domain was http://example.com, this would add example to the body class.

<body class="page-node page-node- page-node-194 node-type-product example">


Create link to email all views results I have a view that outputs a list of email addresses.

I'd like to find a way to set up a mailto: link that contains all of those as one comma-separated list.

Could anyone advise?

In the views under fields add "Custom Text" field. Wherein text field you can Replacement patterns from exisiting fields. There you can give link

{{field_name}}.

After that edit email field and check "Exclude from display".


Merging output of Print.module's printpdf with existing PDFs Recently, I created an output template for the Print module, such that it dynamically generates a measurement sheet when a certain content type is parsed by its PDF functionality (using dompdf in this case).

Everything works great, but the client's requested file attachment fields for PDFs, such that existing PDFs are added to the end of dompdf's output. For instance, a PDF of a CAD drawing would be attached in Drupal, printpdf/$nid generates the template I've created, and the file locations given from the file upload fields are used to merge the files at those locations with the generated PDF.

dompdf apparently cannot merge PDF documents, so I'm thinking a workaround would be to generate the PDF and save to disk somewhere, run another PDF merger script, then present the merged output to the user.

How would one go about programmatically saving the output of Print.module's PDF generator to somewhere on the server, then running an external class on that saved output?

(Alternately, if you know of a way for dompdf to read PDFs and append them to the document, that'd work even better.)

I hacked print_pdf.pages.inc to merge PDFs after creation based on the existence of a filefield:

Starting at line 209, in function _print_pdf_dompdf();

    $node = $print['node'];
    if ($node->field_pdf[0]) {
        $meas_pdf = $dompdf->output();
        file_put_contents($base_path . 'sites/default/files/pdf_temp.pdf', $meas_pdf);
        include $base_path . 'sites/all/libraries/PDFMerger/PDFMerger.php';
        $newpdf = new PDFMerger;
        $newpdf->addPDF($base_path . 'sites/default/files/pdf_temp.pdf', 'all');
        foreach ($node->field_pdf as $attach) {
        $newpdf->addPDF($base_path . $attach['filepath'], 'all');
        }
        $newpdf->merge('download', 'measurements.pdf');
    }
    else {$dompdf->stream($filename, array('Attachment' => ($print_pdf_content_disposition == 2))); }
}

It'd be great to write a module that undefines Print.module's private _print_pdf_dompdf(); function and replaces it with my own (so I'm not hacking a contrib module); any idea how I'd go about that?


How call a custom function after input got validated in hook_form_alter? I want to call custom functions for doing some profile filed updation on user registration. So i used to implement my custom functions in hook_form_alter. The code is here

<?php
function calculation_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'user_register':
$form['#validate'][1] = 'do_database_updation';
break;
}
return $form;
}

function do_database_updation($form, &$form_state){
/* perform database updation here... */
}

It works fine, but the problem is when the validation fails, the database updation cannot be retrieved back. I want to call the custom function after validate the input values. How it to do ?

You can add your function in  the [#submit] key. For example :

if ( empty($form['#submit']) ) {
  $form['#submit'] = array();
}
array_push($form['#submit'], 'do_database_updation');

The submit handler is called after the validation.


How to allow user to manually change language when using "Browser" Detection as a detection option? We have a site with multiple languages and have been using the Language Switch Dropdown menu to allow users to change languages on the site. But when we add "Browser | Language from the browser's language settings." as an additional detection option along with "Selected Language" then the selected language no longer works as it is always overridden by the browser's language, even if "Selected Language" is placed before it.
The ideal workflow would be:

Language is detected from the browser and translated
The Language Dropdown shows the current language (currently it always displays the default language, even if the browser detects and switches to a different language)
The user can then override the browser language by selecting a different language from the drop-down switcher. (Currently the dropdown has no effect if a language is detected via the browser)

SOLUTION EDIT:
The proposed solution did not work for us so we ended up writing a custom form alter function and using a one-time cookie to achieve the functionality we were looking for.
In the language detection, we have "selected language" enable as the first item then "URL" and the second item and no other detections are used.
Then we used the below hook to the detect and set the language from the browser one-time using a cookie. The hook also sets the default value of the language dropdown so it shows what the language is, even if set from the browser.
<?php

function MY_MODULE_form_lang_dropdown_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    // Only run if our custom language cookie is not set yet
    if (!isset($_COOKIE['Drupal_visitor_user_lang'])){

      // Get language set in browser
      $language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
      user_cookie_save(['user_lang' => $language]);

      // Set the language dropdown's default value
      $form['lang_dropdown_select']['#default_value'] = $language;

      $current_path = \Drupal::service('path.current')->getPath();
      $path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
      $config = \Drupal::config('system.site');
      $front_uri = $config->get('page.front');
      $front_alias = \Drupal::service('path.alias_manager')->getAliasByPath($front_uri);

      if ($path == $front_alias){
        $path = '';
      }
      $default_language = \Drupal::languageManager()->getDefaultLanguage()->getId();
      if ($language == $default_language){
        $language = '';
      }
      $response = new RedirectResponse('/' . $language . $path);
      $response->send();

    }
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $form['lang_dropdown_select']['#default_value'] = $language;
}

The Selected language option comes with this description:

Changing the selected language here (and leaving this option as the last among the detection and selection options) is the easiest way to change the fallback language for the website, if you need to change how your site works by default (e.g., when using an empty path prefix or using the default domain). Changing the site's default language itself might have other undesired side effects.

This option is meant to be the last on the list and used only as a fallback.
If you give Browser option advantage on the list by placing it above the URL option the language will always be chosen by the browser criteria.
I'm guessing that there are cases where browser language might be not available in which case the URL option will kick in, but in most cases the URL option will not be used because Browser option will set the language and no options that come after it will even be evaluated.
It seems you need the Session option before the Browser option. This option should work with the Language switcher to add the parameter in the URL that will set the chosen language, but before the user selects something from the dropdown the Browser option will set the language.
Turn the URL option off completely if you don't need the language prefix to avoid confusion when the parameter is present. Having too many options turned on complicates the system unnecessarily and makes it more difficult to figure out what the causes are if there are bugs present.
I haven't tested this configuration. Language configuration can be tricky and you may need to do more adjustments and testing to get to where you want to be.


How can my Drupal module expose custom URLs? I'm writing a custom drupal module and have just starter out working with Drupal.

I need to expose a custom URL from my module so that some JavaScript files can request this URL for XML data. How can I do this? I'm not referring to the hook menu. Thanks

You need hook_menu in your .module file.

  This hook enables modules to register paths in order to define how URL requests are handled. Paths may be registered for URL handling only ...

example:

function MY_MODULE_menu() {
  $items['path/callback/%/%'] = array(
    'page callback' => 'my_callback_func',
    'page arguments' => array(2, 3),
  );

  return $items;
}

function my_callback_func($arg2, $arg3) {
  //your process here
  $data = array($arg2, $arg3);
  return drupal_json_output($data);
}

in js call this url with 2 arguments: path/callback/VAR_1/VAR_2 - VAR_1 is second argument, VAR_2 is third as defined in "'page arguments' => array(2, 3)" (path is zero argument, callback is first argument)

The $data may be returned in what you want format. In this example this is JSON.

More for hook_menu - http://api.drupalize.me/api/drupal/function/hook_menu/7


Customizing menu link output In Drupal 7, how I can intercept menu rendering in template.php and add pipes after menu links?

I tried using template_preprocess_menu_tree but I don't think that is what I am looking for. I want to change the HTML structure of a couple of menus.

theme_menu_link() did the trick. It contains an array under element of #original_link which has the menu name in it. Using that, I can add pipe delimited links to certain menus.

http://api.drupal.org/api/drupal/includes--menu.inc/function/theme_menu_link/7


how to automatically create other entities when creating an entity I have 4 entity types. All types have a relation to each other. For now let's call them A, B, C and D. How can I allow a user (let's say userA) to create an entity of type A so that entities for B, C and D are also created at the same moment. UserA has the permission to create A entity types and is not the author of the automatically created entities of type B, C and D.
Is there a way to automatically create these related entities?

If you were looking for a code solution, you can use hook_entity_insert() to trigger the creation of the other entities.

Your custom module code would look something like this:

function mymodule_entity_insert($entity, $type) {
  if ($type == 'typeA') {
    // entity type A is being inserted
    global $user;

    // now create type B
    $entity_b = entity_create('type_b', array(
          'uid' => $user->uid,
          'type' => 'type_b', //bundle
          'field_my_field_c' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => 'foo!',
              ),
            ),
          ),
        ))->save();

    // now create type C
    $entity_c = entity_create('type_c', array(
          'uid' => $user->uid,
          'type' => 'type_c', //bundle
          'field_my_field_c' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => 'foo!',
              ),
            ),
          ),
        ))->save();

    // now create type D, etc...
    }
}

I've borrowed from the code sample posted in the comment from Mołot and for simplicity sake, I made the author of A to be the same as B, C and D.

One more thing, the entity_create() function is in the contrib module Entity API. Your custom module would have a dependency on Entity API.


Drupal Apache solr does not return "no results founds" I'm using Apache Solr 7.x-1.1 with Drupal. It was working fine but something happened and when I search for dummy data that I'm sure that is not found in my site, the search result will be all nodes in my site instead of returning "your search yielded no results". It was working perfect before but I don't know what I did so this occurred.

I met the same issue, and the main reason was the solr 'bias' settings in admin/config/search/apachesolr/settings/solr_search/bias

I changed some of its configuration. the solution is clicking 'reset to default' button.


Theme suggestion template is not being picked up I add template suggestion in my discount module:
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
      kint($suggestions);
    }
}

And I can see template suggestion on my admin form:

However I added template field-user-discount.html.twig (I don't place it here as it simply the copy of classy one with change of order) in discount module templates folder and it is not being picked up, it still picks up the classy one. I cleared all the caches, both from drush and site itself. I also tried to add this template to theme templates, it is not being picked up there as well. Other templates from both theme and discount modules are being picked up.
How can Drupal pick it up? It is the field on admin pages.

After you add your theme suggestion:
function discount_theme_suggestions_field_multiple_value_form_alter(array &$suggestions, array $variables) {
    if ($variables['element']['#field_name'] == 'user_discount'){
      $suggestions[] = 'field_user_discount';
    }
}

You need to tell Drupal in this hook you should pick my template by implementing hook_theme like the following.
/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form'
    ],
  ];
}

Now just put your template in you templates module folder clear cache and it will be picked.
Note: if you want to use a different name from the suggested one (field-user-discount) of your template like field-user-discount-something.html.twig just tell the hook_theme the name of template like:
 /**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return [
    'field_user_discount' => [
      'base hook' => 'field_multiple_value_form',
      'template' => 'field-user-discount-something'
    ],
  ];
}


How can I rewrite an "edit" operations link in Views? On Drupal 8, I'm trying to modify /admin/people to have the edit button read  edit username instead of edit.

What's the easiest way to do this?

Under fields, add the User ID.  Select Exclude from display and choose Unformatted for the Formatter.
Under fields, add User Name again.  Uncheck display as link.  Under Administrative Title, you can add something descriptive like user name (no link) so that you can remember what this is for.
Rearrange the fields so that User ID and the second User Name fields are at the top.
Click User: Operation Links under Fields.  Under Rewrite results, input the following for the text: edit {{ name_1 }}

This makes a plain link instead of a button.  I imagine there is a more efficient way to do this, but this is the best I could come up with for now.


Drush, post receive hooks and git branches/tags I am stuck with a nagging issue in our deployment systems

drush version 5.7
git version 1.7.7
Drupal 7.x

We currently have a bare git repository (consisting of drush makefiles) on the production server that fires off a post-receive hook to recursively build our Drupal multisite structure with drush make when it receives new data via a push from our local machines.

Everything works very swimmingly until a project in the makefiles contains either a git tag or branch in the definition. Then, the post-receive hook triggered build fails with :

    git://github.com/[account]/[repo].git.
    DOWNLOAD_ERROR: Unable to check out tag 7.x-1.01. -- build forced  [warning]

Even more interesting : if I run the build on the production server locally or via a remote SSH command, the build succeeds. The problem only arises if it is run from a post-receive hook from a remote git push.

Verbose output offers no more information.

I can only assume that the post-receive hook system in git does not store/carry over an environment variable that is required for a drush to perform a two-step git operation on the single project. Is this a known issue?

I recognize this hurdle can be avoided by defining the project in the makefile as a 'get' download and providing the github download URL (instead of using the git functionality). Being pedantic, however, I'd like to narrow down where the problem is, and report it as a bug if appropriate.

I can repeat this on a fresh install.

But has anyone run into this? Solutions would be welcomed with elation.

Your tag 7.x-1.01 could be the problem ... In most Drupal projects the tag would be 7.x-1.1 (Without the zero)


D8: Why updated paragraph content does not lead to an updated translation? I created a content type made up with a long-text field and a multivalue paragraph field. I create some content adding several paragraphs to the same node, then I choose "Translate" and everything is fine the first time I do this: all original paragraphs appear ready to be translated.

However when I update the original language node adding new paragraphs, these new paragraphs do not appear when editing the translation and I'm forced to delete the latter and create a new translation. Why is this happening?

To expand on the comment from @4k4, for most use cases, you want to make the paragraph field untranslatable because it just stores the references to the paragraphs, which are then being translated.

Then you always have the same paragraphs in the same order for all translations.

Translatable paragraph fields are not yet properly supported (this is being worked on in the issue queue) and it should only be done if the paragraph structure must be different for different languages.


Conversion tracking code immediately after body tag? I'm fairly new to Drupal, so bare with me. I need to add some tracking code immediately after the body tag on the checkout complete page. I'm guessing I need to add it to the html.tpl.php or $page_top variables or maybe a checkout pane. My question is:

Which way is the best way to do it?
If I need to add it in the html.tpl.php, how would I do that for just the checkout complete page?
If I need to add it in the $page_top variable for only the checkout complete page, how would I do that?
If I need to do it in a checkout pane, how would I keeping in mind is needs to be immediately after the body tag?

Using the Drupal Commerce module.

You can do this in template.php by using theme_preprocess_html()

function mytheme_preprocess_html(&$vars) {
  $arg = arg();
  $vars['checkout_tracking_script'] = '';
  if (count($arg) == 3 && $arg[0] == 'checkout' && $arg[1] == 'complete' && is_numeric($arg[2])) {
    $vars['checkout_tracking_script'] = '<script>myScript</script>';
  }
}

Then in your html.tpl.php you can print your script like this.

<?php if ($checkout_tracking_script): ?>
  <?php print $checkout_tracking_script; ?>
<?php endif ?>


Is it possible to have a single date exposed filter with date range? In my existing exposed filter, I have two field (Start and End Date) filter, Is it possible to create as one field?

yes, there is a module for that, views_between_dates_filter, from module:

This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.


D7. Facebook Stream: show user's feed I try to display authorised user's news feed:
I installed Facebook Stream module in Drupal 7. After facebook login module displays an error:

  FacebookApiException: User must specify a valid extended permission or
  data permission in BaseFacebook->throwAPIException() (line 1325 of
  Z:\home\devfb.kz\www\sites\all\modules\facebook_stream\facebook-php-sdk\src\base_facebook.php).

I can't understand why permissions which I specified in the module are invalid?
Permissions:

return '<fb:login-button '. drupal_attributes($attr) .' onclick="FB_Connect.login_onclick()" scope="read_stream,publish_stream,offline_access">'. $text .'</fb:login-button>';

Maybe I can do this with another module?

If I understand what you want correctly, you don't need a specific module at all to do this. You can just have embed code generated and add that to the source code for the block/page you want to add it to. You can have embed code generated here. Be sure to select "Show Posts" if that's what you want.

Edit: I just re-read your question and see that you mean to do this for the authorized user... in this case my answer may not be helpful.


How replace a node term programmatically? I have a vocabulary (this is a workflow vocabulary) and another vocabulary attach to a node.

How can I replace workflow term by single another workflow term without change some other vocabulary ?

Something like this ?

$old_terms = taxonomy_node_get_terms_by_vocabulary($node, 23);
foreach($old_terms as $tid => $old_term){
  unset($node->taxonomy[$tid]);
}
$new_term = taxonomy_get_term(30);
$node->taxonomy[$new_term->tid] = $new_term;
node_save($node);

you can add term using term id(tid) $node->field_yourfield_name[$node->language][0]['tid'] = $tid in D7