How to automatically change a Content type field value based on Date field? I'm using Drupal 7, I have a content type, where I have two fields for project allocation:

Status(Active/Inactive)
End Date

If the "End date" is less than current date, then the "status field" should be Active(By Default, Status will be Active) and if it exceeds current date, then that particular "status field" value in Content type should automatically change to Inactive.

Now, how can I automatically change the field value without any Button trigger?

I think you have to do this with some custom JS code.

You can do something like this:

$('.end-date-field').on('change', function () {
  var endDate = new Date($(this).val());
  if (endDate < Date.now()) {
    $('.status-field').val('inactive');
  }
});

This code is not 100% correct, but it can help you to get an idea of what you have to do.


Store user test results against their profile in Drupal Quiz Site I have created a drupal quiz site without depending any quiz modules. I want the user to be able to save their Test result against their profile. So they can see when they log in.

The Result will be like this usually:

  Total Result: 24/30.
  Main Subject: Main_Subject_Name.
  Sub-sub1 score: 12/15.
  Sub-Sub2 score: 12/15.

There can be any no. of sub-subjects depending on test. It would be great if I could be able to pull them later with views.

This is what i have in mind. Create a content type results with 2 fields.  User Id and Data.
User id will hold the uid and in data i will add a json(ified) version of the result for later use. Is this ok? or are there any drupal specific ways to do this?

You can also create fields directly attached to the User entity just as you would to a content type.  It may make more sense to store the information for a specific user in fields attached to their identity directly. You can create views and panels to display the information however you want and provide hook functions in a custom module to do whatever specialized calculations you desire for presenting averages, grades etc.

I also noticed that you have used the Profile tag which relates to a module that has been deprecated for D7.  If you have the module enabled, I recommend not using it for any future site since it will very likely not be maintained in D8.


How do I create a multilingual export? I have Drupal 8 site which interacts with a React component.
I want to expose one of my content type's content using REST export in views.
How do I set views path to create REST export for multilingual support?
For example, mysite/rest/export/data should give JSON data in English, while mysite/nl/rest/export/data or mysite/rest/export/data/nl should give JSON data in Dutch.

Found solution in two ways.

Method-1:

Add language in filter criteria as mentioned below.

Method-2:

1) Add language in contextual filter

2) Provide a default value & select path component(I have selected 2)

3) Provide view path as "rest/nl/export" - EN or NL provide your language code


Views Load More pagination causes duplication I am encountering an issue with Views Load More with Waypoints module. My question is more focused on the next contents that are retrieved. Because there are new contents added to the top, the page 2, for example, now contains items from page 1, thereby showing duplicates. Please see explanation below. How can this be addressed?

Some suggestions:

1) Do not use the LOAD MORE option in views but use a self generated link with the help of global text in the footer. Then this link is going to a second page and then you have the view in a new fresh window. Hopes this helps.

2) You can try if the behavior of the view is the same without Ajax. Sometimes live is a miracle. if so you know that is a ajax issue and not a views issue.


How can I auto tweet any node of a specific type to Twitter? I know the Twitter module lets you setup automatic tweets of new content to your twitter account, but I am wondering how/if its possible to schedule automatic tweets of old content as well.

I ended up doing this with Rules, Rules Bonus Pack, Views, Flag & Twitter Modules.

Set up a Rule that is:

Triggered during Cron runs.
Has no conditions
Loads a list of Node IDs from Views (Rules Bonus Pack)
Posts to twitter based on the first NID in the view.

For my view, I made a flag called Tweet This attached to my node type, and the view displays nodes that have this flag.  You could use a different method to grab the list of nodes you want to tweet, such as filtering by date posted (get older content based on a given date) or number of views (popularity).

Good luck!


Changing existing date time field I am working on an already existing site that has content.
There is a content type with field date and time. I need to remove the time component and just be Date only without deleting any content along the way. If the time data is lost, that is fine.
Can I simply delete the field and recreate it with date only? Or will that delete the existing data?

Unfortunately, as suggested, programmatically changing the config won't work, as all dates will show empty. Which explains why it's locked in the UI.
You'll need to browse your DB and find the node__{field_date} table and manually remove the time part for all values.

Then make a sql export of this table.
Repeat the above with node_revision__{field_date}.
In Drupal, manage fields, delete your field_date. Recreate field_date with Date only. Import your sql db table exports you had made.
Flush cache in Drupal.


View with relationship - column displaying count of related nodes I have a content type ("Interviewee") and a Media entity using the new media stuff in core (e.g. Remote Video) which have entity references back to the Interviewee entity.

I then have a view of the Interviewee content type, with a relationship to Media.

Rather than displaying multiple rows per person for each related media file, I'd just like display the total number of audio/video files linked to that content type in a column – including, this is important, a 0 for anyone who doesn't have media files - also ideally the column would be sortable.

Is this kind of basic counting of relationships possible in core / with a widely used module, without having to code a custom views field or a views sort plugin?

I've written similar plugins before, however I kind of assumed I could do it using aggregation - but I'm not getting anywhere.

You can do this with Aggregation.

First create your normal Views listing Interviewee nodes. Add the Media reference field and set to show all values in one row.

Turn Aggregation on, and change the Aggregation settings for the Media reference field to Count or Count DISTINCT.

Sorting criteria can sometimes mess up Aggregation counting so it's best not to have any while you're configuring the Aggregation, then add later once you know Aggregation is working and check each step that it's working as expected.

You can even add the Sort criteria for the reference field and use Aggregation on it (again Count or Count DISTINCT), Expose it if you want to allow users to change the order Ascending/Descending.

Sorting also works in a table Format if you turn on sorting for that field.


mediafront module showing thumbnails instead of original image I am doing the annoying crosspost thing but I can't get any answers on drupal.org so hoping somebody here can answer this.

I'm using the mediafront module to display images or videos in a slider. it shows videos just fine and if the first slide is a image it shows up correctly. However the subsequent slides the images show up as thumbnails. It is putting in specific styling in the image tag to make it a thumbnail. I really need an answer for this and hope somebody knows what is going on.

Thanks.

Here is the installation guide.

Step 4 shows how to set up your fields, now just make sure you go to the "Manage Fields" for the content type you created, click edit next to the image field. Check the page for a dropdown for "image style", set it to none and define the dimensions of the image.


filter entity reference by another entity reference field in create content there is two content types "country" and "state".
content type "state" has entity reference field for "country".

there is another content type called "shop" which has two entity reference field for "country" and "state".

when i creating "shop" it display all the "state" .

but i want something like when user select one country, the corresponding states to the country should display.

how to do that help needed .

It appears like you are looking for Reference field option limit module. Your case is their first example:

Example 1: countries and cities
Suppose you want to label articles (or products, or businesses, etc) by both city and country so both can be used for filtering and searching. You could use a hierarchical taxonomy with city terms as children of country terms, but that doesn't make sense when you come to set up Views filters.
With this module, create two separate taxonomies for country and city (or content types, or whatever entity you want to use). Then add a reference field so that each city points to its country: eg, the term 'Paris' has a reference to 'France'.
Then when editing an article, selecting 'France' in the country field will cause the city field to update to show only cities in France.

And yes, it works with nodes just as well as with taxonomies, as both kinds are entities.


Aegir / drush alias issue: profiles specified at command line get forgotten Note: Aegir is an installation / site management tool for drupal sites & platforms. See http://community.aegirproject.org/ for details.

This question may be down to an Aegir issue or a drush one; thoughts from either angle are welcome:

I've managed to create Aegir/drupal platforms via both the command line (see http://lists.aegirproject.org/pipermail/aegir/2011-January/000026.html) and web interface, and I can get sites to install with a selected profile through the web interface, but when I try to install a site via the command line it keeps resetting to the default profile. Can anyone see what I'm doing wrong here?

I create a site alias:

drush --uri='demo.c.didev.co.uk' provision-save '@site_demo.c.didev.co.uk' --context_type=site --platform='@platform_dennis_generic_20110316b' --profile='myprofile' --db_server='@server_localhost' --client_email='me@domain.com'

and it creates a valid alias file:

cat .drush/site_demo.c.didev.co.uk.alias.drushrc.php
<?php $aliases['site_demo.c.didev.co.uk'] = array (
'context_type' => 'site',
'platform' => '@platform_dennis_generic_20110316b',
'server' => '@server_master', 'db_server' => '@server_localhost',
'uri' => 'demo.c.didev.co.uk',
'root' => '/var/aegir/platforms/dennis_generic_20110316b/',
'site_path' => '/var/aegir/platforms/dennis_generic_20110316b//sites/demo.c.didev.co.uk',
'site_enabled' => true,
'language' => 'en',
'client_email' => 'me@domain.com',
'aliases' =>  array ( ),
'redirection' => false,
'profile' => 'myprofile', );

However, when I run "drush @hostmaster hosting-import @site_demo.c.didev.co.uk" it rewrites the alias file to "profile = default" and installs with the default profile!

Now, this is a pain but not a disaster as I can do the initial site creating via the web interface and it'll work, but I get apparently related errors when trying to migrate on the command line (per instructions at http://community.aegirproject.org/node/41) where it appears to not create an array of profiles and crashes (I'll post on that separately later) and wanted to rule out these problems before I tackle those.

So - am I doing something wrong, or is there just a bug?

I tweeted this to Mig - he says:

  probably a bug. Workaround is to not hosting-import the site but re-verify the platform & let it autoimport site by itself

