How to assign a user a title based on the number of created nodes? I want to set up a system where a user is given a title based on how much content they have created/published. So, for instance, if the user has published:

0 nodes  - Noobie
1+ nodes - Poster
10+ nodes - Frequent poster
20+ nodes - Super Poster
50+ nodes - God`

I'm wondering if there is a way to implement this in a Drupal site. I can think of a way to do it using database queries and a computed field, but I'm wondering if there might be a more efficient way to go about doing it.

I doubt there is a module for this, but hey. Do not let that bring you down, it's actually a great idea for a custom module! If you have a bit of patience, Drupal is very easy to learn once you get past the initial learning curve.

If you need a start, the module developper section and the create a module page on Drupal are great place to start.

There are many, many ways you could do this, but to start I would probably create a small module. Imagine it's called super_usernames, for the purpose of this post. I would just create a folder in sites/all/modules called `super_usernames. That folder would need to  contain only 2 files:

super_usernames.info and super_usernames.module. The info file is very easy:

name = Super Usernames
description = Gives special credits to usernames depending on number of posts.
core = 7.x
files[] = super_usernames.module

The module file would need at the minimum just one hook to be defined.  Hooks are just plain old php functions that use a simple naming convention in order to be executed by Drupal automatically.

The hook you need here is hook_node_view. Basically you want to add :

/*
 * Implements hook_node_load
 */
function super_usernames_node_view($node, $view_mode){
  $supported_node_types = array('page', 'article', 'blog'); // Supports default content types
  if (in_array($node->type, $supported_node_types) {
    // query to get number of nodes this user has published
    $result = db_query("SELECT count(nid) as nodecount from {node} WHERE uid = %d", $node->uid);
     $row = db_fetch_object($result);
     $node_count = $row->nodecount; // Easier to read
     switch ($node_count){
       case $node_count >= 50:
           $node->super_username = "God";
         break;
       case $node_count >= 20:
          $node->super_username = "Super Poster";
         break;
       case $node_count >= 10:
          $node->super_username = " Frequent Poster";
         break;
       case  $node_count >= 1:  // same as > 0, but who cares...
           $node->super_username = "Poster";
         break;
       default:
           $node->super_username = "Noobie";
     }
  }
}

Now. After doing this, all your nodes should contain the dynamic value of the number of nodes posted by that node's author.  This would be added on the fly on every page load from content-types articles, and pages.

You still need to have it displayed somewhere, though! This is where you would ideally create a sub-theme (so as not to hack a base theme). But for the purpose of this post, we will simply modify one file: node.tpl.php.

Check the theme you are using, by default it is bartik but the procedure is mostly the same whatever theme you are using.

Go into your themes/bartik/templates directory, open the node.tpl.php file.  Locate where you want to add the super username in the html, and add this code snippet:

<?php if ($node->super_username): ?>
  <div class="superUsername">
    <?php print $node->super_username; ?>
  </div>
<?php endif; ?>

Now. One last step, you may need to clear the cache for changes to take effect. Devel module makes it easy, Drush makes it even easier. After this, you should have your super usernames dynamically shown on all the content-types defined in the supported_node_types array.

Hope this doesn't sound too complicated, it's actually quite trivial when you go through the process a few times.  Feel free to message me or repost here if you need any help.

Happy coding, cheers!

PS: This code has been slapped up from memory, nothing is tested but should be pretty close to a fully working example. Your mileage may vary, there may be typos in there.


Problems with workbench access I'm trying to configure Workbench Access.

I follow the guide, so I've two users of the same role that can add node to the "custom" content type, and they can edit own nodes.

Then I've added workbench access and add this two users to all sections.
But if I try to edit, with the user "one" a node owned by the user "two" I obtain an Access denied error.

The system tells me that the node is assigned to "Section one", but also if the user "two" is assigned to the "Section one", he can't edit the node.

Why?
Have I to set standard permissions to node in a particular way?
I haven't set the permission "Custom: edit any content".

To make sure I completely understand your question, I am going to restate it:

User B has created a node from a custom content type and it is assigned to Section One via Workbench Access. User A, who is also assigned to Section One, needs to edit User B's node but is currently unable to.

You're right in that you need to give people in that role the permission to "Edit Any Content" for that custom Content Type. You can access the permission page at admin/people/permissions, scroll to the "Node" section, find the specific content type in the list and select the proper permissions.

I don't know about what specifically you're trying to develop but I do have a couple of notes for you if it's still applicable to your situation.

First, you might want to consider adding a second role that only has the power to edit content from content types you designate in the permissions page. Using your example, let's say User B is assigned the role of "Author", meaning he can create content and edit/delete his own content. User A is assigned the role of "Editor", meaning she can edit any content User B has created but she cannot create her own. If User A needs access to edit content as well as to  create content, you can assign User A to both the "Author" role and the "Editor" role. This means that User B will not be able to edit any content generated from the content type except for his own (if he has the correct permission set for that).

Second, I would recommend taking some time to review the documentation for Workbench Access for more information on configuration and permissions.


How can I automate the site setup process during installation? I have this client requirement:

  While installing Drupal, user needs to do most of the configuration
  himself.

  Select the logo.
  Select the theme.
  Select the type of website he wants like blog, website, forum, eCommerce and when he does it, it should come along with its own configurations.

I know I need to use an installation profile. Is there any other way to do it? If an installation profile is the only way, then how can I meet all these requirements?

I recommend you take a look at NodeStream for examples. With a combination of install profile and Features, you do a great deal of setup during the actual install. You could either build on top of that, which is what we do at work, or you could use it for examples.


how to get the date value in drupal 8 On submitting a form getting error as

Error: Call to a member function format() on null.

Here is the function:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $exp_date = $form_state->getValue('expire_date')->format('H:i:s');
}

As mentioned by @awm in the comment you have to use the DateFormatter service. But the format() method needs a timestamp so you can use strtotime() to parse the value:

$exp_date = \Drupal::service('date.formatter')
  ->format(strtotime($form_state->getValue('expire_date')), 'H:i:s');


File structure of libraries folder and detection of module external plugins The module CKeditor anchor link require a CKEditor plugin.
Can this plugin be placed in subfolder of the /libraries folder or does it have imperatively to be placed at the root of /libraries ?
More generally, does drupal parse recursively the libraries folder when intenting to detect external plugins ?

The libraries folder is no longer managed by Drupal. The project Libraries doing this jobs in older Drupal versions seems to be deprecated in favor of a composer based concept. Modules still using the libraries folder use their own logic and you have to follow their instructions on the project page or README.


Gmap, Views Draw Lines on Field Collection Locations Map I have built a website for car tours. There are multiple tours throughout the year, and new ones are added regularly. Here is a quick outline of the website...

Content type: "Tour Page", Fields: Field collection item, allows multiple tour steps to be added. Each field collection item has a Gmap find address on map location field.

On each tour page, I have a view Gmap using a contextual filter to get a default value of Content ID from URL. This displays the tour steps as single icons. This view is in a block, and set to display on all "Tour pages".

I would like to draw a line on the map from point to point. It can be a straight line, going from point to point.

Now, I can edit the view, go to gmap settings, and enter my own lines using the macro for the view, like this...

[gmap line=#0000ff/5/45:51.512099,-0.15169000000003052 + 51.20086,3.2629389999999603 + 50.654685,4.833983999999987 + 50.403266,6.240233999999987 + 49.966239,8.18481399999996 + 49.067118,8.10241700000006]

...but this will output the same lines for this view on every tour page. But of course, the route is different for every tour.
Here is where I am so far...

http://www.dev.ducktoursinternational.com/tour/maranello-monaco-monza-grand-prix-tour-2009

...The line is on the map, following the points. But this same line is in the same place on every tour.

I have all of the latitude and longitude values for all of the points collection in the field collection location fields, is there a way to create a unique macro for every map using these values?

I can probably use a "master" view to assemble all of the lat and long values into the right format for a gmap macro, but how do I get that macro to apply to the different route on each page?

Some more information...
1. Here is the tour page with the current macro on it... http://www.dev.ducktoursinternational.com/tour/maranello-monaco-monza-grand-prix-tour-2009

Here is a screenshot of the gmap view...

Here is a screenshot of the views GMap Settings

So I have a block with a map, and a block with the correct macro for that page. How do I use that macro for that map?

off the top of my head a custom module using hook_views_pre_build or 1 of the views hooks functions should let you "alter" the Macro value from something you load and compose from the database.

To be of more help we'd need to see your full content type admin page with field collection admin page, and the master layout of the view for example if you wanted coding help ...


Filter for landscape format images in views I am working with Views 3 and Drupal 7 and created a view to display a list of images from a given content type in a slideshow. For layout reasons, images in portrait format don't work. Is there any way to filter for "width > height"?

One simple solution
in given content type, add a CCK (select list) field having  option "width > height". select this field when the image is landscape. then in views add this filter too.  by doing this, only images that are "width > height" will be shown


Get Path from node ID I'm using a twig template for a custom block that have images to link to specific nodes. I actually have the node IDs, however generating a relative link doesn't always work. Some pages are using aliases like so
127.0.0.1/web/products and some are using nodes like 127.0.0.1/web/node/19
so using the same relative link doesn't always work. Note that my drupal instance is within a /web/ folder and not at just 127.0.0.1

My twig template looks like this

    {% for key, image in imageurl %}

            {{ block_title[key] }}

    {% endfor %}

When it appears on 127.0.0.1/web/products the link is

http://127.0.0.1/web/node/15

When it appears on 127.0.0.1/web/node/19 the link is

http://127.0.0.1/web/node/node/9

The image has the same issue, since 'image' only contains the filename.
Is there a way I can automatically generate a link based on a node ID and a file that I know the path to, to account for URLs that may contain aliases?

You should use Drupal 8 classes to generate the link. If you get the nid from an existing node object you can do the following in the .theme-file of your theme:

function yourtheme_preprocess_block(&$vars) {
  $node = Drupal::request()->attributes->get('node');
  $vars['link'] = $node->toUrl()->setAbsolute();
}

In twig you can output:

    {% for key, image in imageurl %}

            {{ block_title[key] }}

    {% endfor %}

To generate the URL of your node just knowing the nid (here in variable $nid) you can use the following in your .theme-file:

function yourtheme_preprocess_block(&$vars) {
  $options = array('absolute' => TRUE);
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
  $vars['link'] = $url->toString();
}

Again you can use {{ link }} to output the URL where ever you need in yout twig template.


Create invoice when registrating I have a register form with some fields like name shop, btw number, subscription, ... . I want to create an invoice of the data filled in (do some operations with other variables). I know that there's a drupal module Invoice but how can I automatically create one when clicked on register button and send them to the users email? (I'm a drupal beginner)