HTH! =)


ubercart template email addresses hard coded in template I have inherited an app which has an email hard coded into an ubercart template here /sites/all/modules/ubercart/uc_order/templates/uc-order--customer.tpl.php

How can I set up this email to be accessible from an adminitratable page instead of being hard coded so it can easily be changed?

There are 2 components here: capture/store a setting for you email & insert it into your template.

Since it's a part of your template settings, I'd suggest hook_form_alter() the order template setting form to capture/store a variable:

function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {
  $form['MYMODULE_uc_order_template_email'] = array(
    '#title' => t('Template Email'),
    '#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
    '#description' => t("Template Email"),
    '#type' => 'textfield',
  );
}

The next component is to take that variable an inject it into your template. Using the example above, the variable MYMODULE_uc_order_template_email will now be available. Use a pre-process function to insert a email variable into template. Add this to your theme's template.php:

function MYTHEME_preprocess_uc_order(&$variables) {
  $variables['my_email'] = variable_get('MYMODULE_uc_order_template_email', 'test@example.com');
}

Lastly, copy over uc-order--customer.tpl.php to your theme directory (so UC updates don't wipe away your customizations), flush the cache (to pickup the new template), and, insert $my_email into your uc-order--customer.tpl.php copy.


Views Slideshow Using Absolute Path to Images We are using views_slideshow to display a 3 image slideshow on our homepage.  The Style is Slideshow, the Row Style is set to Fields.  The Field is: Image attach: Attached images and we are filtering for a specific Node:Type.  The Node Type were filtering for has an attached image which is what the slideshow uses.

The problem we are encountering is that the <img src=""/> references to the image appear to be absolute URLs so that if you view the site over https:// in Internet Explorer, you get the message about referencing unsecure content on a secure page. (since the URL to the image looks like: http://www.foo.com/sites/dailyaccess.com/files/images/Banner1.jpg even though you are viewing the page over https://)

How can we go about correcting this to use a relative URL or display the correct secure/unsecure URL?

Implement hook_preprocess_views_view_field() or hook_preprocess_views_view_fields(). In those you should be able to alter anything related to that image field. If the image field happens to be represented as a render array in the hook (assuming you are using Drupal 7), you can also change the theming function to use for that image. Within your own image theming function, you can get the path to the image using file_create_url(), which supports https.

If you need a good example of an image theming function, you can look at core's theme_image(). For a complete list of Views preprocessors, you can look at the views/theme/theme.inc source code.


A way/module to display a list of Blocks assigned to specific path? OK, this is a bit tricky to explain, but I hope you understand what I'm looking for.

I have a lot of nodes created with the 'Basic page' content type, and at least 20 different blocks assigned to each Basic page. I'm wondering whether there is a way (or a module) the display a list of Blocks in the Drupal backend that are ONLY assigned to one node? There are 20 blocks assigned to each Basic page, and lots of Basic pages, therefore it is tricky to identify which Blocks are displayed on which page with the huge list I see in the Drupal Blocks page.

What would be good is if there was a way to filter Blocks on the admin page by path that they are set to, or something like that?

This is what I'm looking for, is there a module?

I not sure have I understand your question.

At the picture below you can set it two path. Exmaple:

Page_1

Admin_Block_Page

Another one will be:

Page_2

Admin_Block_Page

When you go to Admin_Block_Page, it will display block in Page one and Block in Page two.

Another Method: views
Module:https://www.drupal.org/project/views
You tube: https://www.youtube.com/watch?v=3L9JLZOb_LQ


Programmatically append values to entity reference field of node with a dynamic field name I understand that I can append values to an entity reference field to a node normally with this method

$node->field_tags[] = [
    'target_id' => $my_id,
  ];

However I have a function like so

function addTag($node,$field,$id){
$node->set($field,[
    'target_id' => $id,
  ]);
}

In other words I have to anticipate any field the user supplies. Looking at the node class here

https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x

I did discover the set function that lets me specify a field and a value but I don't believe that this would append to an array of entities in a field.

How would I append to an entity reference field to a node if the field name is supplied in a variable?

Yes, the class Node is a good starting point to look for an OOP way:

Click on get(), which returns a field object FieldItemList, where you can use the method appendItem():

$node->get($field)->appendItem([
  'target_id' => $id,
]);

Replace ->get() with {} and ->appendItem() with [] and you get the shorter version which @Clive mentioned in the comment:

$node->{$field}[] = $id;

This is possible because of the  magic method ContentEntityBase::__get and the ArrayAccess interface the field implements. I've also dropped target_id, because you don't need this for the main property of a field.


Send email from template file I am making a return request page for my website the user will enter in his/her information about their order and it will pull up a list of their order. The information is pulled from the views then submitted to the confirmation page.

I already have the form validation working but I need the validation code written in the page--node--nodeid.tpl.php to send an email to 2 people, the customer and me, using the information from the form.

I've seen drupal_mail(), but this seems like it needs to be used in a module.

Is this even possible?

On a side note it would be helpful to be able to use a template later.

Doing all of this within templates really shouldn't be the way to go. Write a custom module. And then do the following:

Use hook_menu() to create a page. Page callback would be drupal_get_form. Page argument would be YOURMODULE_form.
Inside YOURMODULE_form() you'll create your form. Check Form API for detailed info.
Finally you have to add a submit function YOURMODULE_form_submit() where you do your processing and use drupal_mail() to build and send your emails.

Maybe look at a little module I once wrote myself that follows a similar approach, form to mail, only it doesn't happen on a page but in a block instead. So that it can be placed on every page you want.


Get a list of all users and into an array I was wondering what how to get all the user and put all their UIDs into an array? I have seen similar questions but none really answer my question.

In Drupal 7 you can fetch all the users using entity_load like following,

$users = entity_load('user');

and array_keys($users) will gives you the array of uid's


How to add button to webform to set value to a field Using Drupal 7 and Webform (both up to date), I'm looking for a way to add a button that when clicked, set the value of a field.

I can add a button using code like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {

switch ($form_id) {

case 'webform_client_form_ID':
  $form['alt_button'] = array(
  '#type' => 'submit',
  '#value' => t('Alternative Action'),
);

I now need to figure how to perform the action of changing the value of one of the the webform field when this button is clicked...

Any help will be appreciate!

You will have to create a button in a

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
    // Your code here.
}

and use the #ajax property of the button to update the field when the button is clicked.

The examples D7 module has some nice AJAX examples that will show you how the mechanism works.


How to use a sub-domain for a specific content type? I have a blog content type. My client would like the domain to be blog.example.com for only that content type. I would like to know the best way to approach this, whether it be a rewrite rule or using Domain Access Module.

I have installed the Domain Access module, and created my primary domain (example.com) and another domain (blog.example.com) for the blog - but am now not sure how to go about assigning that domain for my blog content type.

Any advice is much appreciated - please keep in mind this is for Drupal 8.

In hook_ENTITY_TYPE_view_alter you can check for your content type and redirect here.
Lets give a try , maybe it will help


How to eMail webforms to 2 alternating email adresses? I got a Drupal 7 site with a working webform in it. Now I got 2 email addresses to send the mails to, we want to send them like so:

Send 1st email to emailadress A.
Send 2th email to emailadress B.
Send 3th email to emailadress A again.
Send 4th email to emailadress B again
... and so on.

Can someone help me how to do this or push me in the right direction?

I was thinking about something with the Rules module.

1. Userids with those eMail IDs
Assume that some userid exist for a user named X, with emailadress A, and similarly user Y for emailadress B.
2. Enable the Webform Rules module
Use the Webform Rules module to transform your Webform question to a Rules question. Some details about it (from its project page):

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

To get you going, have a look at this example rule (in Rules export format):
{ "rules_process_submitted_webform" : {
    "LABEL" : "Process submitted webform",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules" ],
    "ON" : { "webform_rules_submit" : [] },
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "A new webform submission has occurred",
          "message" : "A new webform submission has occurred (with form-id \u0022[form-id:value]\u0022). It was submitted by the user with id = [user:id], name = [user:name] and eMail Id = [user:mail] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

I intentionally did not include any Rules Conditions here, just to illustrate that by using this Rules Event (= a form is submitted), you do have access to a limited set of tokens related to the user who submitted the webform, such as [user:id], [user:name] and [user:mail].
3. Enable the Flag module
Use the Flag to create a flag for flagging users. Its purpose is to (automatically) indicate which of both users (X or Y) should receive the next eMail, i.e the next eMail should go to the user who is flagged at the time of the webform submission.
4. Create 2 custom rules
a) Send an eMail to user X
Create a 1st custom rule like so:

Rules Event: a form is submitted
Rules Condition: if user X is flagged
Rules Actions:

Send an eMail to user X.
Unflag user X.
Flag user Y.

Note: you probably have to use "switch to direct input mode" multiple times (to be able to enter the uid of user X or Y).
b) Send an eMail to user Y
Create a 2nd custom rule like so:

Rules Event: a form is submitted
Rules Condition: if user Y is flagged
Rules Actions:

Send an eMail to user Y.
Unflag user Y.
Flag user X.

Note: you probably have to use "switch to direct input mode" multiple times (to be able to enter the uid of user X or Y).
5. Perform an initial flagging of a single user
Decide which user (X or Y) should receive the very first eMail, and flag that user. After doing so, next time a webform is submitted the process to send those eMails will start. And as long as you don't flag either one, nothing will happen (as per the implemented Rules logic in step 4 ...).
Note: If you ever want to stop the process, just unflag the user (X or Y) that is flagged.


Install Drupal using composer I'am trying to install Drupal 7 using composer. Before that I tried to install drupal 8 using composer and it works perfectly.

Now when I try to install D7 using same method it is still installing D8 instead of D7. I set up package repository as mentioned here but still installing D8 only. I tried $ composer clearcache also but no difference. Please help.

Checking https://packagist.org/packages/drupal/drupal for the versions available there is NO 7.x version. Drupal 7 has no composer.json for this to command to work.

You can use one of the other 2 methods mentioned on https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Using https://github.com/drupal-composer/drupal-project you need to tell the version

composer create-project drupal-composer/drupal-project:7.x-dev \
  test-3 --stability dev --no-interaction

Using https://github.com/hussainweb/drupal-composer-init you can do

composer drupal-init --drupal-7

Please note:

applying core patches seems tricky or even not working. The core tree (whole web root) is deleted then reapplied. But then ie sites/all/modules gets emptied. See

https://github.com/cweagans/composer-patches/issues/42
https://github.com/drupal-composer/preserve-paths/issues/10
In https://github.com/cweagans/composer-patches/issues/42#issuecomment-288365507 a patch is available but that seems NOT to work 100%


How to hide Fivestar field when editing a comment from another user? My comments on articles have a required Fivestar rating field called 'Stars' and I hid it with the following custom module (see: How to hide rating field when adding comment to own node?):
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['#node']->uid == $user->uid) {
      unset($form['field_stars']);
    }
  }
}

As an administrator, I've permission to edit comments from other users. Suppose that a user commented on his own article. That means he didn't have to set the 'Stars' field, due to the code above. But when I try to edit that comment, I do have to select a value for the 'Stars'.
How can I prevent this? It's sufficient to check that the uid from the user who wrote the comment differs from the uid from the user who edits the comment. Finally, mark that the obligation to select stars when I leave a new comment myself must be preserved!

Edit: I tried the following code:
function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  $comment->uid = $form_state['values']['uid'];
  if ($form_id == "comment_node_article_form") {
   if ($comment->uid != $user->uid) {
    unset($form['field_stars']);
    }
  }
}

Apparently, $form_state['values'] isn't well defined, because I get the following error:

"Notice: Undefined index: values in hiderating_form_alter()".

What's the correct code?

The code in the edit doesn't work, because $form_state['values'] isn't present before the submit. This is the correct code:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['uid']['#value'] != $user->uid AND $form['uid']['#value'] != 0) {
    unset($form['field_stars']);
   }
  }
}

Using dpm($form), I discovered that $form['uid']['#value'] returns the uid from the user who wrote the comment. The value is only different from 0 if a comment is edited. When a user writes a new comment, the uid from the form is 0. That's why the AND in the second if is necessary.


Can you export a list of registered users who've registered for an event via the registration module? Sorry if this is a duplicate. I tried to make sure it wasn't before I posted this.

In Drupal 7, does anyone know if there is "out of the box" functionality (that comes with the Entity Registration module) to export a list of people who've registered for an event via the registration module? Ideally, without using views, etc. Something that an end user/site editor could do.

I had a client ask if that were possible. I couldn't find an answer anywhere else and I've never used it before.

Out-of-the-Entity-Registration-box you will (to my knowledge) not get such export facility that you are asking for, so the short answer is NO.

But Sales starts when the customer says no ...: have a look at the Community documentation of the Entity Registration module, especially to this part of it:

  Not happy with the default tabular list of registrations? No problem,
  registrations and their fields are all Views friendly. You can override the default event registrations list, create additional ones, etc.

In other words, if you're willing to accept, as a compromise, to get other modules involved, then it should be pretty forward. However with only views you still don't have the "export" function yet, and you'd need another module on top of that, like the Views data export module (or any of the "similar modules" mentioned on that project page).

Unless you're open to an alternative module for this views-and-some-other-module(s) approach ... I.e. if you'd be willing to only consider the Forena module (disclosure: I'm a co-maintainer), you'd have your 1 stop solution (only 1 extra module, that can do everything you are asking for). Have a look at it's community documentation to get the idea about it (or look at the answers to some of the forena questions). Or post a followup question like "How can I do this with the Forena module?" (to avoid you'd have to change your question here to a chameleon question).


Disable user language setting in user-edit page I want to unset this specific part of the settings form in template php. I found some code example for Drupal 6, but can't figure out how to do it in Drupal 7.

I tried this without result:

if ($form_id == 'user_profile_form') {
  unset($form['language']);
}

(There is a module "user tweaks" but I want it to do it in the preprocess)

I created both the mentioned projects and I have maintained them for a while. (I stopped maintaining Drupal 6 and 7 modules.)

The code used in the Disable user language module is not correct: unset() should never be used for form elements, as this would cause problems to modules that try to access the form element.

The correct code is the following one. It would preferable if the code would be executed after other modules execute their own code.

/**
 * Implements hook_form_alter().
 */
function mytheme_form_alter(&$form, $form_state, $form_id) {
  // The language selector is only displayed if there is more than one language.
  if (drupal_multilingual()) {
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      if (count(element_children($form['locale'])) > 1) {
        $form['locale']['language']['#access'] = FALSE;
      }
      else {
        $form['locale']['#access'] = FALSE;
      }
    }
  }
}

In my module I also used hook_init() to change $user->language to a default value; differently $user->language would have the last value saved.

/**
 * Implements hook_init().
 */
function dul_init() {
  if (!user_access('change own user language')) {
    global $user;

    $user->language = language_default('language');
  }
}

Clearly, the Disable user language module has its own permission, which allows to select which users have the permission to select their own language, but that part is not strictly necessary.

I used hook_init() because the documentation for hook_user_load() has the following warning:

  Due to the static cache in user_load_multiple() you should not use this hook to modify the user properties returned by the {users} table itself since this may result in unreliable results when loading from cache.

The code is also changing on the fly a property for the currently logged-in user, without making any changes in the database. hook_user_load() would not serve this purpose, since it is invoked any time a module calls user_load().


cURL error (60) SSL certificate problem On my local Wamp, I am trying to import feeds using the Feeds and import.io modules.

Each time I get the following error:

  cURL error (60) SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed for https://api.import.io/store/connector

The error doesn't occur on my hosted environment.

I have looked HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK, and tried adding my php.ini files located in:

C:\wamp\bin\php\php5.3.0
C:\wamp\bin\apache\Apache2.2.11

Adding curl.cainfo = "C:/wamp/www/dev/curl/cacert.pem" doesn't get any result.

Locally you can disable the error by adding this to your curl options:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

This forces curl to not verify your local cert.


Views Filter by Field value (content type A) = Field value (content type B) I am getting exhausted trying to filter views by matching 2 fileds value from 2 different content types.

For Example:

Content Type (Employee A), with the following fields:

ID (integer)
Name
phone Number
Address

Content Type (Employee B), with the following fields:

ID (integer)
Position
Skills
Salary

What I need to do is a View that show

ID, Name, phone Number, Address, Position, Skills, Salary ... By comparing ID integer value from (Employee A) = ID integer value from (Employee B)

Please help me doing this.

Install Equi Join.

  The Equi Join module allows you to create relationships between
  different entities based on an arbitrary field. This allows the use of
  relationships in Views without having to add Node References to a
  content type, which may not be an option when displaying data stored
  on a third-party database or data provided through custom Views
  handlers. That said, it works with nodes as well.

I must confess, I have never used this module before now, so my method of getting it to work was by trial and error. Here goes:

In your view, add a relationship Equi Join: Content, and configure both left field and right field to be on field 'ID' (I am assuming you re-used the ID field for both Employee A and Employee B. If not, adjust as appropriate). Make sure to provide a unique Identifier (will be used later to identify the relationship).

Add all the fields from Employee A and Employee B. For each of the fields of Employee B, make sure to add the relationship of the equi join.

Add Filter Criteria for each of the fields (AND). For all of them, Operator must be Is not empty (NOT NULL). For each of the Filter Criteria using fields on Employee B make sure to add the relationship of the equi join. If you have a required field on any of the Employee Types, then adding just that one required field would be sufficient for that Employee Type. If none of the fields are required, then you might end up filtering out a legitimate row with empty values. So best if each employee type has at least one required field on it.


Custom module shows in list but not in permissions I have a simple module I created and it shows up in modules config panel and I have enabled it. The functions are called and the output even shows:

function products_help($path, $arg) {
  if ($path == 'admin/help#first') {
    return t('Products Help');
  }
}