I can't tell you the exact steps but I can suggest you some workaround for this.

You can use Rules module & create a rule for sending mail after event register.

You can send mail in action. Use Token for mail formatting. Maybe you will need some Mail related modules such as Mime Mail for sending mail.


Why would my hosting account user name show up in page not found errors in my logs? I'm running a Drupal 6 site and recently I've started seeing "Page not found" errors which contain the user name on my hosting server. For example "~username/blog/the-blog-post-title". I use Pathauto to auto-generate path aliases for new content. I've never really seen any problems like this before. I'm also seeing Page not found errors like "user/https://domainname.com/user". When I look at the log entry for these it usually says the path is "http://domainname.com/user/https://domainname.com/user". This is obviously a bad path! I recently enabled Secure Pages and I'm wondering if maybe this might have caused the issue. Does anyone have advice on what might be causing this or how to track it down? Unfortunately there's no referrer listed for these errors so it's tough to know where to look. Could it be something cached incorrectly?

Something is obviously refering "http://domainname.com/user/https://domainname.com/user" so I would search for the log entry for that access and follow the referrer further. I'm guessing something is generating a bad link somewhere. And something else follows that link (could be GoogleBot).


Why is $base_url = http://{$_SERVER['SERVER_NAME']} in settings.php? Will this cause any problems? I saw this on a legacy website and I am not sure why our sys-admin insists on doing it this way. While most things are working fine, I wonder how will this affect the site, for example, I know the $_SERVER is not defined on cli and every time I execute a drush command it gives me parse_url(http:///example): Unable to parse URL in drupal_settings_initialize() (line 718 of                                                 [warning]
path/to/includes/bootstrap.inc).

If the site is served by a single application server and that name will never change, then this isn't wrong, but not the way I would do it.

If you want to use SERVER_NAME and avoid issues if it's not initialized:

$base_url = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : '';

Or, instead of empty quotes, specify the server name if it doesn't change.


Where do I translate strings? Where is the interface for translating strings that modules pass to t(), in Drupal 7?

You can find it here "admin/config/regional/translate/translate"


Auto rendered images from external links I'm trying to make a functionality for users, so when they add a link in a body of some article(in text editor with other text), it displays as an image.
Any ideas?
Thanks)

CKeditor has the ability to add an image to a text field using its url:

  This module will allow Drupal to replace textarea fields with the
  CKEditor - a visual HTML editor, usually called a WYSIWYG editor. This
  HTML text editor brings many of the powerful WYSIWYG editing functions
  of known desktop editors like Word to the web. It's very fast and
  doesn't require any kind of installation on the client computer.


Is there a browser-side validation passed event I can listen for? Is there a JS event that my own custom code can listen for to determine that client-side / browser validation of a form has passed?
i.e. That no messages like this have occurred: "Please fill in this field" because a field was empty.

If there such an event that can be listened to then my own JS could handle the POST submission and then replace the form with a thank you message, in-situ / in place on the same page.
What I don't want to do is have my code run whether the form submission input by the user is valid or not. In other words I don't want to display a thank you message if they've not given valid data. That's why I need an event to say validation passed.
This to me is a better solution to say "thank you" rather than redirecting to content that can itself be indexed and accessed "outside" of the form submit situation, even if a module like rabbit_hole is used.
Looking for a Drupal 8 or 9 solution for myself but tagged with 7 to encourage answers for those who also might want an answer but for Drupal 7.

Drupal doesn't have a browser-side validation framework as it does with the back-end form validation handlers. The "Please fill..." message is the browser enforcing the required property.
If you'd like to hook into those validation events, you can bind event listeners on specific form elements for invalid events. If you want to take action on a submit click, the checkValidity() method can be executed on form field DOM objects.
See the MDN docs on the constraint validation API for more info.


Updating Drush to newer version on Drupalpro VM Virtual Machine Instance I'm setting up a new vm box with a fresh copy of Drupalpro and I need to update Drush and I'm not sure how to go about it. Any ideas would be great. The current drush version that is preinstalled is 5.3 drush.

Using a fresh setup of Drupal Pro VM image, all you have to do is just goto the drush directory and do a git pull from there to pull in the latest code from drush's repo. This is what i did:

cd ~/drush

git pull

git checkout 7.x-5.9

You can load up another drush version by just listing out the ones available by doing a git tag


Views Path Settings is not redirecting to particular path? I have been working on drupal 7.54 version.

I have created on sample view and trying to display the view in particular path.

Here, I have mentioned the path as comment-count, but its not getting redirected to the path, because its taking as query string.

How can I change this thing.

Is there any problem in latest instance or else guide me how to sort out this problem?

Go to /admin/config/search/clean-urls and enable the clean urls.

Then try these steps If clean Url test is failed.
enable mod_rewrite apache from httpd.conf

open httpd.conf
find mod_rewrite
just remove # to enable
once it enable then you can run Clean URL
this will show check box tick on it and save it


How to get nodes that do not belong to a particular user role I am getting custom entity nodes using entity queries like below:

  $query= $this->entity_query->get('order_entity')
      ->condition('external_id', $data['external_id']);

  $order_nids2 = $query->execute();

I am trying to put a condition where I can get nodes which do not belong to a particular user role. How can achieve this?

Nodes are only associated with author's nids (not user roles)

Thus you should do a query first to get the userids that match your selected user roles.  Then use that array to filter out nodes with authors that belong to those user ids.


Showing Details with Drupal Views 3 I have a table structure for fee details as

fid
name
description
currency
fee
instalments
created

This fee schedule has N no of instalments and storing in a cross ref table as

iid
fid
instalment_no
amount
payable_by

This fee schedule has associated students and are storing in a cross ref table as

fid
uid

I need to show the details of a fee schedule to end user with all installments and students. Is this possible to get this fee detail page using views 3.

Please help me to write the SQL to fetch fee details with students and fee instalments.

Thanks in advance for your help.

EDIT

One of my friend suggested me to create three displays in views each showing result from each table i.e. first display to show the fee details, second fee instalments and third to show the fee students. Then in page display all three views by using the functions views_get_view. Thanks Inian :)

While doing the way Inian suggested, I found attachment as a display type and that solved my problem and I don't have to write any custom code now.

Umar


Single on/off checkbox default value not work I have a boolean user profile field which is single on/off checkbox, says 'field_user_flag'. Its On value is 1 and Off value is 0. But I could not set #default_value = 1 from hook_form_alter to save "1" into its table field_data_field_user_flag and field_revision_field_user_flag.

When it is 0 and unchecked in user/*/edit, I would like to set it to 1 and checked. Thus, I did it in my hook_form_alter as below.

$form['field_user_flag']['#default_value'] = 1;
$form['field_user_flag']['#attributes'] = array('checked' => 'checked');

But, it did not work. I created the field in account settings (admin/config/people/accounts/fields/) without using Profile 2 module.

I tested it and worked for me:

$form['field_user_flag'][LANGUAGE_NONE]['#default_value'] = 1;

You can also set a default value of this field (in field settings in field managment).


pass php page to page callback with hook_menu I'm developing a module where I use hook_menu.

I know that I can pass to 'page callback' a function that return string with HTML/PHP code.

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

    $items['test'] = array(
        'title' => 'page test',
        'description' => 'my test',
        'page callback' => 'my_page',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
    );

    return $items;
}

function my_page(){
    return '
hello
';
}

How can I pass a whole PHP/HTML page as an argument to 'page callback' => '[my_page.php]' instead of creating a string inside my_page() function ?

The value to 'page callback' can only be a function name.

If you must use 'a whole PHP/HTML page' then work around by using the hook_theme.

<?php
function my_example_menu() {
  $items['my/example'] = array(
    'title' => 'My title',
    'page callback' => 'my_example_page', /* callback function */
'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
);

return $items;
}

/**
 * Implements hook_theme
 *
 */
function my_example_theme($existing, $type, $theme, $path) {
  return array(
    'the_html_page' => array(
    'template' => 'the-html-page', /* create file with this name + .tpl.php */
  ),
);
}

function my_example_page(){
  return theme('the_html_page');
}
?>

The value of 'template' in hook_theme() is the name of your file. Create the template file with .tpl.php extension and place it in the same directory as your module. You can put any html that you need in the file.


Display custom profile field in twig In drupal7 I used this code in my template file (node--article.tpl.php) to display the author bio. This is a custom profile field named field_author_bio.

<?php print user_load($uid)->field_author_bio['und'][0]['value']; ?>

In drupal8 I have the same setup.But I'm stuck how to do this with a twig template?