function products_perm() {
  return array(
    'access products' => array(
      'title' => t('TBYT Products'),
      'description' => t('Administer TBYT Products'),
    )
  );
}

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

  $items['products/winnipeg'] = array(
    'type' => MENU_CALLBACK,

    'title' => 'Enjoy shopping in Winnipeg',
    'page callback' => 'list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

What am I missing? I cannot find this module anywhere under permission configuration...I expect to find the option for allowing "access products" to authenticated user???

Any ideas?

You need to implement hook_permission to register any custom permissions that your module exposes.

Once you have implemented this hook you can then use your new permission in user_access or hook_menu.


How to test any features that require authentication? I am just getting started with BeHat and I'm able to successfully run tests that do not require authentication. But, anything that requires authentication is failing.

STATEMENT  (or any logged in statement)

Fails with ERROR MESSAGE .

But, if I add 'not-logged-in' as a possible class for logged in, then the test passes. This tells me that I am not successfully logging in with my tests. The test is actually finding a class 'not-logged-in' when it is testing to see if it's logged in.

I am getting email notification that a user has been created when the test runs. So, I know that a user is being created, but not successfully logging in.

Feature: Authentication
  In order to make sure Behaviour testing is working
  As a behat test user
  I want to make sure I can log in

  Scenario: Anonymous access
    Given I am on the homepage
    Then I should see "Login"

@api
  Scenario: Test Being Logged In
    Given I am logged in as a user with the "administrator" role
    Then I should see the link "Test Link"

My behat.yml file looks like this:

default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      selenium2: ~
      base_url: http://mysite.localhost
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/Users/myfolder/sites/mysite'
      region_map:
        footer: "#footer"

As mentioned in my question, it was pretty clear that Behat was failing to login, so I began to look for modules that might interfere with the login process.

It turns out that we are using the module AntiBot (https://www.drupal.org/project/antibot) and when we disabled this module, we were able to run tests that involved successfully logging into Drupal.


How to implement review ratings with Fivestar? I want to build a rating functionality identical to what we can see on http://www.meineuni.de/ - there is a page of a product (or an University as in the example) and that page contains cumulative ratings taken from continuous ratings. A sample page is http://www.meineuni.de/uni/jacobs-university-bremen/bewertungen/

Business case: I want anonymous users to be able to create content of specific type and be able when creating the page, to assign ratings in several categories. This page will then be available online for other anonymous users to rate and the rating will be cumulated with the initial rating to show the weighted (initial+continuous) rating.

Is something like this possible with Fivestar in Drupal 7?

I want to find the right way from the beginning, instead of trial and error approach, which I don't mind, but that is more time consuming.

Yes, you can do it, you can combine the Views module with the Views Aggregator Plus or with the Views Calc module.

Views Calc:

  Adds simple calculations to a views table. You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).

Views Aggregator Plus:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

  ... and it puts summary statistics at the bottom of your aggregated
  table as well!


Problem with OAuth2 refresh token I have the following problem with the simple_oauth module.

I can get the initial jwt token with a POST request to /oauth/token with the following form data:

username: user
password: password
client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: password

This token has the actual access token and the refresh token. So I have an interceptor in Angular to refresh the token when we get a 403 return code. The call to refresh the token is again a POST request to /oauth/token with a slightly different payload:

client_id: xxxx
client_secret: yyy
scope: oauth
grant_type: refresh_token
refresh_token: def5020092674bfb5c570c518c112fbc78ec6ddb2d...

This call also succeeds but when I try to use the returned token I will get 403 returns. It is like the tokens produced using one grant type or the other have different scopes...

Have you experienced this problem? Do you know what can I do to solve it? Thank you very much in advance.

Status code 403 (Forbidden) does not mean that you are not properly authenticated. Since you received all tokens properly you are authenticated successfully. 401 Unauthorized means that you do not have a proper token, i.e. you are not authenticated).

If you receive 403 then you simply are not allowed to access the requested resource with the token you presented. The account you used does not have access privilege for whatever you are trying to access.

If I would have to guess:

Either you used the wrong account (e.g. Stage account used on Production) => use the correct account
Your account was not set up to access the endpoint. => talk to whoever created the account

Edit:
It comes down to "Authentication != Authorization" ("who am I" vs. "what am I allowed to do").


More Node Access Product (nap.module) Problems I have a client who cannot launch his website because of continuing problems with the Node access product module.

After a customer makes a purchase, they are prompted to login. Upon attempting to login they receive a white screen with the following message -

  "Fatal error: Cannot use object of type stdClass as array in
  home/mysite/public_html/sites/all/modules/nap/nap.module on line 824"

Have already looked everywhere for a solution. Any suggestions?

Try changing $purchases['product_vid'] to $purchases->product_vid on line 824. Issue has been created on the project.


Making a basic block in Drupal 6 I am trying to make a simple block to put out some HTML. However, my block is not showing.   This is what I have from putting it together from different pieces of code.

function blue_block_info() {
  $blocks['blue_block'] = array(
    'info' => t('Blue'),
  );

  return $blocks;
}

function blue_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'blue_block';
      $block['subject'] = t('Blue');
      $block['content'] = blue_content();
      break;
  }

  return $block;
}

function blue_content() {
  return '
this is a test
';
}

The code you are using above is for Drupal 7, not Drupal 6. In Drupal 6, it would be the following one.

function blue_block($op = 'list', $delta = 0, $edit = array()) {
  switch ($op) {
    case 'list':
      // code from your blue_block_info()

    case 'view':
      // code from your blue_block_view()

  }
}


Reference start date and end date for date field I'm trying show some text when it falls between a certain date, but I am having trouble referencing the start date and end date of the date field.

My code is:

$now = time();
$date1 = strtotime($date1);
$date2 = strtotime($date2);
  if ( $now >= $date1 && $now <= $date2) {
  echo 'This is a new video';

     } else {
  echo 'This is an OLD video';
     }

But it is not working because I do not think I am getting the value of the date in $date1 & $date2. My drupal field (named field_time) is set up as a Date (UNIX timestamp). I used the Devel Module to see where the start and end dates are held and it told me "date1" and "date2".

But my code above isn't referencing the field, so im suspicious. Am I referencing the correct date strings above?

If that is a node field, then the values you are trying to use are accessible using the following code.

$items = field_get_items('node', $node, 'field_time');

$from = $items[0]['value'];
$to = $items[0]['value2'];


Get menu link item from MenuLinkTreeElement Hey I am loading a drupal 8 menu in the following way:

if ($menu != NULL) {
    $tree = \Drupal::menuTree()
    ->load("my_menu", new MenuTreeParameters());

This returns MenuLinkTreeElement objects.
It does not seem possible to fetch the fields attached to the menu item.

How can I do that? Should I load the menu through another function?

You can get the menu link content entity by accessing the uuid with the method getDerivativeId() of the plugin:

if ($link instanceof \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent) {
  $uuid = $link->getDerivativeId();
  $entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid('menu_link_content', $uuid);
  $field_value = $entity->field_example->value;
}


How to enable user search in Apache Solr? I have Apache Solr running on my site, but would like to get it to index users as well as nodes, so that a single search request will bring up matching users as well as nodes.  What do I need to do to make this possible?  I found some pages talking about installing the Content Profile module to create nodes corresponding to users, which solr could then presumably find, but Content Profile doesn't seem to have made the jump to Drupal 7.  Is something like this required, or will Solr just do this once I tweak some configuration step that I apparently missed?

There is the Apachesolr User module, which has just a development snapshot release for both Drupal 6, and Drupal 7. It is used from 76 sites, 72 of which run Drupal 7.

Basing on the module description, it could suit for you.

  This module will add users to apache solr. It is compatible with the latest beta of Apache Solr search integration.
  It now exposes the User entity type as an indexable entity type so it can be indexed properly. All Apache Solr hooks are available to modify the way you are indexing users.

Looking at the issue queue for the module, I found Only users with the "Bypass content access control" permission are able to search for users when Apache Solr Access is enabled. Before using the module I would rather wait that issue is fixed. If you aren't using the ApacheSolr Access module, you should not have the issue reported there. That is what a user commented.


Post user location to a map I am building a site where people can log power failures in their area on a google map in Drupal 7.

I want to be able to have my site users register their location on their profile. This seems pretty straightforward to do using the Profile 2 and Location modules, however it's the next step that I'm hung up on.

I want the user to be able to click an "add a power failure" button, fill in the details of the failure (time, date etc) and hit save. Once this is done, I want to be able to plot a point on the map (using views or whatever) with the location details they entered in their profile when they signed up.

I've been trying to play with User reference and node reference in the power failure content type, but this doesn't really give me what I want.

Does anybody have any ideas on how I can accomplish this?

Thanks!

G

For the location to be displayed on the google map,You need to install few modules:-

Install GMAP and LOCATION module,
Install GEOLOCATION and its dependent modules.
Add a field in content type with field type GEOLOCATION  and widget type GOOGLE MAP.
With this, When the user will ad content,he will be able to mark the location of the area of the power cut on the map.
Refer this GEOLOCATION for further help.


Multiple copies of the same content shown due to voting I have made an image gallery using views. I want to create a vote option for each image. I used the Rate module and I've created a rate button which looks something like this

I used the yes/no widget and changed the option to this

In my gallery view I've selected the Content:Votes relationship and changed the
value type to options
and vote tag to normal vote

The problem is multiple copies of the same content appear in the gallery when the votes are increased. How can I fix this issue? or is there any other way to do this?

Hmm.. On the right side, go to Advanced, Other, then Query Settings.

Select the checkbox for "Distinct", and click Apply.

According to the help note:

  This will make the view display only distinct items. If there are
  multiple identical items, each will be displayed only once. You can
  use this to try and remove duplicates from a view, though it does not
  always work. Note that this can slow queries down, so use it with
  caution.

There are more options past that if it doesn't work.. making it more strict, for example.  But as the help note mentions.. this doesn't always work.


Content Type - Image able to link to other website I had create image field at content type. Without any views module or java-script, am I able create link to other website?

I am not using panel for my website. My question is ONLY related to CONTENT TYPE.

Example: When someone click on the image, it will link to www.google.com

Many Thanks.

you can do this by using any of the below modules :

Image Link Formatter

  This module is the result of the discussions around a requested feature
  to allow an image field to be displayed with a link to a custom URL

Image URL Formatter

  This module add a url formatter for image field. Then you can output
  image url directly.

  Most of the code, maybe more than 90%, is just copy from the drupal
  core. I think it is stable enough.

  I have created a content type, and add an image field instance to it,
  later i use views to export the data of this content type.And i want
  to output the data,then i could import it into another drupal 7 site
  with feeds module. What i need is the url of the image field, but i
  could not export the image url directly. That is why i create this
  small module.

Link

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


Change pager href attribute I'm new to Drupal and I've a 'pager' link that shows the second page of a block. It's href attribute is set to something like this '?page=0%2C1' I want it to be simply '#'.
It worked by setting $attributes['href'] to '#' in pager.inc but I'm not sure if I'm supposed to modify this file or not.

I think we've covered why this might not be a good idea in comments, but to change the output of the pager you just need to override theme_pager_link() in your site's theme.

You'll need to reproduce the original function almost exactly, except you'll probably want to ditch the use of pager_get_query_parameters(), and alter the url() on the penultimate line to use a fragment.


Echoing admin menu child items When you click 'Structure' in Drupal admin the page displayed is a print of the child items of the 'Structure' menu item.

I imagine this behaviour is relatively simple to achieve? I have a custom menu item using hook_menu but what do I need to do in page_callback in order to achieve the same results?

$items['admin/sponsorship'] = array(

    'title' => 'Sponsorship',
    'page callback' => 'system_admin_menu_block_page',
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
);

Seems to have done the trick.


Translating only Field labels I'm using Entity Translation and I've enabled "Enabled, with field translation" in a content type but don't want to translate each individual field.

It seems "Field translation" of i18n suit does it and in translate interface at admin/config/regional/translate/translate we can translate the field labels.

But the problem (as in the photo) is that it shows the same field text for all the content types sharing same field with same label. That is for same label I should be able to translate once only.

Is there any more simple way to translate field labels at once?

A similar question is here:  How to translate Boolean field labels? but seems to be more specific.

You need to download internationalization module and enable field_translation module which comes in this package. How to translate the field labels:

Go to manage fields. For ex. Articles, the path will be admin/structure/types/manage/article/fields/
Click edit for field_tags.
You'll see a translate tab there. I have attached the screenshot.
Translate field name and description there. It works.


How to theme webform in D6? I've got a website with a custom theme who was developed by an external group. I would like to custom the webform appearance.

In my form, there are grid fields. And these grid fields need to have a description. But in my custom theme, the description appears under the grid and I would like it appears just between the label and the grid. I hope you see what I mean.

In the theming.txt it seems that I have to edit the webform-form.tpl.php and save it to my theme folder. But in this file, there are only PHP code. So, how can I modify the HTML structure?

I found the solution.

Editing the template.php file of my custom theme and more specifically the theme_form_element() function. In that function, simply move these 3 lines where I want :

if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
}