Any advise?
Thanks.

This is a user template from Drupal 8. Check detail here or below code.

{#
/**
 * @file
 * Theme override to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 */
#}

<article{{ attributes }}>
  {% if content %}
    {{- content -}}
  {% endif %}
</article>

Please see the comment code. If you want to render your custom field in template, just content.<your_custom_field>.
With your example is content.field_author_bio.

In case your field's content when rendering is not your expectation, you maybe need to use template_preprocess_user() for preprocessing content before rendering in the template (Search more about this function if you need).


What is the significance of dumping the tablespaces? While recently running drush sql-dump on a server where there were never any error messages, I have started to get:

mysqldump: Error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation' when trying to dump tablespaces

It still produces a file I can import locally and I don't seem to be having any problems. But I am still curious: What is the significance of dumping the tablespaces when it comes to the average Drupal sysadmin?
Environment

Drush: Drush Commandline Tool 10.3.2
Drupal: 8.9.13
DB: Server version: 5.7.31-34-log Percona Server (GPL), Release '34', Revision '2e68637'
Acquia Cloud hosted

Tablespaces are used to define the physical file location of one (or more) tables - chances are if you were using them for something beyond the default innodb space, you'd know about it. It's likely safe to ignore.
The error will have started when MySQL was updated to 5.7.something, they introduced a breaking change in a minor version because it addressed a security flaw, and world + dog was greeted with this error message.
There's a way around it:
drush sql:dump --extra-dump=--no-tablespaces


How to configure drush with Acquia DevDesktop on Windows to access through proxy? There are some answers to similar questions using WAMP, but now drush is not recommended under Windows (unless using DevDesktop, which I am). And this is seriously frustrating. I followed the instructions here and created a wgetrc file with the proxy addresses and use_proxy=on on d:\, then set up a wgetrc environment variable to point to d:\. Stopped and started DevDesktop to verify that the wgetrc variable is taken into account. But when i try to download a module (eg drush dl admin_toolbar), I get an error message:

  simple_xml_loadfile(): I/O warning : failed to load external entity Project.php:74 Failed to get available update data from https://updates.drupal.org/release-history/admin_toolbar/8.x

Following the comments below I tried again (twice). Once, with the env variable WGETRC set to d:\wgetrc, next with the file renamed to _wgetrc as suggested and the env variable set to d:. Neither worked, here is what seems to be the relevant wget output (obtained by redirecting the output to a file):

First attempt:

Wgetrc:
  d:\wgetrc (env)
  /etc/wgetrc (system)
Locale: /usr/share/locale
Compile: gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
  -DLOCALEDIR="/usr/share/locale" -I. -I/usr/src/wget/wget-1.12/src
  -I../lib -I/usr/src/wget/wget-1.12/lib -D__CYGWIN__ -DEILSEQ=138
  -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686
Link: gcc -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686
  -Wl,--enable-auto-import /usr/lib/libssl.dll.a
  /usr/lib/libcrypto.dll.a /usr/lib/libiconv.dll.a
  /usr/lib/libintl.dll.a /usr/lib/libiconv.dll.a -lregex ftp-opie.o
  openssl.o http-ntlm.o gen-md5.o ../lib/libgnu.a

Second attempt:

Wgetrc:
  d:\ (env)
  /etc/wgetrc (system)
Locale: /usr/share/locale
Compile: gcc -DHAVE_CONFIG_H -DSYSTEM_WGETRC="/etc/wgetrc"
  -DLOCALEDIR="/usr/share/locale" -I. -I/usr/src/wget/wget-1.12/src
  -I../lib -I/usr/src/wget/wget-1.12/lib -D__CYGWIN__ -DEILSEQ=138
  -O3 -fno-unit-at-a-time -s -march=i386 -mtune=i686

As far as I can see it is looking in /etc/wgetrc no matter what I do, which is not much use on Windows. In all cases I get this error still:

https://updates.drupal.org/release-history/file_entity/8.x [3.81 sec,16.55 MB]
Executing: wget --version
Executing: wget -q --timeout=30 -O "C:\\Users\\mknapp\\AppData\\Local\\Temp\\dow6C08.tmp" https://updates.drupal.org/release-history/file_entity/8.x
simplexml_load_file(): I/O warning : failed to load external entity    [warning]

I've even tried putting the wgetrc file in c:\windows\system32\drivers\etc but to no avail

You can follow this tutorial to install drush on windows.
http://www.drupal8.ovh/en/tutoriels/95/install-drush-on-widows

For the proxy you can try:

Controle panel -> System -> Advance settings -> variable -> variable system

PROTOCOLE_proxy  NAME:PASSWORD:HOST:IP

http_proxy http://192.168.100.100:3128

https_proxy http://192.168.100.100:3128

Example from :
http://www.drupal8.ovh/en/tutoriels/208/internet-access-via-proxy


Can I by pass the one time login page that forces a use to click "log in"? I'd like to send a user to a specific page on their one time login.  I'd also like to not force them through presentation of the page that says :

This is a one-time login for USER and will expire on DATE.
Click on this button to log in to the site and change your password.
This login can only be used once.
Log In

I understand  the redirection I want to do can be done on a form submission override on the Login button form. link

I'd like to achieve the redirection AND by pass the one time login page.

My intial though is that the onetime login page is essencial to the one time login process. Is that true?

Thanks in advance.

If you look at this: http://drupal.org/node/350634

You could try setting your own function for user_pass_reset: http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user_pass_reset/7


How do I set 'Locale settings' fieldset, in the user profile form, to uncollapsible? After running a dpm($form) via hook_form_FORM_ID_alter I couldn't see the 'Local settings' in the form defintion of the user profile form. I did a search for 'locale settings' on all the code and found the value I need to alter (I think) on line 2016 of system.module. So I tried:

function MY_MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['timezone']['#collapsible'] == FALSE;
}

Cleared the cache. Fieldset is still collapsible?

Found it!
The point is that your hook_form_alter is called before system_form_alter, so you don't see the timezone. You need to reorder the implementation of hooks with hook_module_implements_alter

Here is the full code:

function CUSTOM_MODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['CUSTOM_MODULE'];
    unset($implementations['CUSTOM_MODULE']);
    $implementations['CUSTOM_MODULE'] = $group;
  }
}

function CUSTOM_MODULE_form_user_profile_form_alter(&$form, &$form_state) {
  $form['timezone']['#collapsible'] = FALSE;
}

Credits to this post.


How to add an action button to item of content type page? I have a page which shows the details of an Event content type item. I added in my second sidebar a block which content a button. Here is a screenprint of what I have so far:

I want to use this button to update the status of the item (a field with machine name "field_event_status"). Before the validation I want to show a confirm popup.

Any help to get this to work?

It appears to me that you should start with using the Flag module, with a so called "global" flag. And configure your flag so that it would show an appropriate "confirmation" whenever such node gets flagged.

Next you could use the Rules module and create a custom rule like so:

Rules Event: A node has been flagged, under "Some flag" (= the flag's label).
Rules Condition: Entity has field (related to your field_event_status field), to make it available for further processing in subsequent Rules Events and/or Rules Actions.
Rules Action: Set a data value (related to your field_event_status field).

With that you have the mechanics (logic) in place, and the only think left is theming the flag link(s) to have them shown as buttons. If you wonder how to make that happen also, then have a look at my answer to "How to add a custom icon or symbol to a flag link?" (i.e. the Option 2 part of it).

Tutorials

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the Flag module. Especially these tutorials from it:

Creating global flags and listing flagged content in Views.
Triggering Rules with Flag

More info

Refer to Flag's Community documentation for (way) more details.


How ajax open a link of node in custom region? Please help someone who knows how to deal with this. I'm not the first day trying to realize this. But unfortunately nothing sensible on the subject on the Internet is not found.

By default in drupal when you link (example, http://site.domain/node/7) to page content of material is loading on a full page.
I need to make so that when you click on link (example, http://site.domain/node/7) first is loading the front page and then over it ajax loading content of material (/node/7) in custom region. How it can be best implemented? I would be grateful for tips.
I create regions in theme and them work well.

I don't have much time to write the example code for you at this moment, please try to digest the steps below. Let me know if you find some points which you don't understand.

Duplicate a new ajax endpoint (e.g. ajax/node/%node) fornode/%nodeinhook_menu`.
Alter the menu item 'node/%node' with custom page callback.
In the custom page callback, load front page content.
Load a custom JS file in the page callback.
In block admin, move a empty block to the desire region.
In the custom JS file, use l_ajax() to load the content ajax/node/%node to the target DIV.


Email notification based on purchased item I am working on the magazine site using Ubercart. In this site individual magazines can be bought or subscribed to. When a new issue of a magazine which the customer has subscribed to is created, I need to send a notification to all the customers who have subscribed to that magazine.

Can I achieve this using the messaging and notification module? Is there any other way?

Have you tried rules? The trigger would be when new content is added, and the condition would be that the content type is appropriate. Not sure how you've stored the data connecting subscribers to their magazine, but that will be needed for the action. I don't think you'll be able to do this out of the box (specifically I'm not sure if you can send an email to multiple addresses using rules) - so you might need to write a custom action.


How I can management private files My default download method is public, but I need save some file on private folder, I am doing this:

//...
$file = file_save_data($handle, 'private://example.zip', FILE_EXISTS_REPLACE);
//...

Now when I try show to download it:

//...
$file = file_load($file_fid);
$url = file_create_url($file->uri);

$output['download'] = [
  '#type' => 'markup',
  '#markup' => l(t('Download'), $url),
];

return $output;
//...

If I do click on the url, I get:

  Access denied. You are not authorized to access this page.

I am superadmin (uid = 1). How I can management those files for me and for others users?

For bypass Drupal permission, you can implements hook_file_download():

/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  if (someCondition()) {
    if (!user_access('some permissions')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}


How to specify the latest album in a images view? I am using node galleries. I've created a view where I display all the images that are of type "gallery_image". The problem is, I need to now get it to only show me the values for a specific album, where the specific album is whatever is the most recently created album.

So in this image:

First prize would've been if I could say:

operator : is equal to : value

And make the value something like [[LATEST_ALBUM]] and have that somehow magically figure it out. It would be easy to do if I could add PHP there.

Any ideas how to get around this?

I just ended up using "arguments" with a default PHP argument if one is not specified. The PHP code:

$res = db_query("select nid from node where type  = 'node_gallery_gallery' order by nid desc limit 1");
$res = db_fetch_object($res);
return $res->nid;

Works beautifully. Only side effect being that anyone that can access this view, can view other galleries using a parameters. But in my case that's not a problem.


Custom Placeholder Module I have created a custom module to create a few placeholders in form fields.  Unfortunately, I am having a little trouble with getting two of them to work.  The code I have in the module is as follows:

function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if ($form_id == 'user_account_form') {
    $form['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    $form['pass[pass1]']['#attributes']['placeholder'] = t( 'Password' );
    $form['pass[pass2]']['#attributes']['placeholder'] = t( 'Confirm Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount[min]']['#attributes'] = array('placeholder' => array(t('Min Price')));
    $form['commerce_price_amount[max]']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }
}

(In order) The search block placeholder texts works perfectly.  The login placeholders also work perfectly.  The register (user_account_form) placeholders are not working at all, and I can not figure out why.  And the views_exposed_form works for the title and sku, but not for the min and max price range?

I need helping figuring out what I did wrong on the register form, and the min/max view filter price range fields.

EDIT:  I have gotten everything to work except the registration passwords.  When I uncomment the line for the password fields, they are no longer displayed on the page.

    function solid_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['search_block_form']['#attributes']['placeholder'] = t('enter search terms');
  }
  if ($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['name']['#attributes']['placeholder'] = t( 'Username or Email' );
    $form['pass']['#attributes']['placeholder'] = t( 'Password' );
  }
  if($form_id == "views_exposed_form"){
    $form['title']['#attributes'] = array('placeholder' => array(t('Search by Title')));
    $form['sku']['#attributes'] = array('placeholder' => array(t('Search by SKU')));
    $form['commerce_price_amount']['#process'][] = 'placeholders_process_commerce_price_amount';
  }
  if ($form_id == 'user_register_form') {
    $form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
    $form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );
    //$form['account']['pass']['#process'][] = 'placeholders_process_password_confirm';
  }
}
function placeholders_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}
function placeholders_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}

The user account form stuff is one level up in the account container. For the name and email you can use:

$form['account']['name']['#attributes']['placeholder'] = t( 'Username' );
$form['account']['mail']['#attributes']['placeholder'] = t( 'Email Address' );

The password is slightly more complicated, as the 2 inputs are created in a process function. You'll need something like:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'user_account_form') {
    ...
    $form['account']['pass']['#process'][] = 'MYMODULE_process_password_confirm';
  }
  ...
}

function MYMODULE_process_password_confirm($element) {
  $element['pass1']['#attributes']['placeholder'] = t( 'Password' );
  $element['pass2']['#attributes']['placeholder'] = t( 'Confirm Password' );
  return $element;
}

See form_process_password_confirm() if you're wondering where 'pass1' and 'pass2' come from (it's one of the default process functions for a password_confirm element as set in system_element_info()).

It'll be the same sort of thing for the slider, but without knowing where that slider comes from (module, custom code, etc) it's difficult to say what the code should be. At a guess based on the input name's you're trying to target:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  ...
  if ($form_id == 'views_exposed_form') {
    ...
    $form['commerce_price_amount']['#process'][] = 'MYMODULE_process_commerce_price_amount';
  }
  ...
}

function MYMODULE_process_commerce_price_amount($element) {
  $element['min']['#attributes']['placeholder'] = t( 'Min price' );
  $element['max']['#attributes']['placeholder'] = t( 'Max price' );
  return $element;
}


referencing/linking to an entityform and passing nid/other field information through the URL Thanks in advance for any help with this - I feel a bit like I'm down a rabbit hole.  I know there must be several ways to do this, but I'm running into some obstacles.

I'm trying to set up an event registration, but for various reasons, Entity Registration, Node Registration, and Signup don't work for what I'm looking for.  I have a content type "event," and I'd like to link to an entityform to allow anonymous users (not registered on the site) to sign up for events.  Ideally, information about the event would pass through the url or through using references to the entityform and populate the Event field and the Event Type field.

I tried using node reference URL and entity reference prepopulate, but ran into some major issues trying to reference/link to the actual entityform, as opposed to creating new content through a link.

I'm using entityform because of views integration, because I don't want anon folks to have to create new content (i.e. have a content type "registration" and have them create new ones to sign up), and also because I'm validating their email against an email collected through another registration form (volunteer registration, and I can't do that with the anon_email field in Entity Registrations.

One caveat - I'm building this site for a tiny non-profit, without the resources to do any real development in the future, so I'm trying to find a solution using features that already exist (or mostly exist).

Thanks so much for any suggestions/pointers! I've been stuck on this for a while now, and I know I'm probably just missing something big.

EDIT:

Found an inelegant solution by passing info through the url.   entityformurl/?event=[node:nid] did the trick. (Where my field name is event). If there is a better way to do this, I'd love to hear it.

I finally figured out how to get everything I wanted to happen, and figured I would post it here in case anyone had similar difficulties.  Entity reference prepopulate + a views block that links to my event registration entityform.  This blog was extremely helpful: https://wunder.io/blog/simple-contact-form-per-content-item-with-entityform/2012-10-24 .

One tricky thing for me was getting my taxonomy terms to be recognized by an entity reference field.  The only field option I had was "Content: All taxonomy terms," and entity reference taxonomy term fields will only recognize the taxonomy id in the url.  So, I used views to rewrite the output of the  content: all taxonomy terms field as [term_node_tid-tid].

Really effing love tokens, views, and entity reference prepopulate right now!


How to validate a field value programatically in Drupal 8? I've created a module for Drupal8 that checks against values in the user register and set an error if the values do no match with something you have entered in a custom form.

My module has got a form where you add a list of username you don't want the user to take and a custom message to display as an error.

Forms works perfectly, I can store data, edit it etc... It is stored under src/Form/ and settings are under config/install

Now when I'm trying to hook the user register form validate I got an error regarding form_set_error():

  PHP Fatal error:  Call to undefined function form_set_error()

Also I think I'm not using $form_state in the right way (but it does the job)

Here's the code in my_module.module:

function my_module_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#validate'][] = 'my_module_user_validate';
}

/**
 * Custom validation function.
 */
function my_module_user_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // get module settings
    $config = \Drupal::config('my_module.settings');

    // Convert $form_state to an array as it has been passed as object, it looks wrong but I could not find any documentation at the moment
    $form_state = get_object_vars($form_state);
    $name = $form_state['values']['name']);
    $usernames = $config->get('my_modules_usernames');
    // Username are inserted in a text area separated by an enter key
    $usernames = $usernames != '' ? explode("\r\n", $usernames) : array();
    foreach ($usernames as $username) {
      if ($username == $name[1]) {
        //apparently in Drupal 8 form_set_error does not work anymmore
        form_set_error('mail', $config->get('my_module_message'));
      }
    }
  }

The $form_state now become a classed object as documented here

You can use getValue() to get field value instead of converting it into an array

$form_state->getValue('name');

instead of:

$form_state = get_object_vars($form_state);
$name = $form_state['values']['name']);

Same thing for form_set_value.

And form_set_error() became $form_state->setErrorByName().


How to print all values of a multi-value field, except the first? Suppose that in a Twig template, I want to print the first value of a multi-value field, then something else, and finally all other values of the same field. Is there a way to do that?

I know how to get the first value of the field, but I don't know how to exclude that first value from the place where I'm printing all other values.

This is what I tried, but doesn't work:

{# print first field value #}
{{ content.field_foo.0 }}
{# print something else #}
<hr>
{# print remaining field values #}
{{ content.field_foo|without(0) }}

Alternatives for the last line that didn't work either:

{{ content.field_foo|without('0') }}
{{ content.field_foo|without('field_foo.0') }}

Looking at the code in twig_without(), I would expect {{ content.field_foo|without(0) }} to work, but instead the entire field disappears.

In field preprocessing this while loop which fills the field items doesn't get started if the first delta is removed:

  $delta = 0;
  while (!empty($element[$delta])) {
    $variables['items'][$delta]['content'] = $element[$delta];
    $delta++;
  }

So if you bypass the field template to print the 0 delta do the same with the other deltas:

{# print first field value #}
{{ content.field_foo.0 }}
{# print something else #}
<hr>
{# print remaining field values #}
{% for key, item in content.field_foo if key > 0  %}
  {{ item }}
{% endfor %}


How predefine templates for webform email templates? I need to have a bunch of different webform e-mail templates with different text - how do I create those with code in Drupal 7?

Ok, I got this sorted out, I used hook_form_alter to get the stuff into the select field, and did an override on the javascript-file from the webform module. I will try to answer it more complety in the next days if I have the time to do so.


Show custom banner per page Admin user wants to be able to upload image banners and select on which pages/nodes/views/panels to show it when visited (as a wide screen image banner above title).

It means when creating the banner node and uploading the image, there should be some field or list of pages to select from. But e.g. Views pages has no NIDs.

I kind of came up with a solution with Panels, where you just add field for your Article content type and upload the banner and then display it via Panels, so it would show above Title, etc. But it works only on node pages, but not Views pages. And that's still very limited, it means you need to add the banner field to every content type and still no solution for Views pages.

Is it possible somehow to have some type of a field that would autocomplete the path/node nid/view path when entering keywords and would be also separated by comma for multiple paths/pages and then render it via Views using contextual filters and output the view display via Panels?

There are a few ways of going about this... and I have literally done dozens of formulas for it since Drupal 6.

The way I usually go about this is with Bean (Drupal 7). Create a new Bean that will represent your banner, add some fields - then let the admin create the bean. Since it is based on blocks, you can set content type visibility or path visibility, and if you add Context (if you need that muscle) you get a lot more options.

Another way to do it, which is hard to describe in a comment, is to setup an entity type for banners (since they are not content), add the fields you need, and then on the node level, add an entity reference field. Create a view that displays the entity type in a view mode of your choosing, and base it on the ER relationship value. As you said, this won't solve Views pages, which is why you might want to stick with the block route. This formula is a little similar, as it entails relating whatever banner entity the user wants to the given node, and, you can set a default value to one banner if you need that option.

Yet another way to do it is to put a Field Collection representing banner components (title, link, image), and hide the Field Collection from the node rendering. Create a View, feed it the node id contextual filter, and have it render the node in a 'Banner' view mode, which will only hold the field collection. Then just theme that level of templates, and you're good to go.

The first way (with Bean) seems like your best option, whereas the second two put the creation aspect in the node form, but you lose a way to set them on non node pages (since the Views arg will fail). Blocks won't care what the page is made up of, as long as the path or visibility rule matches.


Need Steps to Install multisite configuration using only drush. i.e multi-site install having different database I need a help to install multi-site setup using only Drush that have multiple/different databases.I have already installed a site using drush but when I do the same steps for install another site into the sites folder using drush it gives me an error to delete previous database. I want instead to install another site that having same code base but different database.

Install site in /var/www/html/abc
Install another in /var/www/abc/sites/xyz.com

Gives error.

Try:

drush site-install --db-url=mysql://USER:PASS@localhost/DATABASENAME --sites-subdir=sitename

You may also need to add --db-su and --db-su-pw if necessary to provide the right credentials to create the database if the user specified by USER:PASS does not have permissions to do this.

See drush help site-install for other useful optional options you might want to specify, e.g. site name, admin account details and so on.


user login form: name and password default values Currently, when the user is loggged out, on user login form, the username field is filled with text, which probably is taken from a cookie (not sure) - it is the name of someone who logged in before. The password is also filled with dots, representing previously logged in password.

How to prevent it, i.e. always display username and password fields empty?

P.S. Why I need this? Because the requirement is that in the user name box there is a placeholder behavior with text "Username". (HTML5 placeholder). I noticed that it works well when the browser has no username remembered and does not work at all when the browser remembers the username and password.

Usually, it's the browser that remembers login names and passwords, allthough some sites place a cookie upon successful login that they use to populate the username field on your next visit.

I don't think Drupal does this by default so I think in your case, it's the browser that remembers the login name and password.

There is one way to avoid this and that's by changing the name of the form fields. Browsers 'know' to remember usernames because the name of those fields is usually something like 'user', 'username' or 'login'.

If you change the name attrribute of the login input field to, say, 'bycicle', browsers will stop remembering those values automatically.


Migrating files from multiple paths with the migrate module I am trying to take a bunch of files and turn them into nodes that link to those files in my system. Now when I say a bunch I am talking about thousands, if not tens of thousands of files. So I need a way to do this which includes using multiple directories as the source. Mainly one directory with multiple sub-directories to recurse through.

So I decided to go with the migrate module. In my module setup that creates the migration script I have a schema declared for an intermediary table. This table will hold all of the path information for each file I want to import.

I then (in the install function hook) loop through the image directory recursively and gather a list of file names and paths. Then I stick the information into the intermediary table. This table is what I then import from.

The only problem is that when mapping the file fields I am unable to figure out how to get it to get the source path from each entry. It seems to want me to specify a flat path where all the files will reside and that won't work.

Is there a way to get it to get the full source path from the intermediary table?

This is using Drupal 7 and Migrate 2.2.

Here is the mapping information I am trying. The jpg_uri field is where that source path should be coming from (I just can't seem to figure out how to make that happen).

$jpg_arguments = MigrateFileFieldHandler::arguments('',
  'file_fast', FILE_EXISTS_RENAME, NULL, array('source_field' => 'jpg_name'),
  array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));

$this->addFieldMapping('field_image', 'jpg_uri')
     ->arguments($jpg_arguments);

I believe you need to pass NULL as the first argument to arguments() instead of ''.

$jpg_arguments = MigrateFileFieldHandler::arguments(NULL, 'file_fast', ... etc);


How to set which entities a workflow for Content Moderation applies to? On Drupal 8.3, I enabled the Content Moderation and Workflow modules.

This provides an example Editorial Workflow by default.

The Content Moderation documentation states:

  Once your moderation workflows are established, you can apply the
  workflows to different entity types. Out of the box Content Moderation
  can be added to Block Content and Content (Node) entities. The
  "select" button will allow you to select which types should use this
  workflow.

However, there is no "select" link on the workflow edit page.  The screenshot on the documentation page shows This workflow applies to, but out of the box that information is not displayed.

Where can I select which types of entities a workflow applies to?

This is supported from Core 8.4, so you have to upgrade your site.  Then it shows up in the UI normally.


Hook after creating content I want to add some specific treatment after creating the content.

Rules module is for similar cases but I look for a hook.

Is there a hook that triggers just after creating content (node)?

Thank you

You can use hook_node_presave, it is called right after creation and edits.


How to Reload a Custom Drupal Theme (Without the Command Line) How do I reliably reload a custom Drupal theme I am developing without access to the command line? Just clearing the caches before I perform the load only works sometimes.
FWIW, we are promised command-line access in the future (security issues yet to be ironed out) but not anytime soon.

The steps that so far work reliably for me with Drupal 8.9.1 to load a custom theme again without command-line access are:

Install and enable the Devel module. (You will only need to do this once.)
Put your site into maintenance mode.
Turn on Devel -> Settings -> Rebuild the theme registry on every page load.
Clear the caches.
Load the new copy of the theme from Appearance -> Install new theme -> Upload a module or theme archive to install.
Clear the caches.
Reload one of your pages to verify your theme changes.

The second "Clear the caches" (6) might be redundant.
So far, this has worked like a champ once I figured out all of the necessary steps.


How to use Hansel Module? I was asked to use the Hansel breadcrumbs module to derive the breadcrumbs in a site, but I hardly understood the flow of the module. I cannot get a clear picture even from the modules documentation. I would appreciate any help to clarify my doubts about this module.

I have removed a custom breadcrumb module, and installed the Hansel breadcrumbs module.
I want to create breadcrumbs in specific page like Home->Bussiness->Faq and so on.

How is this possible with the Hansel breadcrumbs module?

"Switch on node type" is like a switch($case){} statement in PHP (and other languages).

After selecting "Switch on node type" in Hansel, you will need to provide the *machine_name* of the node-type in the "Name" field that Hansel presents.  For instance, you can enter one of the following in the "Name" field:

article -- will target Article nodes
blog_entry -- will target Blog Entry nodes
webform -- will target Webform nodes
<default> (for remaining node types)

If it were in code, it would look something like:

switch($node->type) {
  case 'article':
    // Make an article crumb
    break;
  case 'blog_entry':
    // Make a blog-entry crumb
    break;
  case 'webform':
    // Make a webform crumb
    break;
  case '<default>':
    // Do something for everything else...
    break;
}

"Switch on path argument" works the same way... but, instead of providing a node-type in the "Name" field, you should enter the path-argument you're targeting, such as:

node (to control breadcrumb on pages with a path like node/*)
taxonomy (i.e. for taxonomy/term/* pages)
admin (i.e. admin/* pages)
blogs (i.e. blogs/* pages)

$path_arg_1 = arg(0);

switch($path_arg_1) {
  case 'node':
    // Make a crumb for node/* pages
    break;
  case 'taxonomy':
    // Make a crumb for taxonomy/* pages
    break;
  case 'admin':
    // Make a crumb for admin/* pages
    break;
  case 'blogs':
    // Make a crumb for blogs/* pages
    break;
}

It seems Hansel can only target the first path-argument.  Also note that <default> seems to only work for "Switch on node type".

To create Home->Bussiness->Faq->How To Tie a Tie (assuming Business is a tax-term and Faq is node-type):

First Rule (for the breadcrumb's head, i.e. "Home" link)
Create a rule with the name start, and leave "Parent" set to <root>
Under "action with breadcrumb", select "add a single link"
Set "Action" to "switch", then click "next"
Enter "Home" as your link name, then set path to <front>
Select "switch on url argument" and click "save"
Second Rule (for the breadcrumb's tail, i.e. node-title: "How To Tie a Tie")
Create a rule with the name finish, and leave "Parent" set to <root>
Under "action with breadcrumb", select "add link to current page"
Set "Action" to "leave", then click "next" and "save"
So far, these two rules will get you: Home->How To Tie a Tie
Third Rule (for the second crumb, i.e. taxonomy term "Business")
Create a rule with the name node, and set "Parent" to -start
Under "action with breadcrumb", select "add term path"
Set "Action" to "switch", then click "next"
On the next page, select the vocab containing the "Business" term
Set "Switch on" to "node type"  then click "save"
Fourth Rule (for the third crumb, i.e. node-type "Faq")
Create a rule with the name faq (for node type "FAQ"), and set "Parent" to --node
Under "action with breadcrumb", select "add link to nodetype"
Set "Action" to "Goto rule", then click "next"
On the next page, configure the "Path" as desired
Set the "Goto Destination" to -finish then click "save"


Drupal 7: Help me to wrap my head around EVA/reverse node reference What I wanna do shoult be quite easy but but till now I've been without luck. I've read different approaches but none of them worked for me.

Setting: Drupal7/Views 3.6/References/EVA

We have 2 node types:
"article" (e. g. "How to sleep better" and "What your dreams mean")
"theme week" (e. g. "Sleep")

"theme week" has a node relationship field which points to the "article" node type (i. e. theme week "Sleep" has references to "How to sleep better" and "What your dreams mean").

Now I want to show that referenced articles in my "theme week" node which reffers them. I use EVA to attach a view to my "theme week" node.

Problem: I can't get to set up the view properly; my guess is that I'd use a reverse relationship to my reffering node "theme week", but till now I haven't been lucky with that.

Any advices (step-by-step) would be highly appreciated! Do I have to set up a contextual filter as well? Which fields/filters must use the relationship?

Thanks in advance to everyone
sp

OK, i did it. Here's how:

Node types:
I've set up 2 node types "article" and "theme week".
"theme week" has a node reference field where nodes of the type "article" can be choosen.

View:
 - I've set up one "EVA" view (requires EVA) Under "advanced", I've
   selected the relationship to my "article" node type.
 - I did NOT set "require relationship".
 - Unter "contextual filter" I've set "Content: Nid", "Provide default value -> Content ID from URL".
 - I've set all my fields and filter criteria to use that relationship

Display Suite/EVA: - I've attached my View as a field in my "theme week" node type (requires Display Suite/DS).

Now when a "theme week" node is viewed, it shows the "article" nodes which have been referenced by "theme week".

I hope this might be useful to someone!


Login user programatically (Create user session) My question is based on this question: Programmatically User login not working i dont have this clear, to login an user (create an active session) only need use User::Load()? i'm triying make this on my custom module, due to i need an independent login and register form, but dont work. Someone can help me? i want create a user session and let the user navigate for all sections that your role have assigned, but without pass by "user/login" route. Thanks in advance. On resume i want emulate the login controller shipped with drupal 8.

User::load() loads information about an account, it does not inject or alter the current session in any way. user_login_finalize() is one of the key functions when doing programatic user logins because it will create and set a session for the current user.

See more:
https://api.drupal.org/api/drupal/core%21modules%21user%21user.module/function/user_login_finalize/8.7.x


Why doesn't 'drush cc all' work? I installed Drush, but most of the commands doesn't work, I guess. I tried drush cc all and got the following output:

  Command cache-clear needs a higher bootstrap level to run - you will need invoke drush from a more functional Drupal environment to run this command.
  The drush command 'cc all' could not be executed.
  A Drupal installation directory could not be found

drush status outputs the following:

  PHP configuration     :  /etc/php5/cli/php.ini
  Drush version         :  4.5
  Drush configuration   :
  Drush alias files     :

You need to rebuild cache with Drupal 8, rather than clear it:

drush cr


get value from content type B, in a view of content type A i have a content type named songs. among other fields, it has a field named title of the song, which has as its field type the Node reference. i also have a second content type named songsTitles which keeps all songs' metadata, where there is for instance the duration of the song, the producer, etc. how can i retrieve in a view that i have created for the content type songs, instead of the node reference value, for each song, its duration instead? I would prefer to do it via the Views gui, since whatever i tried with code was not successful.

To retrieve information linked through ER fields you have to add the Relationship for the ER field.
The Relationship will open new options you can add to your Views.
You will be able to add the Duration Field to your Views after you add the Relationship. That field will use the Relationship by default (it wouldn't work without it).


How to append an HTML tag to a field? On the basic page content type, we have a paragraph field that is set to Plain Text with Link field and below are the paragraph type's fields.

How to append a  to the field so that it is displayed right at the end of the field?

Fields:

Description (type = text (formatted, long))
Link (type = link)

Current

Twig template:

{{ content.field_description }}
{{ content.field_link }}

Sample output:

Dramatically create 24/7 paradigms via ubiquitous information.

Read More

Goal

Twig Template:

{{ content.field_description }}

Desired Output:

Dramatically create 24/7 paradigms via ubiquitous information. Read More

What we tried and got stuck. When we tried to print the $pr_description field using ksm(), we could not find a method or array where we could append the link to:

mytheme.theme

function mytheme_preprocess_paragraph__plain_text(&$variables) {
  $pr_plain = $variables['elements']['#paragraph'];
  if(!$pr_plain->get('field_link')->isEmpty()) {
    $pr_link_field = $pr_plain->get('field_link')->first();
    $pr_link_uri = $pr_link_field->uri;
    $pr_link_title = $pr_link_field->title;

    $pr_description = $pr_plain->get('field_description');
    ksm($pr_description); // this did not provide method or array such as `#suffix`
  }
}

You are using "Text formatted" for your description field, so the
 tag is most likely part of the field value (an editor also could enter

Dramatically create 24/7 paradigms via ubiquitous information.

 in that field). It will be much easier to achieve your desired output if you change the description field to plaintext or unformatted long.


curent language token on block body what is the token used to get the curent language, I want to use this token on a link in the block body, like that:

About us

I find this token [site:url] is good, but in default language the link become //about-us two slashes, otherwise /fr/about-us in the french language(good).


How to implement an enumerated field using hook_schema()? I need to have a field in my database that is shall hold a limited set of enumerated values.

The MySQL ENUM type is not one of the predefined Drupal data types.

So how do one implement a field to hold enumerated values using hook_schema?

I understand that I can do it with a tiny int, but how do I map from and to the strings of enumerated values (e.g. "zero", "one", "two", "three") to integers stored in the DB?

If you are using the Form API to accept this data, you can map integers to string values.

You can also store that mapping array in your .module file.


Why are there "updates" to dev versions of modules that do not include any changes to the code? When I used drush to check for updates to my site, which has about 100 modules installed, I was informed that the dev versions of several versions of the modules had updates.

However, when I updated the new version, the only thing that was changed was the packaging information and datestamp.

For example, this is the git diff for the Prepopulate module dev version:

-; Information added by drupal.org packaging script on 2013-05-25
+; Information added by drupal.org packaging script on 2013-10-01
 version = "7.x-2.x-dev"
 core = "7.x"
 project = "prepopulate"
-datestamp = "1369450574"
+datestamp = "1380623732"

That's it-- no actual changes to the code.  If this was just one module, I wouldn't think much of it.  However, I had several modules like this-- the Role Expire module, Views PHP module, PHP Mailer module, i18nviews, and there may be more.

It's pretty frustrating for me to download each of these updates and do a diff, only to see that nothing has changed.  I feel that I am really wasting my time.  Are the maintainers doing this?  Does this have anything to do with Drupalcon?

Strange, I selected some modules at random and I see dev versions consistently packed 2013-Oct-01. I can't find any one with another date now.

Examples I've tested:

https://drupal.org/project/views_data_export
https://drupal.org/project/views
https://drupal.org/project/prepopulate
https://drupal.org/project/imagecache_actions
https://drupal.org/project/file_entity_revisions
https://drupal.org/project/file_download_count
https://drupal.org/project/scald_file

and many more.

Edit: Some of them, closer to the beginning of alphabet, was packaged one day earlier:

https://drupal.org/project/elysia_cron
https://drupal.org/project/blocktheme

but operation big as this surely needed to take considerable time and it still looks like one long rebuild queue.

With so many unrelated projects repackaged at the same day, and without any correlation to their GIT log, it must be something on the Drupal.org side that triggered mass repackaging.

It's simply impossible that all maintainers decided to rebuild at the same day, plus as far as I remember only way to trigger for them rebuild is via GIT anyway.

GOT IT

https://drupal.org/node/2101175#comment-7919049

  -dev releases are currently being rebuilt ... working alphabetically, and there are a lot of packages, so it will take a while. :)