drush: list of update-locked modules We excluded some modules from drush update (--lock=module_name). Is there a way to get a list of locked modules? A drush command or a file with the list?

There is no way to do this via Drush; the easiest way to find the locked files is with the find command:

find . -name ".drush-lock-update"


How can I alter the contents of a form before they are submitted? I'd like to do something like the following:

Let's say that I intended to allow users to input their Social Security Number, in the format 123-45-6789, which is a field in a "Person" content type. When saving to the DB though, I'd like to store this SSN as an integer. So, before the form gets saved, I want to remove the dashes. How can I do this? I can't find an appropriate hook that will allow me to alter the data BEFORE it is submitted. Adding a submit handler would not work, I believe, since this additional handler would trigger after the data is already saved.

EDIT: I'd now like to change this value before the individual element's #element_validate function is used. I tried changing the callback of this element's #element_validate function, but then the actual value isn't being changed before being submitted to the database, and I get an insertion error.

EDIT2: I'm attempting to use value_callback, but still having the same issue - either I'm using this incorrectly, or this is not firing before the element's validator. Either way, the result is that rather than attempting to insert "123456789" into the database, "123-45-6789" is attempted, and since this is an integer field, insertion fails.

You may be interested in form_set_value().  You would use this within the form validation function.  There are examples of its use posted below the API documentation in the comments if you need further clarification.

For help creating a validation function, see the Form API Quickstart Guide (D6) or How to use the Form API (D7).


Calendar module translation I have installed the Calendar module and would like to translate a few fields:

At the above screenshot, I'm looking for the day strings ("Sun", "Mon", "Tue", Wed",...). I've been searching everywhere, but can't find where they are located.

Where can I find these strings so I can translate them in the language I prefer?

Go to Administration > Configuration > Regional and language > Translate interface and search for !day-abbreviation. Then translate these strings to the language you prefer.


Fresh installation on the same server where another core version was installed gives error I have my own remote server to play around. I gave Drupal 8 a go but decided today to delete it from my server and install Drupal 7.56 again.

So I deleted all files via FTP and deleted all tables in phpMyAdmin, uploaded the Drupal 7.56 files from a fresh package I downloaded from drupal.org but ran into this issue:

When running through the process of install.php I suddenly get these 2 error:

Notice: Undefined variable: app_root in include_once() (line 690 of /var/www/clients/client1/web3/web/sites/default/settings.php).
Notice: Undefined variable: site_path in include_once() (line 690 of /var/www/clients/client1/web3/web/sites/default/settings.php).

So, after some Googling I found out it might have to do with the setting.php file of Drupal 8. The thing I don't understand is how this fresh install can search for the settings.php file of the Drupal 8 installation whilst I deleted every single file and table?

I checked my settings.php file of the Drupal 7 installation and there are only 648 lines, so I have no idea where to go searching...

After you install Drupal, automatically Drupal set sites/default to 555 and settings/default/settings.php to 444 , So it means they haven't deleted .

my suggestion is to change the permission for them, them delete settings.php (and make sure you delete it correctly ), and when you got insure of deleting everything Setup Drupal 7.56 again.


Panels visibility rule: Hide if value is in the query string I am trying to use a visibility rule in Panels to hide a block based on whether the query string has a parameter (value=5) or not.

Panels provides a String: URL path visibility rule by default, but this seems to only work for the URL path, not the query string.

Is there a way to add a condition to show/hide the block based on one of the parameters in the query string?

Using PHP code is not recommended unless absolutely necessary. You never want to store the PHP code in database, you do that in the modules :-)

I would recommend you to write an ctools access plugin for the same; check the logic there and give access to users accordingly.

Benifits:

The code is more maintainable, and can be version controlled.
You could reuse the same visibility rule throughout the site wherever necessary.

Please check my answer here, for an example of a working access plugin.


Secure Login not Working I'm running drupal 7 with the secure login module and login toboggan. After installing it, going to http://site.com I see the usual site, with the login button.

The login form action has not changed, it remains a POST to /node?destination=node. Sure enough, if I login there my password is sent in the clear with a POST to http://site.com/node?destination=node

Any ideas on how I might start debugging this? The securelogin.module seems really straightforward, just some hooks. Is there a logging statement I can add there to see if these hooks are being called?

update I also noticed this other problem (probably the same cause).

Sometimes when I start a fresh browser and go to http://site.com I get 302's to https://site.com automatically. If I then log in the POST goes over https (good!) but I then get 302'd back to http://site.com, where I appear NOT logged in. If I just change the URL to https://site.com I can see that I am indeed logged in.

I am very confused.

To force SSL for login, admin, node editing etc, I use http://drupal.org/project/securepages - also has has configuration options to force plain HTTP when browsing the site as well (which can save you load).


What are the steps to be undertaken while writing a .install file for drupal 7 module? I want to add an table to the database using .install file of a module. I am creating a completely new module which has not been enabled till now.
Which are the functions required in the .install file

function [HOOK]_install() {
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
//Should I write my query to create table inside this ...
    case 'pgsql':

   break;
}
}

function [HOOK]_uninstall() {
//Should I write the code here to remove the table after installation

}

as Clive says you should use hook_schema for creating your custom tables and then
hook_update_N
https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_update_N/7
for the updates of your tables module.


Working with data from a form I am trying to create a module with a simple form. The form allows the user to enter their address, from there I need to take the user's address, make a geocoding request, then send the data to another api, and then I need to display the data from the api request.
The part I am having issues with is taking the submitted address so I can do the requests with it. How do I take the data from the form so I can use it? I do not need or want to save the data into my database.

Thanks in advance.

In the form submit handler, look in the form state. The values array will contain submitted values.

So for a form element, 'foo', generated like this:

$form['foo'] = [
  '#type' => 'textfield',
  '#title' => t('Foo'),
];

You get the value like this:

function MYMODULE_form_submit($form, &$form_state) {
  $value_of_foo_field = $form_state['values']['foo'];
}


How can I get the real password via hook_user_update()? I want to change the current user password, and get the new password(the real password, not md5 encryption) when edit the account profile via user profile form(e.g.: example.com/user/1/edit) and save. would anyone can tell me how to do that? I tried using hook_user_update(), but it didn't succeed.

I mean I want to change the current user password, and I want to get the new password.