So it was a manual rebuild triggered to fix an issue with infrastructure, not something planned as regular action.


How to configure boost for multisite configuration I installed the Boost module in my site. The site is running on multisite configuration having subdomains like

http://site1.example.com

http://site2.example.com

http://site3.example.com

http://site4.example.com

After enabling the Boost module in all subdomains. And also edited the .htaccess rule generated for a subdomain.

in the document root www.example.com/public_html/cache/normal i can see 4 directories and relevant  cached pages for each sub domains inside these directories
site1.example.com
site2.example.com
site3.example.com
site4.example.com

But cannot see the boost comment at the end of page in any subdomain. In short I would say "Boost module is not working". Am I doing right boost configuration for multisite configuration. Actually I don't know what extra stuffs is needed for boost to work in multisite configuration

here is my .htaccess generated rule for each subdomain placed in .htaccess file in root folder

  ### BOOST START ###

  # Allow for alt paths to be set via htaccess rules; allows for cached variants (future mobile support)
  RewriteRule .* - [E=boostpath:normal]

  # Caching for anonymous users
  # Skip boost IF not get request OR uri has wrong dir OR cookie is set OR request came from this server OR https request
  RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]
  RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]
  RewriteCond %{HTTPS} on [OR]
  RewriteCond %{HTTP_COOKIE} DRUPAL_UID [OR]
  RewriteCond %{ENV:REDIRECT_STATUS} 200
  RewriteRule .* - [S=3]

  # GZIP
  RewriteCond %{HTTP:Accept-encoding} !gzip
  RewriteRule .* - [S=1]
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html,E=no-gzip:1]

  # NORMAL
  RewriteCond %{DOCUMENT_ROOT}/cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html -s
  RewriteRule .* cache/%{ENV:boostpath}/%{HTTP_HOST}%{REQUEST_URI}_%{QUERY_STRING}\.html [L,T=text/html]

  ### BOOST END ###