Implement hook_form_alter() (or one of it relatives) such that it array_unshift() a new submission handler to the user update form. The submission handler should add the password to the $form_state['values'] array. You also have to add the same key to $form_state['user'], because of the way user_profile_form_submit() calculates which keys from $form_state['values'] to pass as $edit to your hook_user_update() implementation.

If you did not insist on using hook_user_update(), I'd suggest handling your custom additions to the password update directly in your submission handler.

By the way, Drupal 7 does not use a simple MD5 hash to store passwords.


How to use Exposed Filter criteria form for Advanced forum I'm trying to modify my Advanced forum topic list Master view to have an exposed filter so that my users can search for topics.

However, after even a clean install with simplytest.me gives me the same problem: while entering a search query into the exposed form, the user will be redirected to the front page.

This is not a solution, but might help toward writing one.

I found that the redirected page url had appended something like this:

?sid[]=6

which, when I appended to the forum page url, worked as desired - filtering as desired. So the url is created without the forum page part, just appending the above to the main site url part.


Menu  href not working I've never seen this problem in Drupal 7, but my home link contains the string <front> within its href. It's not working.

Any idea what could be happening?

In Drupal <front> is used to make a link which points to home page.. If you are in home page even if you click on that link you will come back to same page..

You can find the documentation about it in URL API function where it says..

  The special string <front> generates a link to the site's base URL.

URL function converts href from <front> to ''. So you should get baseurl in href. I see you are using spanish language, may be special characters in <front> is causing issue.. Can you make sure front word is utf-8 english supported letters..

After carefully watching your screenshot i see you are using Void Menu module which is the root cause of your problem.. For solution see this issue in module Project Page..


Store token replacement values in the database rather than tokens themselves Is there a way to store the token replacement values of tokens put in a form field in the database rather than the tokens themselves?

I have a text field in a custom content type that has a token as default value (using Token Filter), [current-user:uid], so on node creation the replacement value is inserted into the node. In the database, it's stored as '[current-user:uid]', rather than as the replacement value. What is one way of storing the replacement value rather than the token string in that table?

The gist of it is to execute token_replace in a suitable location. Here's an example.

hook_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_with_replacements['und'][0]['value']);
    $node->field_with_replacements['und'][0]['value'] = $replaced_text;
  }
}


CRUD API from article I would like to create 4 api calls (GET/POST/PUT/DELETE) for the basic node article. I'm a real noob in this. Can someone help me on my way? Where do I go for information?

You will need the Services module, together with the REST Server submodule.

The two will allow you to create a new "server" and configure which entities can be retrieved via REST, what the authentication should be and which exactly calls are allowed (get, post, delete, etc.).


8 How to set a value for select list, While using $entity->set('field_name_type_select_list', ["Se_the_optional_value"]); Programmatically? The following line of code I am trying to use,

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function mymodule_node_update(EntityInterface $entity) {
  switch ($entity->getType()) {
    case "article":
      $entity->set('field_set_color', ["red","green"]);
      break;
  }
}

Why not able to set the value for a select list like this?

You can use hook_ENTITY_TYPE_presave as in hook_ENTITY_TYPE_update

When saving existing entities, the entity is assumed to be complete, partial updates of entities are not supported.

use Drupal\node\NodeInterface;

function mymodule_node_presave(NodeInterface $node) {

  switch ($node->getType()) {
    case "article":

      $node->set('field_set_color', ["red","green"]);

      break;

  }

}


How to skip client side validation for draft node? I am using clientside validation module for drupal 7.I have two button for submit node one is for save as draft and other submit so Now my scenario is that if i click on save as draft then it should not display client side validation error.

You can add a 'cancel' class to your draft button and it will skip clientside_validation, we do this out-of-the-box for the delete button, code can be found in clientside_validation.module, line 278


Relationship between node and other nodes related by node reference to same parent I've been stuck on this all day and I need help.

I have a video node that has a relationship (node reference) with a playlist node.

There are multiple videos referencing that playlist and there are multiple playlists.

Now here is my issue...

I have my node that plays my video and a view that lists all other videos in the same playlist to the bottom of the node. The views display plugin i'm using is EVA: Entity Views Attachment. This works apart form the fact I don't know now to filter it to only show a list of videos that are in the same playlist (referencing the same playlist node). I am able to get the ID or tokens (eg: field_video_playlist) from the video node and pass as an argument but when I setup contextual filter and relationships in the EVA view it returns nothing.

Without the contextual filter and relationship in the view it returns ALL videos.

Any help with this would be very much appreciated.

C

Start with a view that lists Content of type video.

In the ENTITY CONTENT SETTINGS use:

Entity type: Node
Bundles: Video
Arguments: Use the ID of the entity the view is attached to.

This adds the EVA field to all nodes of type Video and provide the node id to Views. I suppose you have gotten about this far.

Now add a contextual filter to the View, and choose the Content: nid. This value will be populated by EVA as just specified in the arguments. This makes the view aware of the node we are currently viewing. If you want to hide the current node from the playlist, you can select exclude hidden behind the more fieldgroup.

Then add a relationships from the playlist back to the video called Entity Reference: Referencing entity.

This includes all other video nodes associated with the same playlist in the view.

As you can see in my preview, when I view Video 1 (node id 2 because 1 was for the playlist), I see the other 2 videos in the playlist (I chose to hide the current node in the contextual filter).

If you DO want to include the current video in the view (you left exclude unchecked) it becomes a bit more complicated as you will need to use an extra relation: Entity Reference: Referenced entity. Then alter the other reference to use the reference of this one (you might have to change the order).

Then make sure all your fields and filter make use of the last relationship, so they display the title of the attached nodes and not the title of the initial node. It should look something like this:


Switching nodes no refresh AJAX What I have is a view that shows couple of nodes of type "product", they are related by an SKU ID.

What I'm trying to achieve is a way to switch between those related product produced by the view without refreshing the page.

Checking "Use Ajax" in my view did not achieve what I want.

Thanks,

i have developed module ajax_links_api which help you to load any drupal page to a specified div with help of JQuery Ajax.

in your tpl =>

    <?php  l_ajax($title, $path, $target)  ?>

$title: Title.

$path : Drupal path.

$target (optional): ID or CLASS of DIV to be replaced. Default value is .region-content, you can change default value in admin page 'admin/settings/ajax_links_api'

Example :

<?php l_ajax("Load node 1", "node/1", ".region-content") ?>

Hope you can use this for this case


Boost + Expire: Front Page not expiring from cache I am using Boost and Cache Expiration. My site generates nodes automatically and adds them via node_save(). I have setup Expire to get triggered on node insert, update and delete and to let the front page and the node page expire (see screenshot).
The problem is now: When the site is under high traffic, the front page does not get expired. When the traffic is low, the expiration works as it should.
I could reproduce this error even locally: While adding a node, I let wget constantly accessing the front page on my local host. As on the production server, the front page did not expire.
My hunch for the reason now is that the following happens within some milliseconds:

When calling node_save(), the new node get only scheduled to be saved but not saved yet.

The cache although, gets flushed immediately.

A new request to the front page is made, it gets delivered and its old version gets cached again.

The scheduled node save operation finally gets written to the database. But it has no effect to the front page, since it is already cached.

Do you think that my hunch is correct? If yes, what should I do? And if no, what could be the reason instead and what should I do?

You may try to add the <front> page to the rules action "Clear URL(s) from the page cache":


What consequences does "references in call_user_func_array are deprectated" have on form api? The documentation on call_user_func_array has a note, part of it quoted below

  Before PHP 5.4, referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference does not emit a deprecation notice, but it is nonetheless deprecated, and has been removed in PHP 5.4.

The function drupal_retrieve_form uses call_user_func_array in building the form, and has this comment shortly before the call:

  We need to pass $form_state by reference in order for forms to modify it,
  since call_user_func_array() requires that referenced variables are passed
  explicitly.

While I haven't hit any serious issues running PHP 5.4, it sounds to me like anything that builds a form and then relies on getting back a modified form_state will break on 5.4. I may not entirely understand what's happening here however.

What are the consequences for Form API of this PHP 5.4 change?

No expert, but here's my punt:

  Before PHP 5.4, referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference ... has been removed in PHP 5.4

means

function myfunction($a, $b) {
  $a++;
  $b++;
  print "myfunction($a, $b)\n";
}

$apples = 10;
$bananas = 20;

// PHP < 5.4: $b is passed by reference, not honouring the function signature
call_user_func_array('myfunction', array($apples, &$bananas));
print("apples: $apples, bananas: $bananas\n");
// PHP < 5.4: $apples = 10, $bananas = 21
// PHP >= 5.4: $apples = 10, $bananas = 20

and

  Furthermore, this does not apply to internal functions, for which the function signature is honored.

presumably means (though it seems a bit unnecessary?):

$angle = 1.5;

// Despite passing by reference, there's no chance of $angle changing as the
// function signature's honored for internal functions.
$res = call_user_func('sin', array(&$angle));

Letharion wrote:

  it sounds to me like anything that builds a form and then relies on getting back a modified form_state will break on 5.4

It seems to me like this should be fine, in this case at least: we're passing
a reference exactly where it's expected by the function signature (I presume this is still the right way to pass by reference where that matches the signature). However if I am right, then any modules with typos in their form hooks like this function MYMODULE_form_alter($form, $form_state, $form_id) will work exactly as expected under PHP < 5.4, but 'suddenly' mess up on 5.4.