Boost works out of the box with multi-site. If your cache files are being generated (they appear in /cache/normal/site1.example.org/), but not served (boost comment in the footer of the page, or X-Cached-By in the HTTP headers), then there is an issue with your .htaccess configuration.

You can debug your htaccess rules by enabling the rewrite log:

RewriteLog "/tmp/rewrite.log"
RewriteLogLevel 2

This can generate a lot of logs, use with great care in production.

Also check this post on how to debug htaccess rules:
https://stackoverflow.com/questions/9153262/tips-for-debugging-htaccess-rewrite-rules


How can I output a field as link? I have a title field and some date fields in my view in the following order

1.title

2.from_date

3.to_date

Since the title is long, I have trimmed and it is a known bug that the links don't work after trimming.

So how can I add a link to the title so that when I click on it, gets redirected? Please help somebody.

I have found a solution for the problem. Follow the steps.

Add a field 'Path' above the 'Title' field.
Exclude 'Path' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as {{ path }}.

OR

Add a field 'ID' above the 'Title' field.
Exclude 'ID' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as /node/{{ nid }}.

It both works.


How to use hook_init in a custom module? I am trying to use a hook_init within my custom module to add a js file. The problem is I do not see where the script is being called or executed on the front-page.

/* Implements hook_init. */
function hook_init() {
  if (drupal_is_front_page()) {
      drupal_add_js(drupal_get_path('modules', 'myInfo') . '/myScript.js');
  }
}

name = My Info
description = My Info Evaluation.
core = 7.x
version = 7.x-0.1-dev

I even tried to remove the hook_init and referenced the JS within the module info, but no luck. What am I missing here?

Some suggestions:

Is the module enabled? Silly question, but I've forgotten to do that before.
hook_init implementations won't get called until you clear the cache. Did you clear the cache?
I will sometimes put a drupal_set_message('this line'); in various parts of the code to see if that's getting called. In situations where a drupal_set_message isn't helping, I sometimes will put a asdf() so I can get a "fatal error, call to undefined function" message. Then it's really clear whether or not the code is getting called.
If the hook_init is not being called and the module is enabled and cache was cleared, then it's probably mis-spelled. The function should be named based on the name of your module: If your module is mymodule.module then the function name is mymodule_init().
It's possible that the path you are using isn't quite right. Does the file really exist there? I would try: drupal_set_message(drupal_get_path('modules', 'myInfo') . '/myScript.js'); so you can see the path and confirm that it's right.
There's some good documentation on Managing JavaScript in Drupal 7 though perhaps you've already read that page.

Good luck!


Display the amount of the order on the block cart do you know how to display the amount of the basket next to the number of elements?
As this page http://demo.commerceguys.com/cart

thank you

/**
* Returns the title of the shopping cart menu item with an item count.
*/
function commerce_cart_menu_item_title() {
global $user;

// Default to a static title.
$title = t('Shopping cart');

// If the user actually has a cart order...
if ($order = commerce_cart_order_load($user->uid)) {
// Count the number of product line items on the order.
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$quantity = commerce_line_items_quantity($wrapper->commerce_line_items,             commerce_product_line_item_types());

// If there are more than 0 product line items on the order...
if ($quantity > 0) {
  // Use the dynamic menu item title.
  $title = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping   cart (@count items)');
 }
 }

return $title;
 }

In Commerce Kickstart, you're actually looking at a view. The footer of the view displays a line item summary:

You can read through the handler's render() function to see how it actually gets that information.


After disabling and uninstalling memcached module, I get this PDOException and WSOD? I´ve cloned my production site in a local Xampp installation.
My site has Memcached installed (in the server and I´ve got the drupal memcache module installed).

But I´ve got this error at my local site:

  You must enable the PECL memcached or memcache extension to use
  memcache.inc

(this is repeated at least 30 times, so that line is printed about 30 times at the top of every page).

Now, I´ve disable and unninstalled memcache at my local installation, and the error is still there.

I´ve tried after that deleting the additional settings added to my settings config file:

  $conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
  $conf['cache_default_class'] = 'MemCacheDrupal';
  $conf['memcache_key_prefix'] = 'memcache_sitio';
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

But if I do eliminate those lines (after I´ve uninstalled -not only disabled- memcached module), I get WSOD and this error:

  Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc:2139
  Stack trace: #0
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2139):
  PDOStatement->execute(Array) #1
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(664):
  DatabaseStatementBase->execute(Array, Array) #2
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc(2318):
  DatabaseConnection->query('SELECT expire, ...', Array, Array) #3
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(167):
  db_query('SELECT expire, ...', Array) #4
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\lock.inc(146):
  lock_may_be_available('schema:runtime:...') #5
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\bootstrap.inc(405):
  lock_acquire('schema:runtime:...') #6 C:\Users\Victoria in
  C:\Users\Vic\Desktop\XAMPP\htdocs\drupal\includes\database\database.inc
  on line 2139

Please note that I´ve deleted all cache, tried disabling (and enabling) all performance options, and I´ve run run cron more than once.

What should I do? Thanks!

Each time I saw the "Mysql server has gone away" error, it was caused by the max_allowed_packet setting (in the my.ini setting file) that was too small.


Commerce Order id as seletion list in view filter and limit to 10 I am trying to make Order id as selection list exposed filter but couldn't make it possible.
I modified default order view by making clone, added block to view.This view block will be presented to the authenticated user where he can view his/her last 10 orders.

In views sort criteria order date is added which is in descending so that only most recent orders are fetched
Pager setting  - Use pager: Display a specified number of items | 10 items

Order's details has to be shown when user selects any order no from select list.
Is it possible to make selection list of Order id?Is there any module for that?

You can do it in views.

Add a new view for the product display type.
Add a relationship under "Advanced -> RELATIONSHIP" with the product, something like "Content: Referenced product", check "Require this relationship".
Add a filter in "FILTER CRITERIA" & choose "Commerce Product: Product ID" by help of added relationship, expose this filter.
Show it wherever you want, like you can make tab in the profile page etc.


Pass a logo to image module How do I pass the logo on my theme to the image module to create different sizes? I'm using domain access to I can't use

<?php print theme('image_style', array('style_name' => 'thumbnail', 'path' =>'public://new_ctrl_logo_front1_1.jpg')); ?>

as I'm using domain access and using one theme for use on multiple sites. I found this code on another form that works on my theme and need to know if I can pass an image style through it.

<?php
if (theme_get_setting('toggle_logo')) {
$image = array(
'path' => theme_get_setting('logo'),
'alt' => 'my logo',
);
print theme('image', $image);}?>

Thanks for helping,
Gregory S.

Update

If one needs to obtain "JUST" the filename for theme logo for the active theme for any given domain in a domain access environment (as the OP found he needed to do), then the following code provides the image file name for the theme logo as $img_file.

$global $base_url;
img_path = theme_get_setting('logo');
$str_to_remove = $base_url . '/sites/default/files/';
$img_file = str_replace($str_to_remove, '', $img_path);

Original

Pass "theme_get_setting('logo')" as the path for the first php script?

<?php print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo'))); ?>

or rather - an amalgamation of the two -

if (theme_get_setting('toggle_logo')) {
print theme('image_style', array('style_name' => 'thumbnail', 'path' => theme_get_setting('logo')));
}


Access denied for the user #1 I'm getting a 403 error everytime I try to log in with the user #1.

What can I do to get access again?

I have already tried to:

clear all cashes (via Drush)
set the time in both the server and Drupal's timezone, to be sure it isn't a cookie expiration problem

The problem began after I uncommented and defined a wrong $cookie_domain, in settings.php. (I needed this set up for FCKeditor/CKFinder.) Once I have corrected this, I've managed to log in again.


How to add multiple value field in webform I want to add a file field called picture to a webform, and Want it to be a multiple value field to allow users to upload more than a picture

Webform Multiple File Upload allows user to upload multiple files on a webform and you can also limit the number of files, see the below image.


CSS fix for stacked gear icons in Drupal Panels? When using the Panels module within Drupal, I often end up with multiple gear icons stacked on top of each other, inaccessible to the Drupal admin.

For example, take a Panels page with this structure:

MyCustomContentPaneTop
A Drupal View
MyCustomContentPaneBottom

When logged in as a Drupal admin, I can access the gear icon for MyCustomContentPaneBottom easily.

However, when I try to edit MyCustomContentPaneTop, I can only see an "Edit Panel" gear icon. I can see that this originates with this code, toward the bottom of the page.

  Configure

      Edit Panel

I can see in the HTML source that the gear icon does exist for MyCustomContentPaneTop, but it must be sitting in a z-index below the Panels gear icon.

Configure content pane

  ...

I know I can hack around with very specific CSS rules that apply only to pages where I discover this issue. However, is there an easy Drupal (or CSS) method to say, "If two gear icons are stacked on top of one another, stagger them by 5 pixels?"

Here's the minified version of that same Javascript, from said coworker. :)

jQuery(function($){l=[];t=[];$('.contextual-links-wrapper').each(function(){h=$(this);o=h.offset();k=o.left;v=o.top;if($.inArray(k,l)>-1&&$.inArray(v,t)>-1){h.offset({top:v+=50})}l.push(k);t.push(v)})});