@Letharion: in another answer you mention you have 5.4 running: I would've thought something would've exploded by now if it wasn't passing $form_state by reference? But IIUC if the following works as expected in 5.4, then the code you reference should be ok:

function myfunction(&$a) {
  $a++;
  print "myfunction($a)\n";
}

$a = 10;

call_user_func_array('myfunction', array(&$a));
print "a: $a\n";
// We expect a to be 11 the second time for all versions of PHP.

My 2 pennies


Quiz: Multiple choice question - Able to have the question correct with any correct answer I am using Quiz Module / Multiple choice. In one question, I have two answers correct and I'm hoping to have the question marked right, if any of the answer is chosen.

Right now, if both answers are chosen, only then the question is marked as correct by the module.

Thanks.

There is an option " Score if chosen and Score if not chosen " in multichoice question.

Set Score if not chosen = 1 and Score If chosen = 1

I hope, It would fix the issue.


Contextual views - show articles that the current user is interested in Aim
I am working on a Drupal 8 site that has articles which have a 'interests' field, and each User profile has a 'interests' field.
I want to create a view that only shows articles that the currently logged in user is interested in. For example, if the currently logged in user is interested in "Sports" and "Business", the view should show all articles that are tagged as either "Sports" or "Business".
Attempts
I presume that the solution will involve using Relationships and Contextful Filters. I have read about both here and here.
I have checked previous answers, and think this one is pretty close to what I'm trying to do: Display content having the taxonomy of the logged in user
However, I couldn't seem to get it to work for Drupal 8
Amends
Include of screenshot

1) Create users View

2) Add contextual filter of User ID

3) a) Add relationship of reference field

3) b) Checkmark require this relationship

4) a) Add relationship of Content with term

4) b) Checkmark require this relationship

5) Now in FIELDS it should allow you to add title field

6) Remove Name from fields.
7) Add FILTER CRITERIA of Published content

Overall, should look like this:


Dynamic filters based on another filter I am looking to create something similar to this http://www.smartoplug.com/partsearch I need my view to sort based off of multiple parameters. So if you select ford in the make, the models dynamically change to only show models that are referenced in ford i.e. F150, F250 etc.

I've looked into hierarchical select, and simple hierarchical select, but it doesn't look like what i am wanting to accomplish

Views Dependent Filters

Allows the presence of exposed filters on a view to be controlled by
values in another exposed filter. Dependent filters are hidden when
not relevant, and their values are not considered when the exposed
form is submitted.


Get current URL inside ajax callback? I have created custom module called mymodule.

In this URL localhost/mymodule/name, I have this field:

$form['name'] = array(
  '#title' => t('Enter name'),
  ...
  '#ajax' => array(
    'event' => 'blur',
    'callback' => 'mymodule_ajax_callback',
    'wrapper' => 'my-wrapper',
    'method' => 'replace',
  ),
  ...
);

My ajax callback is successfully called:

function mymodule_ajax_callback($form, &$form_state) {
  ...
  return ...
}

However, inside 'mymodule_ajax_callback', I need to get the current URL of the page which is localhost/mymodule/name. Currently it returns system/ajax which is how Drupal works by nature.

How to get the current URL inside the ajax callback?

As said by @Jayendra Kainthola
You need to store current path value in a session

$_SESSION['current_path'] = current_path();

Then use it inside your callback function as follows :

function mymodule_ajax_callback($form, &$form_state) {

$current_path = $_SESSION['current_path']  ;//gives the current path

}


Create a node(filedepot folder) after user registers in site Possible Duplicate:
  How to create new node programmatically, when a new user is created, in Drupal 7?

I am using Drupal-7 and Filedepot module. In Filedepot module a folder is created when we create node of filedepot folder content type.

I want to achieve that when any user registers in the site then one filedepot folder should be created.

Initially I used Rules module. And after registration I created a Rule to create a node of filedepot folder content type, but problem is that by using Rules I can't set some of the fields of content type. Node creation using Rules only creates node and sets title but it doesn't set the values of other fields.

Now I am planning to achieve it using other way, after user registers I want to create a node programmatically.

How can I customize Rule's node create action?

This is how I managed it, and there was one problem regarding permission in folder creation. So I just assigned permission to create folder. and here is the code to create folder during user registration

function modulealter_user_insert(&$edit, $account, $category) {
    $node = new stdClass();
    $node->type = 'filedepot_folder';
    node_object_prepare($node);
    $node->language = LANGUAGE_NONE;
    $node->uid = $account->uid;
    $node->name = $account->name;
    $node->title = check_plain($account->name);
    $node->filedepot_folder_desc[LANGUAGE_NONE][0]['value'] = 'This is private folder of author user.';
    $node->parentfolder = 4;
    $node->inherit = 0;
    node_save($node);
    watchdog('filedepot',"New folder created @name - new filedepot folder created.", array('@name' => $account->title));
}


Odd user login error For some reason on my site, if a user logs in using the user login block it will send them to the /user/ page to login where they have to type in their details again and it will log them in. It will redirect them here whether the initial details are correct or not.

This is also happening with the slipjaq module (slide down login panel) so I think it might have something to do with clean URLs. Do you have any idea?

Try disabling Clean URLs and see if it works.
If it does, it might be a problem with the module you are using.

Do this behavior also happen if you disable slipjq module?
If no, I recommend that you build this functionality yourself using jQuery. It would be easy.
If yes:

Have you created any alternative URL's pointing or coming from /user ?
If yes, try removing it.


Does requiring core/drupal load jQuery in custom script files? I am trying to understand a bit more about where and how jQuery is loaded in Drupal 8.

If I write a custom script file that will include some translation strings using Drupal.t(), I need to add core/drupal as a dependency.

I know we have a call for jQuery: core/jquery, but hoping to have a clear understanding.

Drupal core in places uses jQuery, does calling core/drupal include jQuery? When using Drupal.t()?

Is there a difference when doing so inside a custom behaviors wrapper?

The premise is if I write my scripts in vanilla js, will using core/drupal and/or behaviors still call any jQuery?

No, core/drupal depends only from core/drupalSettings; using it will not load core/jquery. The definition of those libraries is contained in core.libraries.yml, where  you can see their dependencies.

drupal:
  version: VERSION
  js:
    misc/drupal.js: { weight: -18 }
    misc/drupal.init.js: { weight: -17 }
  dependencies:
    - core/drupalSettings
  drupalSettings:
    suppressDeprecationErrors: true

drupalSettings:
  version: VERSION
  js:
    # Need to specify a negative weight like drupal.js until
    # https://www.drupal.org/node/1945262 is resolved.
    misc/drupalSettingsLoader.js: { weight: -18 }
  drupalSettings:
    # These placeholder values will be set by system_js_settings_alter().
    path:
      baseUrl: null
      scriptPath: null
      pathPrefix: null
      currentPath: null
      currentPathIsAdmin: null
      isFront: null
      currentLanguage: null
    pluralDelimiter: null


Field groups not showing when nested using field type HTML I'm using Drupal 7.34, Profile2 module, Field groups 7.x-1.4.

When building a form with nested field groups and using the fieldset field type, my form renders properly.

When I configure my form like this:

It renders into this, showing nothing but the Title and Save button:

There is nothing in the generated HTML as well, i.e. not hidden div's or something. The HTML markup just isn't there.

When I configure my form like this (changed nested fieldgroup element from HTML to Fieldset):

It renders into this, showing all:

My goal is to have some nested HTML elements, which I am able to style in a theme. Am I doing something wrong with nested HTML elements?

Thanks,
Eric

the solution and patch can be found here:
https://www.drupal.org/node/1503094#comment-11981615


Views: Sort By Global Math Expression Result? I have created a global math expression field in views, and I want to sort the results by the results of the math expression.

In particular, I use Drealty to connect to a RETS server and download property listings.  My local database gets populated with prices and number of bedrooms for each listing.  I want to sort based on Cost per Bedroom.

Any Ideas?

You can't sort currently by just using views but i would recommend to store
the value in the database.

Therefore create a computed field: http://drupal.org/project/computed_field
and do the logic in there to store the value in the DB. Once you have done this views will be able to sort by that.


How to restrict users to view their own custom content type? I am developing a custom module called 'serviceentry' which also exposes a custom content type called 'serviceentry'.

I also exposes the custom permissions as :

function serviceentry_permission() {

        return array(
           'view own serviceentry content' => array(
            'title' => t('view own serviceentry content'),
            'description' => t('view own serviceentry content')
        ),
        'view any serviceentry content' => array(
            'title' => t('view any serviceentry content'),
            'description' => t('view any serviceentry content')
        ),
        'create serviceentry content' => array(
            'title' => t('create serviceentry content'),
            'description' => t('create serviceentry content')
        ),
        'edit own serviceentry content' => array(
            'title' => t('edit own serviceentry content'),
            'description' => t('edit own serviceentry content')
        ),
        'edit any serviceentry content' => array(
            'title' => t('edit any serviceentry content'),
            'description' => t('edit any serviceentry content')
        ),
        'delete own serviceentry content' => array(
            'title' => t('delete own serviceentry content'),
            'description' => t('delete own serviceentry content')
        ),
        'delete any serviceentry content' => array(
            'title' => t('delete any serviceentry content'),
            'description' => t('delete any serviceentry content')
        ),
        'administer serviceentry' => array(
            'title' => t('administer serviceentry'),
            'description' => t('administer serviceentry')
        ),

        );
    }