Use Rules to notify original author when their node is published In short, I'm simply looking to notify the original author when their node goes from a non-published state to a published state. I have Workbench Moderation enabled if it makes a difference.

I've tried implementing the exact solution that was provided / accepted here (https://drupal.stackexchange.com/a/159103/79465) but can't get it to work for some reason.

Solved for with the following config:

Rules is great, but sometimes also tough to debug if things don't work as you'd expect. In your case, either something unexpected happens in your Rules Conditions, or there is some error in your Rules Action.

There are some typical facilities to do such debugging (further detailed below), but a Keep-It-Super-Simple technique I often use, is my BINGO-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

If the above doesn't help, then there are typically 2 ways of more advanced debugging, as further detailed below.

Rules Evaluation Log

Within the Rules settings, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "Rules Evaluation Log" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

More info

For way more details about these 2 variations, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


How can I tell if I'm on a taxonomy page in preprocess_page? If I'm on a node, inside preprocess_page(&$variables), I can check

if (isset($variables['node']) && $variables['node']->bundle() == 'my-type')

to see if I'm on a node, and a node of a certain type.

Then I can get field information with

$variables['node']->field_icon->entity->getFileUri()

How can I do the same thing for a taxonomy term page to know that I'm on a taxonomy term page and get the field values?

Unfortunately I don't think there is anything that the hook gives you directly that you can use in this instance. However you can always check the route name to determine if you are on a taxonomy term page.

// Will be "true" if you are currently on a taxonomy term page.
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {

  // Since this is a taxonomy term page, you may wish to get the term ID.
  $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}


Status message "The changes have been saved" displays when updating user data using AJAX and Services module I am using navigator.geolocation.getCurrentPosition to get the user's current location, and then using the Services module to update the user's location (part of the user object) via AJAX.

Here is the AJAX call to the service:

jQuery.ajax({
  type: "PUT",
  url: "/api/internal/user/" + uid,
  data: JSON.stringify(geolocation),
  dataType: "json",
  contentType: "application/json",
  success: function(r) {
    console.log(r);
  }
});

The update works just fine, but when I navigate to another page afterwards, I get the status message: "The changes have been saved". After some digging, I found that this status message gets displayed any time user data is updated, which is fine usually, but will be confusing in this scenario since data is being updated behind the scenes. I'm assuming that since the user update is taking place via AJAX, the status message doesn't get displayed until next page load.

Is there any way to prevent Drupal from displaying this status message only when user data is updated using Services?

On your menu callback function ( at /api/internal/user/%user ) you can call drupal_get_messages('status');. This will clear the status messages displayed to the user. A better approach would be to check the message first:

$message = drupal_get_messages('status', false);
if( $message == t('The changes have been saved.') ) {
  drupal_get_messages('status');
}

If this is not a custom module, you should build one and use hook_page_alter() like this:

function yourmodule_page_alter(&$page){
  if(arg(0) == 'api' && arg(1) == 'internal' && arg(2) == 'user') {
    $message = drupal_get_messages('status', false);
    if( $message == t('The changes have been saved.') ) {
      drupal_get_messages('status');
    }
  }
}


Search API / Facet API hierarchy based on taxonomy term reference across vocabularies With Search API + Facet API it is possible to create search facets for taxonomy term reference fields, that reflect the hierarchy of terms in the vocabulary, based on the taxonomy_term_parent table. (With Facet API Taxonomy Folding it is even possible to browse these hierarchies as folders.)

Sometimes hierarchical information is not represented in the taxonomy_term_parent table, and the relations exist between terms of different vocabularies.

E.g. in a site I am building, a "Product series" has a term reference field to "Product family", which has a term reference to a "Supplier". Suppliers, Product families and Product series are 3 distinct taxonomy vocabularies.

Some products only have a supplier. Others have a supplier and a product family. And some have all three. If a product has a series, then its product family is the same as that of the series. And if it has a product family, then the supplier is the same as that of the product family.

I would like to expose this structure as one hierarchical facet, similar in appearance and behavior to that for a single hierarchical vocabulary.

Any ideas?

What I managed so far is to assemble the terms from different vocabularies into a common entity property. I also managed to unify the two different "parent term" relationships (series -> family, family -> supplier) into a common entity property. But then what?

One alternative, which is not quite the same, is to use dependencies between facets.

So, the product families facet is shown only if a supplier is chosen. And the product series facet is shown only if a product family is chosen.

With hook_block_view_alter() one can rewrite the block title, so that the product family facet block says e.g. "Acme product family", if "Acme" is chosen as a supplier.

Again, this is not quite the same. But it provides an acceptable user experience, I would say. And it might be a suitable solution for some visitors of this question.


Alternative ways to group results of a view by CCK field? I have cck content type with a variety of fields - video, taxonomy of terms, images, etc - in drupal 7, core 7.8. Unfortunately, I'm unable to group the results of the page view by a cck field by simply filtering and changing format settings by Group Field - UNLESS, I update my Drupal Core (tested w/ 7.12 and works easily). I am, however, able to group via using content: post date.

I've read through several answers on stack-xchg, ie. Grouping a View by Custom Field - but didn't really find an alternative way to group fields in the event I am not permitted to update core or modules.

Is there a way I can group fields by cck field via code? Thanks,

You can do almost anything you want within a views template.  If you look at the Theme Information in the View UI, you can see what you can modify, or just cd into modules/views/theme and take a peek at them.  But, given that the $view variable is available to almost if not all of the templates (whether or not the comments say it is), and $view->result is an array of row values of the view, you can certainly foreach() through it and do whatever you want.  Otherwise, you have the whole gamut of preprocess() hooks, views_pre_render() of which is probably most of interest here.


How to remove a comment based on it's field value? I have a multilingual site, Comments in this site include a language field (field_language), so users who send comment to nodes must specify in what language they are sending the comment. On loading a node I want to display only the comments which their field_language is equal to the current website language. I tried this code based on the following result

function THEME_preprocess_node(&$variables) {
    global $language;
    foreach ($variables['content']['comments']['comments'] as $comment)
        if($comment['field_language']['#items'][0]['value'] != $language->language)
            unset($comment);
}

The $comment['field_language']['#items'][0]['value'] prints the comment field_language so I'm sure this is a correct syntax and the condition holds for a few comments but unset($comment); doesn't unset the comment.

I tried the following code

unset($variables['content']['comments']['comments'][71]);

and it successfully worked and removed the comment. The ID inside the [] is stored in the $comment['#entity_view_mode']['id'], I can easily use this ID to remove the comment but I think there must a more straightforward solution.

Is there any other solution like using hook_comment_load or anything else?

This code should work for you

function THEME_preprocess_node(&$variables) {
  global $language;
  foreach ($variables['content']['comments']['comments'] as $key => $comment) {
    if ($comment['field_language']['#items'][0]['value'] != $language->language) {
      unset($variables['content']['comments']['comments'][$key]);
    }
  }
}


How to create a new seller (store) under administrator using drupal commerce marketplace I am using drupal commerce kickstart to create an eCommerce portal. I need to create sellers, re-sellers and sub-re sellers with in the site. i had installed commerce marketplace, but not aware of creating the new seller. Please help.

The hierarchy will be

The Service Provider has multiple resellers, each reseller can have multiple sub-resellers and finally end-users

First you add role like seller then just add a user with role of seller and set permission for seller.


Need Help Finding Permission Needed for Entity Reference Content Type field I've got a content type called 'resources' in my drupal 7 site. I have authors who have permission to create new resources and edit all the fields.

However, I have recently added a new 'entity reference' field to 'resources'. This field is a select list and the options are 'none' (the default) or 'on the home page'. The authors can SEE this field when they edit or create a new resource, but the only option available to them is 'none'. However, as an admin I can see both 'none' or 'on the home page'. When I select 'on the home page' it puts that particular resource into a VIEW block on the home page of the site. I'd like authors to be able to do this themselves.

I've tried giving authors the permission to edit all Views settings (just to see what would happen) and it didn't help.

Here's how I have it setup:

Views Block:

Access permission, view published content
Pager: display 1 item
Relationships: entity reference: GS Resource
(identifier: content entity reference from field_gs_resource_2 - require this relationship)

Content type GS Resource:

Entity reference - select list (name: field_gs_resource)
custom permissions: admin/author all have all permissions
target type: content
Mode: simple; target bundle: GS resource

Content type Resource: (for embedding the field into the main content type used when creating resources)

Entity reference - select list (name: field_gs_resource_2)
custom permissions: admin/author all have all permissions
target type: content
Mode: simple; target bundle: GS resource

Does anyone have any idea how to give the author the permission they need to edit this field when creating a new resource?

I found the answer to this one. It was the permission 'Bypass content access control' under 'Node'. I gave this permission to the one user role and then removed 'add content' from the shortcut bar so they could only use the link I gave them to create the one specific content type I want them to create.


Boolean checkbox in sytems_settings_form I have written the following code

$form['checking'] = array(
    '#type' => 'checkbox',
    '#default_value' => variable_get('checking',0),
    '#title' => t('title'),
    '#required' => TRUE
  );

  return system_settings_form($form);

the checkbox preserve its checked and unchecked state in the form but I can't get value of the checkbox.

I'm printing its value

dsm(variable_get('checking);
print_r(variable_get('checking',0));

Whether a checkbox is checked or unchecked, in both cases it returns me 1

How can I know whether the checkbox is checked or not?

Have you tried removing the "#required" => TRUE line? If you uncheck the checkbox and the form item is required the form won't validate and your submit callback will not be called.

Also, you should check that your variable isn't overridden in settings.php https://www.drupal.org/node/1525472