Then, I check for permissions using following function.

function serviceentry_node_access($node, $op, $account) {
    $type = is_string($node) ? $node : $node->type;

    if (in_array($type, node_permissions_get_configured_types())) {
        if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
            return NODE_ACCESS_ALLOW;
        }

        if ($op == 'view') {
            if (user_access('view any ' . $type . ' content', $account) || (user_access('view own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
                return NODE_ACCESS_ALLOW;
            }
        }
        if ($op == 'update') {
            if (user_access('edit any ' . $type . ' content', $account) || (user_access('edit own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
                return NODE_ACCESS_ALLOW;
            }
        }

        if ($op == 'delete') {
            if (user_access('delete any ' . $type . ' content', $account) || (user_access('delete own ' . $type . ' content', $account) && ($account->uid == $node->uid))) {
                return NODE_ACCESS_ALLOW;
            }
        }
    }

    // Returning nothing from this function would have the same effect.
    return NODE_ACCESS_IGNORE;
}

Now, I want to restrict users to view nodes of serviceentry based whether they have 'view own serviceentry content' or 'view any serviceentry content' permissions. The above code is not working as Drupal is not passing $op='view' in order to restrict the user. If user has 'access content' permission, then all nodes are shown otherwise not. I want to have finer control over my own node type. How to do that?

When the implementation of hook_node_access() returns NODE_ACCESS_IGNORE, it is not denying the access to a node, but it is letting other modules decide if the user has access to the node. If none of the modules implementing hook_node_access() returns NODE_ACCESS_DENY, and none of the modules implementing hook_node_grants() returns 0 for the node, then the user has access to the node.


How to display custom news from other news providers? I want to show news from news providers of my choice to users on my drupal site. Imagine a horizontal news ticker block on the front page with individual news from different news providers. I am using drupal 7.50.

Some more details: I just want to know the way to grab/fetch/retrieve news from websites like cnn, al-jazeerah, etc of my choice to my drupal site and show them in a slider. For example yahoo has a nice news slider. I have views ticker and views slideshow modules, but it is not necessary I use them if other modules fulfill the purpose.

You could import RSS feeds from cnn etc as nodes or aggregate the feed using the feeds module


How to download from private// following a link? I have a custom entity (contract) created in a custom module (amap) by a bunch of BaseFieldDefinition, one of which being

$fields['file1'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Source file'))
  ->setDescription(t('Source file (may be modified)'))
  ->setSettings([
    'target_type' => 'file',
    'file_extensions' => 'doc docx odt pages',
    'uri_scheme' => 'private',
    'file_directory' => 'contracts',
  ])

I have a View about the custom entity that displays some fields in table mode:

The download action (the yellow arrow) is defined using Custom text with rewrite results, link path being {{ file1__target_id }}:
The link is something like mysite/system/files?file=contracts/Contract-4-20200408.doc (for example).
And following the link gives different results depending on the browser. None of them being what I want: the default filename proposed is not correct 'files' or 'file.dot' instead of 'Contract-4-20200408.doc' (in my example).

So I tried to implement hook_file_download. My code is

function amap_file_download($uri) {
  $sFileName =  \Drupal::service('file_system')->basename($uri);
  $sFileNameWithPath = 'sites/default/files/_private/contracts/' . $sFileName;
  $response = new BinaryFileResponse($sFileNameWithPath);
  $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $sFileName);
  return $response;
}

and there I get this error!

Notice: Object of class Symfony\Component\HttpFoundation\BinaryFileResponse could not be converted to int in Drupal\system\FileDownloadController->download() (line 51 of core/modules/system/src/FileDownloadController.php).
Drupal\system\FileDownloadController->download(Object, 'private')
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 693)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

What am I doing wrong?

Thanks to @Kevin, I updated my code to

function amap_file_download($uri) {

  $sFileName =  \Drupal::service('file_system')->basename($uri);
  return array(
      'Content-disposition' => 'attachment; filename="' . $sFileName . '"',
  );

}

And it works!


Redirect to page after Simple News subscription I wish to redirect the user to a specific page once they have inputted their email and pressed subscribe. Does anyone know how to achieve this please?

I have found the setting to achieve this but upon deeper digging it is not working. An issue has been opened here -> https://www.drupal.org/project/simplenews/issues/2822420

You do as follows:

  use Drupal\Core\Url;

function MODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'FORM_ID') {
    foreach (array_keys($form['actions']) as $action) {
        if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
          $form['actions'][$action]['#submit'][] = '_redirect_submit';
        }
    }
  }
}
/**
 * Add redirect to user after subscription.
 */
 function _redirect_submit(array &$form, FormStateInterface $form_state) {
    //If you know route name you can do like this
    $form_state->setRedirect(ROUTE_NAME); // example as "user.admin_create" redirects to user create page
    // If you have path do like below.
    $destination = "INTERNAL_URL";
    $url = Url::fromUri('internal:' . $destination);
    $form_state->setRedirectUrl($url);
 }


How to treat textfield as integer field while adding sorting in views? I have a textfield in my content type. It have values like 1, 2, 3, ..., 10. While I adding sorting it sorts the content like 1, 10, 2, ...

I can write the custom handler for it, But how can I treat it as integer in sorting while adding a query. Currently sort handler implements the following query :

$this->query->add_orderby($this->table_alias, $this->real_field, $this->options['order']);

What change I have to do?

Solved it by adding a custom handler and used CAST Functions of mysql and changing the query to :

$this->query->add_orderby(NULL, 'CAST(' . $this->real_field . ' AS SIGNED)', $this->options['order']);


Why am I getting a JSON dump when saving a node? I've read about this issue elsewhere and the primary culprit has been Views and the jQuery Update module...particularly having jQuery set to anything but v1.5. I'm getting the JSON dump when saving a node:

[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"my_theme","theme_token":"yyYQcgn3UELRKecX6yTsTIV8lKutRmg3bBIpqbjACzE"}},"merge":true}]

I need jQuery 1.7 for an image rotator that I'm using and I found a patch for jQuery Update that allows you to set the version of jQuery for admin and and front-end so I have 1.5/1.7 set respectively and yet I'm still seeing this issue. I have confirmed that jQuery v1.5.2 is being loaded. I do see that jquery.form.min.js v2.69 is being loaded from the jQuery Update module along with jquery.cookie.js...could these be causing the problem?

This is the URL after clicking save and seeing the JSON dump:

http://mydomain.com/views/ajax?title=test&sitename=&type=All&uid_1=&status=All&vid=All&language=en&__utma=1.98635126.1382890057.1383491752.1384184897.6&__utmz=1.1382890057.1.1.utmcsr%3D(direct)|utmccn%3D(direct)|utmcmd%3D(none)&Drupal_toolbar_collapsed=0&Drupal_tableDrag_showWeight=0&has_js=1&SESS0e1269226b42fa1c68bd46a4609d8d90=YIk12tixVnxuF9Om77vikXdp7Il8oxAYukuDswiCJoI&__utmc=1&SESSe5a8c6595a55e490f10153304dbfc1ee=El6m94kqyvIsFjx_IDJkC6-nujMMHCed4oVBpPNnvXA

The error only seems to occur when I edit a node after searching for it on the Find content page. I'm using the Administration Views module as well.

All modules have been updated as well as core (7.23). I have the jQuery admin overlay disabled in an attempt to solve the problem. Is there anything else I can check/do to alleviate this issue?

Now that the issue is repeatable, I disabled jQuery Update and still received the same JSON dump, so that's not the issue :s

We were having this same issue on our company website. We have Administration Views installed, and use jQuery 1.8 as default version and 1.5 for admin pages.

As SomethingOn mentioned above, we were consistently seeing the JSON dump after filtering on the Find Content view, editing a node then saving. The URL paths all had 'views/ajax' in the query string of the node edit URL; e.g.,

/node/XXXX/edit?destination=admin/content%3Fq%3Dviews/ajax%26title%3D%26type%3DAll%26author%3D%26status%3D0%26vid%3DAll

What I ended up doing was turning AJAX off (under Advanced > Other > Use AJAX) for the Find Content view (Administration:Nodes). This removed 'views/ajax' from the node edit paths and resolved the issue for us.


How and when to use filter_xss() and check_plain()? There are lots of template files like this one views-view-fields--magazine--magazine.tpl.php in my website. how and when I should use the filter_xss()  and check_plain() to improve security? for example this is the code:

<?php print $fields['title']->content; ?>

<?php print $fields['field_magazine_body']->content;?>

<?php print $fields['field_magazine_image']->content;?>

How do I can apply those functions in it?

First, read up about these in the Drupal API:

filter_xss
check_plain

So check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. &lt; and &amp; respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. The function filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. It does four things:

Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Both functions are used to sanitize data from users to make sure that any user injection is neutralized before the data is rendered on your site.

You never pass the same string through both.

If you use check_plain() then the string passed to the function is supposed to be used as plain text (not HTML). Then filter_xss() is not needed, since check_plain() will always make the string plain text.

If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() will mess it up.

When I look at the template you use as example, it looks to me as if all three fields passed to print() comes from content that is already sanitized, and need no more sanitation.

However, if you create your own module that collects user input without passing it through a "safe" text filter such as "Filtered HTML" or "Plain", you must use these functions for sanitation purposes.