Multi step registration - save on last step

You could consider one of two modules that force users to complete their profile if they've dropped off halfway thorough, but still created the account:

Complete Profile or Profile Fields Force Filling

Or, roll your own form using ctools.


#value or #default_value missing from field in $form array

See Why is hook_form_alter() so messy? for a bit of background, but basically you need to drill further down into the array.

Assuming it's a standard text field you would set, for example, the default value like so:

$form['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = 'foo';


Can't get rid(find) of this margin. Please help!

Inside professional_theme/style.css line no 727 there is css rule,

.node {
margin: 20px 0;
}

thats create the margin of 20px white margin.


If I understand your question correctly, sounds like you maybe want to use a contextual filter for the taxonomy term TID, and embed as a block in the sidebar for taxonomy pages.

This may help: http://dannyenglander.com/blog/using-views-contextual-filters-create-related-content-block-drupal-7

Steps to help:

create a relationship, Content: Taxonomy terms on node, choose taxonomy, check require this relationship
add contextual filter, Taxonomy Term: Term ID, select the relationship you just made, check "provide default value- Taxonomy term ID from URL, Load default filter from term page.

Just checked on a vanilla install, and that worked a charm for me...


Thank you very much for your help. I finally manage to autenticate and retrieve files from my rpc server. Here is my syntax in case anyone needs it.

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);

EDIT: AFTER SERVICES 3.5 you should do:

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

//RETRIEVE FILE
$file= xmlrpc($settings['server'], Array('file.retrieve' => Array(Array("fid"=>$fid),Array("file_contents"=> 'true'),Array("image_styles"=>'true') )),$options);


I would just like to answer my own question. After reading more documentation about how CORS works, I found out that, to allow Drupal access other site/server, CORS must be enabled in the other party not in Drupal site itself. Some basic explanation found here too. https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work/10636765#10636765


You can achieve your requirement by installing any of the below modules:

Custom Breadcrumbs

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

Path Breadcrumbs

  This module is a solution for all problems with the breadcrumbs on
  your site! Path Breadcrumbs module helps you to create breadcrumbs for
  any page with any selection rules and load any entity from the URL!

You can also follow this link.


Where to place php code snippets in Drupal?

You should place this helper function in your custom module, so once the module get enabled the you can call this function anywhere across drupal environment.


Foolproof way to prevent email sends from local/dev server

You can sanitize the database so that the emails are not "live" before you provide the database to new developer(s).

drush sql-sanitize is one way to do this.

On my site, I have dev/staging/live servers.  When the live/test database is cloned to dev, a script is called that automatically changes all email addresses to uid@mysite.com.  And then all developers pull the database from the dev server.  This way, it is impossible to accidentally spam users.

I think the only "foolproof" way to prevent accidentally emailing users is to never give the developer the users' emails in the first place.


How to automatically deliver Drupal 7's static contents using CDNs?

Easy

Copy the static files to your CDN (Rackspace cloud files in this case)
Install http://drupal.org/project/cdn (drupal 7 requires no core patch)
Configure the CDN module

Update

You can automate the delivery of content files with the File Conveyor mode, this module integrates with the File Conveyor daemon. This allows for much more advanced setups: files can be processed (e.g. optimize images like smush.it, minify CSS with YUI Compressor, minify JS with YUI compressor or Google Closure Compiler, before they are synced and your CDN doesn't have to support Origin Pull, any push method is fine (supported transfer protocols: FTP, Amazon S3, Rackspace CloudFiles). File Conveyor is flexible enough to be used with any CDN, thus it enables you to avoid vendor lock-in.


Set field_id for views "Global: Custom text" field

Well, sometimes the only way to solve a hard problem is to write your own module (or, as in my case, just collaborate with someone who's already writing such a module).

I'm now using the newly-launched Views fieldsets module to achieve what I was trying to do!


What causes a search_api based view to stay cached for anonymous users even after the index is updated?

Is it possible you have a "non Drupal" cache for anonymous users? Common such caches include Varnish (server based) or Cloudflare (cloud/cdn based)
Failing that, have you checked the cache settings on the view itself? I believe for search API the correct settings should be Caching: Search API (tag based) (under advanced in the view edit screen). If that doesn't work you could try turning off the views cache temporarily to at least determine if that is the root cause.
Finally check your modules are up to date, including Search API & check the issue queue to see if there are any patches that may solve your issue: https://www.drupal.org/project/issues/search_api?categories

“There are only two hard things in Computer Science: cache invalidation and naming things”


Why did Views just jump from 3.8 to 3.10 (what happened to 3.9)?

I can't say exactly what's happened in this particular case, but:

It's fairly common practice to do a double release in the case of security updates. Core for example, does this every time, although I couldn't find a reference to the practice right now.

Let's say you've released version X.Y.

Working on X.Y + 1, you've made some number commits on top of X.Y. Now you find a security problem in X.Y, and need to address it. You can now quickly rush out X.Y + 1 along with your additional feature work, and the security fix.

However, your new feature work isn't as well tested as it should be, because you hadn't prepared for a security emergency release. So although it might function perfectly well, likely, your work is "more buggy than usual".

Also, big sites are likely to be careful in upgrading versions, they'll need to take their time testing the site, making sure everything keeps working.

Any delay in the security update process is bad however, so we'd really like to be able to help people upgrade as soon as possible.

So what can we do? We can take the security only fix, and make a separate release of only that.

In this particular case, it looks like the feature release was done first, and then the security release. If I wanted to security patch my 3.8, I would have to pull out the diff between 3.9 and 3.10 and apply it. I could then take my time upgrading to the real 3.10.

If you look to Core for a similar example, check git log 7.31..7.32, which will show you that "SA-CORE-2014-005" was fixed on October 15th, however, the later release, 7.33 (git log 7.32..7.33) will contain commits from both before October the 15th and after. Gits history was re-written, such that the security update alone ended up in the next release, and any additional work then went into a new release. This requires more git trickery, but further lowers the bar for upgrading. In the case of SA-CORE-2014-005, this was important. Not so  much in the case of the Views issue, which was minor.


Views adds "nid" to SELECT and GROUP BY when trying to aggregate by title

Try to enable checkbox Query settings -> Distinct in your view settings.


How do I write this PHP query the Drupal way (database abstraction)?

I think that you can review this answer:

  If you use db_query() all the time without directly inserting
  variables, but using the arguments.

I hope information be useful.


Add user picture to profile 2/any entity for that matter...

You have two options.

You can use theming to make whatever you want use the profile picture.

Another options would be to add the picture from the profile to the user object on load.

Third option would be to sync the user picture with the profile picture whenever the profile entity is saved.

If you want it to take effect everywhere, you need to use the third options, which adds the headache of having the same data store twice and the problems such a thing can bring,


I'm getting a 403 forbidden on your prettify.js. If you change the permissions of the sites/all/libraries/prettify/src folder to 777, It should solve your problem.


succesfully changed order regions in info file, but rendered html stays untouched

the orders of your regions are probably defined in the page.tpl.php of your current theme. so you will have to change the order there, changing the order of your .info entries should (if any) only change the output from configuration pages.


Apache SOLR + Facet API + Taxonomy terms

Although I've not tried the recipe I believe that this article over at wunderkraut is an exact match for what you are after. There is a lot of custom coding involved.


How to apply js and css to ajax loaded content?

Is there any issue with above code?

Yes, you're using the D7 approach. In D8 it is different. You need to create a libraries.yml file where you will define your CSS and JS files.

See:

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

Once you have a library you can attach it like this:

  '#attached' => array(
    'library' => array(
      'your_theme/library_name',
    ),


Subtract UserPoints from all taxonomy terms upon purchase?

You have few options that depend on the number of userpoints categories and the way you want to do it (w or w/o code):

Option 1: Create separate actions for each userpoint category within Ubercart.

Option 2: Enter custom PHP code and do the following:

Load userpoints dictionary - userpoints_get_vid()
Loop through all terms in it and subtract the points.

Sample code:

$userpoints_vid = userpoints_get_vid();
$userpoints_terms = taxonomy_get_tree($userpoints_vid);
foreach ($userpoints_terms as $term) {
  // Build the params for this transaction.
  $params = array(
    'points' => -100,
    'moderate' => FALSE,
    'term_id' => $term->tid,
    'entity_id' => $order->order_id,
    'entity_type' => 'order',
  );
  // Subtract the points. This will call automatically all UP hooks.
  userpoints_userpointsapi($params);
}

Option 3: You could also create a Rules action from the code above that will accept $order as an argument. This will take slightly more time, but is the right way to do things.


Routing multiple params / paths to single method

Yes, you need to define a route for each path.

The order should not matter, it will put them all in the router table and then "order" them by the best match first.


Writing PHP code to creating menu in block show and alert

You need to define it as a global variable first:

global $base_url;

So that your code is now:

<?php
global $base_url;
$url=$base_url.'/drupal';
echo
'

One

 Two

';
?>

Then you may don't need drupal in your $url variable. and it would become:

$url=$base_url;


Shared subset of users in a multi-site instance

As you mentioned yourself you can share users across multiple site but that are all users. So you need an external 'database' for your admin users that magically exists for all sites.

For this you could use https://www.drupal.org/project/ldap which could contain you administrators.

Normal users can login as normal aka without use the LDAP directory.

Note LDAP can work with MS Active Directory too.


Commerce Hook Function To Checkout Button

The checkout form is a form like any other, so you can just alter it (using hook_form_alter()) and add a submit handler:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_commerce_cart_form_default') {
    $form['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  drupal_set_message('This was run after the cart form was submitted, before the checkout page was rendered.');
}

Addressing the comments...

As you have a custom shopping cart form, with a link instead of submit button, no extra processing will be done so you can just hook into the page build of the linked page (/checkout/%) and perform your operation there; it will have the same effect.

There are a couple of places you could do this (neither really 'better' than the other), hook_page_alter() and hook_init(). There are other places too (theme preprocess functions) but for processing logic something a bit earlier is probably more appropriate. Basic example (will probably need tweaking for your needs):

function MYMODULE_init() {
  if (arg(0) == 'checkout' && $some_other_pertinent_condition) {
    // Do some processing.
  }
}

As for learning Commerce - that's a tricky one. Commerce is heavily integrated with Drupal and uses a lot of its functions/hooks/integrations just like any other module would. So really you need to know Drupal's workflow, and then overlay Commerce's workflow on top of that. The best advise I can give is to grab a Drupal book (Pro Drupal Development is excellent), and after you're happy with the workflow there, hit the Drupal Commerce support pages and read, read, read.

Drupal has a notoriously steep learning curve, and there isn't really a shortcut to understanding how it works as a whole. You just have to get stuck in. But it's well worth it, Drupal's awesome.


Customized Node Display for 'Document Template' Content-Type

Where did I go wrong?

You used the wrong format. Replace the space with a -:

node--document-template.tpl.php


How to make a raw SQL query to get the node/node_votes pairs?

Try this query:

SELECT field_vote_rating from field_data_field_vote
WHERE entity_type = 'node' AND entity_id = $nid;

You can use the database api to create SQL Queries


Search is broken after updating search_api_solr from 8.x-2.7 to 4.1.4

After the latest search_api_solr module update you need to update config files on your server, as there is a new field added.
If you look into the update log you will find the below message.

A new Solr field type has been installed due to configuration changes. It is advisable to download and deploy an updated config.zip to your Solr server.

You can find the additional information on how to update server configs from the below link.
Upgrade Search API Solr
Even after checking above points if you are still getting issues, check whether it is due to varnish.
And also run cron once and clear drupal cache after cron and check results again.


How can build a website for multiple organization?

This is pretty much exactly what the OG (Organic Groups) module is for.


There is not an easy way to get the parent of a specific menu item. The problem is that a path can be in many menus so you need to not only know the path of the item whose parant you want to find, but also which menu to look for them.

The menu_links table hold the info and with a few queries you could find info about the parent. If you actually want to change anything in the menu being printed, that's a completely different story, and can be quite tricky in Drupal 6.

To get menu item you could do something like this:

$path = 'foo';
$menu = 'bar'
$mlid = db_result(db_query("SELECT plid FROM {menu_links}
          WHERE link_path = '%s'
          AND menu_name = '%s'";, array($path, $menu)));

$menu_item = menu_get_item($mlid);
// $menu_item is now the parent menu_item of the menu in bar with path foo


How do enable panelizer support for a custom entity?

Just create a PanelizerEntity Plugin in your module.
Ex if your entity type id (or machine name) is 'course'. Create a file PanelizerCourse.php in your_module/src/Plugin/PanelizerEntity/

This file should extends PanelizerEntityBase like that:

<?php

namespace Drupal\your_module\Plugin\PanelizerEntity;

use Drupal\panelizer\Plugin\PanelizerEntityBase;

/**
 * Panelizer entity plugin for integrating with courses.
 *
 * @PanelizerEntity("course")
 */
class PanelizerCourse extends PanelizerEntityBase {

}


How to restrict user to chat with another user based on their payment and subscription?

From the DrupalChat project page:

  ... provides optional integration with ... Flag Friend module.

And issue # 936350 states:

  ... Would it be possible to show only friends from the Flag Friend module?

Since this issue has status closed(fixed), you should be able to use the Flag Friend module like so:

After the payment was completed, grant the user some permission to be allowed to "flag" the consultant the user paid for.
After such flagging is done, the user should be able to chat with such consultant.


Redirect (or show the node) taxonomy term page to node, if there's only one node associated with that term

My solution is handle it in hook_preprocess_page(maybe there is another or better solutions but this is good too)

put this in template.php

first solution(maybe not worked)

function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid;
    if(count($item)==1){
         drupal_goto('node/'.$items[0]->nid);
     }
    }
}

Alternative solution

function YOURTEMPLATE_preprocess_page(&$variables) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $items = taxonomy_select_nodes($tid);
    if(count($items)==1){

         //another solution is set a variable in preprocess and in page.tpl.php or your taxonomy tempalte page redirect it
         $variables['soheil_redirect_tax'] = array('path' => url('node/'.$items['nid']));

    }
  }

if first solution (drupal_goto) not worked in page.tpl.php or your custom template for terms page handle redirect(I mean in page.tpl.php file or taxonomy--term.tpl.php file) with

 if(isset($soheil_redirect_tax)){
    drupal_goto($soheil_redirect_tax['path']);
 }


As @Clive suggested in the comments, I was searching for a module involving links when I should have searched for some kind of text filtering.

I've found the responsible module : Path Filter, and I indeed forgot to enable it again after the update.

The internal:forum pattern is written in a node's content, and is changed to a valid path in the final page.


Where is the "sites/all" folder for an ubuntu linux installation?

It's referring to the "sites/all" folder in your website's root folder.

The location of your site's files will have been set by your web server software (probably Apache, in this case).

Have a look here:  /var/www/

and see if there are any directories in there that look like "httpdocs" or anything with your site's name in it or anything.


content type or normal er table, that is the question

If you are using Drupal 7, instead of using plain custom tables, use a custom entity type, this is really easy to do with Entity API This gives you basic integration with Views and some other modules such as Rules 'out of the box', and customisation is very easy to handle.

I do not see entities having much overhead above a plain database table when the entities are not fieldable. I have worked on a site with millions of rows of data, which is all available as entities, and we load several thousand of them at a time when necessary, this does require a memory limit larger than 128MB, but I haven't seen memory usage go over 256MB while paginating a thousand or so entities at a time out of the possible millions. (Bear in mind though the entities are not fieldable, and we are using APC which does reduce memory usage.)

You can then also use the full power of entity_metadata_wrapper(), which is really awesome, and simplifies code.

Basicly, entities give you the benefits of a content type, without the overhead of revisions or comments. In fact, nodes are entities, so are taxonomy vocabularies and taxonomy terms.

It is definitely a best practice to use entity API to access entities as this allows all the proper hooks to be run, such as clearing the necessary data from entity cache. However, you are not forced to always use the Entity API to access the database entity rows, but do be aware that there are extra risks and gotcha's attached to this.


Use node edit form layout for other entity types

Drupal\node\NodeForm provides it own build() method that puts the meta items into an  advanced group, and then the classy template node-edit-form.html.twig renders that group in a sidebar. The form builder also attaches the node/drupal.node library, which provides the layout CSS.

To copy this layout and style for another entity, you could implement hook_form_alter in a custom module and move the metadata form items into an advanced group like NodeForm does. You also need to theme the form with the node_edit_form template and attach the node/drupal.node library.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Select the group add/edit form.
  if (in_array('group_form', $form['#theme'])) {
    // Use the node edit form template.
    $form['#theme'][] = 'node_edit_form';

    // Use the node form layout library.
    $form['#attached']['library'] = ['node/drupal.node'];

    // Create the advanced element if it doesn't exist.
    if (!isset($form['advanced'])) {
      $form['advanced'] = [
        '#type' => 'container',
        '#weight' => 99,
      ];
    }
    else {
      // Make 'advanced' a container instead of vertical_tabs.
      $form['advanced']['#type'] = 'container';
    }

    // Add the style class to tell the admin theme how to style it.
    $form['advanced']['#attributes']['class'][] = 'entity-meta';

    // Move detail elements into 'advanced'.
    $form['detail_element_you_want_to_move']['#group'] = 'advanced';
  }
}

Alternatively, you could create your own Twig template and library and use those instead of borrowing from node.


Views exposed filter for children terms when on parent term page

You could use a form_alter hook in a custom module (or even your template.php file of your theme) to alter the filter values in the exposed view form.

as an example:

<?php
    function mymodule_form_alter(&$form, &$form_state, $form_id){
        //if it is the exposed filter view
        if (($form_id == 'views_exposed_form') &&
        //for the view we care about
        ($form_state['view']->name == 'your_view') &&
        //and the view display we care about
        ($form_state['view']->current_display == 'your_display') &&
        //and on a taxonomy term page
        (arg(0)=='taxonomy') && (arg(1)=='term') && (is_int(arg(2)))){
            //get the childern of the term
            if ($child_terms = taxonomy_get_children(arg(2))){
                //only care about the tids
                $child_terms_tids = array();
                foreach ($child_terms as $child){
                    $child_terms_tids[] = $child->tid;
                }

                //for the exposed filter, alter the available options
                foreach ($form['exposed_filter_name']['#options'] as $tid => $term){
                    //is is a child term?
                    if (in_array($tid,$child_terms_tids)){
                        //leave it
                    }else{
                        //remove it
                        unset($form['exposed_filter_name']['#options'][$tid]);
                    }
                }
            }
        }
    }

    ?>


If you use even/odd pseudo-classes, you don't need even/odd classes

:nth-child(even)
:nth-child(odd)

Example:

.parent_class > div:nth-child(even) {background: #CCC}
.parent_class > div:nth-child(odd) {background: #FFF}

or

ul.yourclass li:nth-child(even) {background: #CCC}
ul.yourclass li:nth-child(odd) {background: #FFF}


Why node/*/track appears as Referrer to node/*?

The issue is with the _statistics_link() function and no referral data; this function relies on drupal_get_path_alias() and when an empty path (i.e. the referrer) is passed to it, it returns the current path which is node/%node/track.

So in other words, those are not anonymous users viewing the tracking page, rather it's anonymous users browsing directly to the page (or not sending referrer data).


Appache solr results multi sites search sorting based on specific feild

A quick Solution may be to use Apache Solr Sort Module.

  Per environment setting of grouping per content type/taxonomy/field
  value/... Allow for a custom amount of items per group (global)

But the best way is to setup a Apache Solr View :

Search API, has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.


If you're not committed to using Bartik, you could try one of the Adaptive Theme subthemes.  These themes are very popular (one of them, Corolla, was intended for inclusion as the default theme in Drupal 7 but lost out to Bartik) and they allow you to change the width of the page easily on the settings page.

They are also responsive, which means that they will automatically adjust the columns on your page to display better on different screen sizes (by default, they provide PC, tablet, and smartphone layouts).  You can also adjust the colors from within the UI just like Bartik.  They are very newbie-friendly (the other major collection of newbie-friendly Drupal themes are the Fusion subthemes).

The base theme is Adaptivetheme, which you must install (though you won't actually use this theme).  Then you can choose from Corolla, Sky, or Pixture Reloaded.


How to upload enterprise blog picture programatically in drupal 7

Ok, here is my testing example. I can't say that it works perfectly but in my case it works fine. And, of course, you can modify/customize it by your needs if you want (add validation, check file path, directories, and so on..):

function _executeFile($uri, $uid) {

  $file_url = file_create_url($uri);
  $file = system_retrieve_file($file_url, NULL, TRUE, FILE_EXISTS_REPLACE);

  if ($file) {
    $user = user_load($uid);
    $file = file_load($file->fid);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // file_usage_add($file, 'MY_MODULE', 'enterprize_picture', $file->fid);

    $file_info = image_get_info($file->uri);

    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['fid'] = $file->fid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['alt'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['title'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['width'] = $file_info['width'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['height'] = $file_info['height'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uid'] = $file->uid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filename'] = $file->filename;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uri'] = $file->uri;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filemime'] = $file->filemime;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filesize'] = $file->filesize;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['status'] = '1';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['timestamp'] = $file->timestamp;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['rdf_mapping'] = array();

    user_save($user);
  }
  else {
    // SET VALIDATION ERROR
  }
}

and call it like this:

define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
_executeFile($uri /* e.g.: 'public://OTHER-OpenSourceSystem_1600x1200.jpg' */, $uid);

First function gets two variables as arguments and loads user object
and creates file object from URI, and sets file object properties to
user file field and saves it;
Second piece of code bootstraps system and just calls that function.. You can set your validation rules here


Webform doesn't send email using MIME Mail

I had a similar, slightly different, issue after updating from webform version 7.x.3.25 to 7.x.3.27

WORKED FOR ME:

Upgrade to webform 7.x.4-branch


How to make a user role expire after 1 year?

Below are the following ways to do this:

1.As same as role expire another module User expire is available User Expire.

2.By using Rules module you can expire the role after 1 Year.

Try these Modules hope this will help you.


Webform with File upload field throwing "... field is required" error

This can be solved by applying the patches found here:

#49 https://www.drupal.org/node/2675170#comment-10908802
#22 https://www.drupal.org/node/2678822#comment-10926613

This will hopefully be resolved just by updating for future versions of drupal core and webform.


How to loop through comments using the Rules module?

How to loop through comments using Rules

Have a look at this rule (in Rules export format, you should be able to import it in your own site if you have the Rules UI enabled):

{ "rules_change_a_comment_field" : {
    "LABEL" : "Change a comment field",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_update" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "An update to some comment has been discovered ... Some more details about this updated comment:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment body (before) = [comment-unchanged:comment-body:value]\u003Cbr \/\u003E\r\nComment body (after) = [comment:comment-body:value]\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\u003Cbr \/\u003E\r\nComment author (before) = [comment-unchanged:author]\u003Cbr \/\u003E\r\nComment author (after) = [comment:author]\u003Cbr \/\u003E\r\n" } },
      { "LOOP" : {
          "USING" : { "list" : [ "comment-unchanged:node:comments" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "drupal_message" : { "message" : "Now processing comment with cid=[list-item:cid] and body = [list-item:comment-body:value] ..." } },
            { "entity_fetch" : {
                "USING" : { "type" : "comment", "id" : [ "list-item:cid" ] },
                "PROVIDE" : { "entity_fetched" : { "comment_fetched" : "Fetched comment" } }
              }
            },
            { "data_set" : {
                "data" : [ "comment-fetched:author" ],
                "value" : [ "site:current-user" ]
              }
            },
            { "entity_save" : { "data" : [ "comment-fetched" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

In this rule, for the sake of simplicity, I intentionally did not use a Rules Component (I just included my entire Rules logic in a single rule). Here is a summary of what the above rule does:

Rules Event: After updating an existing comment.
Rules Actions: Loop over each of the comments, and perform these actions for each of them:

Show a message on the site (just for demo purpose, to know what the rule is processing).
Fetch entity by id, to retrieve all data about the comment entity being processed in the loop.
Set a data value, to change the author of the comment being processed to the current user (this may seem a bit bizarre, I know, but consider it as just a demo sample, to illustrate you can update EACH comment processed in the loop).
Save entity, for the comment entity being processed in the loop. If you don't perform this action, then I'm pretty sure the updated value won't have been saved in the end (which is probably also what you experienced in your nothing happens).

Disclaimer: there may be more refined (optimized) solutions to get such rule to work, but using the above Rules actions (and meaningful variables ...) should help to understand what's happening if you're not experienced enough with Rules (yet).

Attention: be careful if you import the above rule (and leave it active) ... because this rule really works (and will change all comment authors to the last user who updated any comment).

Plan B

If what's above doesn't help, then something that will help you find the answer to your question, is to have a look at Rules debugging ... 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).

Depending on what the result of that type of debugging is, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of your node:comments).

Refer to the (great!) video "Debugging rules configuration" for way more details about these 2 variations.


Add html to li for active-trail menu links

You can check if $element['#localized_options']['attributes']['class'] contain active-trail class and create your custom span based on this information.

function MYTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $span = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if (isset($element['#localized_options']['attributes']['class'])) {
    if (in_array('active-trail', $element['#localized_options']['attributes']['class'])) {
      $span = 'Something';
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . $span . "
\n";
}


In your "submitForm" method write below code:

$form_state->setRedirect('<front>');
return;

To redirect you can also use the following code:

//after the namespace
use Drupal\Core\Url;

//In your "submitForm"
$url = Url::fromRoute('<front>');
$form_state->setRedirectUrl($url);

To redirect you can also use the following code:

//after the namespace
use Symfony\Component\HttpFoundation\RedirectResponse;

//In your "submitForm"
global $base_url;
$response = new RedirectResponse($base_url);
$response->send();
return;


Views usage of the term "Global" is unrelated to PHP Globals. It means that is it globally accessible to all Views regardless of base type (node, user, taxonomy term).

If you find the need to use PHP in your Views, then you should either look into writing a custom Views handler, or try the Views PHP module.


The advice is the same, it's just moved. The docs for t() say:

  See \Drupal\Core\StringTranslation\TranslatableMarkup::__construct()for important security information and usage guidelines.

On that page you'll find familiar advice:

  Translating Variables
  $string should always be an English literal string.

  $string should never contain a variable, such as:

  new TranslatableMarkup($text);

  ...

So generally speaking no, it's not OK to pass a variable as the first argument to t() in Drupal 8. Always use a literal string.

If you need to use variables for t(), pass a literal string containing placeholders, and a second argument containing their replacements. For example:

new TranslatableMarkup("@name's blog", [
  '@name' => $account
    ->getDisplayName(),
]);


Conceptual question about taxonomy structure

If I understand the question correctly you want to prepend the city name as an argument on the view, so you would have:

  organisations/denver/yogashops

well you could equally have the city appended:

  organisations/yogashops/denver

The question has no mention of Views, but I would recommend that you create a view with the contextual filters of organisation and city:

I recently set up something similar for global dealerships /find-a-dealer/europe/fr


To get the real value and not  a themed one...

You can use http://api.drupal.org/api/drupal/modules!field!field.module/function/field_get_items/7

 $my_field_items = field_get_items('node', $node, 'field_my_field');

Or use Entity API module and entity_metadata_wrapper

 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

Take a loot also at http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


Get node field image in " hook_node insert "

Drupal gives this by single file load from database:

$objFile = file_load($fid);
$imgabspath = objFile->uri; //getting file page (Example of image file absolute path)
print file_create_url($imgabspath);  //This is your file absolute url
$filename = objFile->filename; //getting file name

Still you are not getting result proper then there is some problem into $fid so confirm it by:

$node = node_load($nid);
// assuming file field has been added to the node has field_example_file machine name.
if (!empty($node->field_example_file)) {
  // $img will contain an array, which has the data of a file (file object converted to array I suppose..)
  $img = $node->field_example_file['und'][0];
}
$fid = $img['fid'];//This is your fid...

NOTE : file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap. Also note that file_load() doesn't return title and alt attributes of field_image.

Thanks!


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

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

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

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

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


Where can I set the following HTML attribute to my custom field?

Solved with formElement, at least form mobile devices. Just was I was looking for.

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    $element['#accept'] = 'image/*;capture=camera';

    return $element;
  }

Thank you!


How to know where the value of a field is being stored in

Sounds as if you are asking how to see what's available to you in a variable.

Install the Devel module, and just use the dpm() function:

dpm($variable);

It will use Krumo to represent the data you pass and display it on the page. If it's an array, it will show you all the elements, same for objects and so on.


Ubercart - Stay on page when you add product to cart

Yes.

1. Log in as admin, and go to: admin/store/settings/cart
2. Click on Basic Settings
3. Then in the "Add to cart redirect" section, enter: <none>
4. Got to "Continue Shopping Element" and set "Make continue shopping go back to the last item that was added to the cart."


Can you try this solution?

$items['user/%user/hybridauth']['access arguments'] = array('administer site configuration');


What is the Drupal's way of wrapping fields inside a field?

You can try https://drupal.org/project/composed_field

  The Field collection uses a different approach for creating composed fields. Here are the main differences between this module and the "Field Collection":
  The host field created by "Field Collection" is in fact an entity that gets attached to the fieldable entities (nodes, taxonomy, comment, commerce products, etc). So, although you attach a Field Collection through the Field UI, what is being attached is not a field but an entity.

  Once you get your new entity (host field) attached to your fieldable entity (node, comment, taxonomy, commerce product, etc) then you have to attach the fields ( what would be the subfields ) into the host field ( Field Collection entity).

  Each subfield is actually a field on its own, that is, from the database point of view, each subfield is a single field.

  "Composed Field" on the other hand attaches a field (host field), not an entity, to your fieldable entities (node, comment, taxonomy, commerce product, etc) through the Field UI. At the end of the day, even if you set a field with say 4 subfields, you will end up having only one field and a single value saved into the database.

  Unless you have a very specific use case need "Composed Field" should do what you need with less effort and less resources.

One more module availabel to achive the similar task is https://drupal.org/project/multifield but it is currently in unstable status

  This project seeks to provide a true compound field solution for Drupal 7. As much as I love Field collection, it still has to save actual entities, and can cause performance problems due to having to load all the referenced field collection entities on node, or parent entity load.


Although not open source, there is the paid for module called 'pay to publish'.

I've not used this exact module, but have used this companies products before and they worked 100% as advertised...

For some reason my phone will not allow me to paste the URL in here, so just Google 'moneyscripts Drupal pay to publish'.


Form in a block with results is the same block

Thanks 4k4, the main point I was missing here is that a form is just a specific form of render array... I though it was only possible to define form elements to be rendered. But as you pointed me out, it's possible to define anything one wants to render, like... form result... Since what I need to render is a bit more complicated than simple markup, I've created a new template in my .module file :

function my_module_theme() {
return array(
'my_module_form' => array(
  'variables' => array(
    'form' => array(),
  ),
'template' => 'my-module-form',
),
 'my_module_results' => array(
  'variables' => array(
    'tracks' => array(),
  ),
 }

And then, my buildForm method looks approximately that way :

public function buildForm(array $form, FormStateInterface $form_state) {
// define default values...
$defaultValue = 3;

// define form fied + submit button...
 $form['my_field'] = array(
  '#type' => 'select',
  '#required' => true,
  '#default_value' => $defaultValue,
  '#options' => array(1 => 1, 2 => 2, 3 => 3)
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Go'
);

// define field default value that will be overwritten whe  form is submitted
$my_field_value = 1;

//get submitted value
if ($form_state->isRebuilding()){
    $my_field_value =  $form_state->getValue('my_field');
}

//get datas from database
$results = $model->getResultFromDb($my_field);

 $form['result'] = array(
    '#theme' => 'my_module_results',
    '#results' => $results,
    );

return $form;
}

Then is the "my_module_results" you can use the $results var as in any other template :

  {% for result in results %}

 {{ result.title }}

  {% endfor %}

For the results not to be nested in the "form" markup, I had to build manually the form in its own template and call the result var where I needed the result template to be inserted :

    <form method="{{ form['#method'] }}">
        {{ form.form_build_id }}
        {{ form.form_token }}
        {{ form.form_id }}
        {{ form.my_field }}
        {{ form.submit }}
    </form>

    {{ form.result }}

Not sure it wes the only way to do that, but it works like a charm...

Hope this would help somebody...


How to split configurations in features to minimize conflicts

What I try to do is to build up features in layers. At the bottom most layer you put all the things that do not depend on anything else in your features, such as contrib modules, site settings and the like.

At each layer you add features that depend on the layer below, trying to avoid cross-dependencies. Each feature should be as standalone as possible apart from its depndencies on lower-level features.

It's difficult to achieve perfection, though, because a new feature may affect things you have already configured. For example if you install the field permissions module for a specific need, that'll add extra settings to fields you have already configured. So that module effectively becomes a dependency of sorts even though logically it isn't.


Do not send registration mail to fake users, who haven't specified their gender in registration form

I suggest you implement hook_form_id_alter to either add a new validation function to the registration form, or replace the submit callback.

In a validation function, you have access to the form values, and you can do whatever checks you want, and fail the submission. This will reject the form all together.

If you replace the submit callback instead, you could override only the sending of the e-mail. but otherwise let the form pass through, which seems closer to what is being asked for.


how to display the machine name of module at /admin/modules?

If you don't mind going low-tech you can just look at the value of the checkbox next to each module; it contains a string like:

modules[Core][aggregator][enable]

In that example, aggregator being the machine name of the module.

If you don't want to go low-tech you'll need to implement hook_form_alter(), loop through the module data in the form and add the machine name somewhere.

For example, the following code will add the machine name in brackets after the title of each module:

function MYMODULE_form_system_modules_alter(&$form, &$form_state, $form_id) {
  foreach (element_children($form['modules']) as $group_key) {
    foreach (element_children($form['modules'][$group_key]) as $module_key) {
      $machine_name = " ($module_key)";
      $form['modules'][$group_key][$module_key]['name']['#markup'] = $form['modules'][$group_key][$module_key]['name']['#markup'] . $machine_name;
    }
  }
}

Screenshot of the results on a blank Drupal installation:


How do I set up PayPal parallel payments in Drupal 7 Commerce Express Checkout module?

The short answer is that there isn't just a place to "paste the snippet." That integration wizard is hopelessly simplistic. Support for a new payment method within Drupal Commerce would require more than simply adding code to a page, because presumably you'll want some sort of local record of any payment action taking place. For that to happen, you have to work with the Drupal / Drupal Commerce APIs as well.

In Drupal Commerce, these integrations are handled through payment method modules. We have documentation for writing them in the developer guide on DrupalCommerce.org. Additionally, if you're PayPal Express Checkout, you should switch to using the 2.x branch of the main PayPal project, http://drupal.org/project/commerce_paypal, as it has a complete implementation of the Express Checkout payment method and has been verified by PayPal.


I would pass the argument in via the URL, you can pass multiple args in using '+'. So http://example.com/my-view/[nid1]+[nid2]


Get the last revision id of any given entity?

I think entity_extract_ids() is the quickest you'll get:

  Helper function to extract id, vid, and bundle name from an entity.

e.g.

list($nid, $vid, $bundle) = entity_extract_ids('node', $some_node);


If you create webform first and then install webform localization module , the module will see only new components in webform , so try to open each component and save it then go to Regional and language > translate interface > strings , check "webform localization" and "fields" then "Refresh strings" , then back to translate interface > translate , search for your components labels and translate them


I enabled certain page view (which is a clone of currently working view), but its page link returns 404 page

Save the views and then in admin/config/development/performance do clear cache


AFAIK, there is no module that does this for you.

I think this is a sensible approach.  I am doing the same thing myself, storing the array with site-wide persistant data using the built-in function variable_set() to save, and then I use function variable_get() to retrieve the data.

I don't think saving site wide information in fields is a good idea.


How to theme a flag for different pages?

Something like this will work for user pages. You can adapt for other pages. Put it in your theme's template.php file.

function MYTHEME_preprocess_flag(&$variables) {
  if ($variables['flag']->name == "MACHINE_NAME_OF_FLAG") {
    if (arg(0) == 'user') {
        $variables['theme_hook_suggestions'][] = 'flag__user_page';
    }
  }
}

and the template file name then becomes

flag--user-page.tpl.php


You are safe to use the same name. The fields are unique for each entity type, even when they have the same name.

They have their own field storage configuration, instances and will be stored to dedicated database tables per entity type.


how to prepopulate a flexifield in form_alter?

do a form alter and add your value as a default value using the default value key,

http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/5#textfield

'#default_value' => //my value;

you can always print $form in your form_alter after you have altered your $form, to have a better look at your flexifield array, and chck if the default value is set like it is shown in the forms api reference link above. :)


How to implement a multiple (AJAX) field collection with the FAPI

So, I followed the answer in the other thread Clive linked and this did the trick:

  $profile = new stdclass();
  $profile->type = 'some_profile_type';
  field_attach_form('profile2', $profile, $form, $form_state, LANGUAGE_NONE);

EDIT: Well, this is fixing the issue because it enables the form to use its widgets. But it remains a problem, the button part of the array is passed in form_state as a value, and I have to delete it manually...


I got the solution: If the node doesn't change, don't create a new revision.


I think you can better do this with hook_form_alter. Like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
    }
  }
}

If you do a var_dump (or dpm if you use devel) on $form, you can easily find out which values to alter.


You can use hook_menu_alter
below code not completely correct but can get you good idea about how can you do it

function mymodule_menu_alter(&$items) {
 $temp= $items['node/%'] ;
$items['page?%']=$temp;
}


How to numerate drupal views rows in twig?

The fields template is probably not the best place. Normally you would do this in the views style plugin. Grid has such options built in, for Unformatted you can add

loop.first ? 'views-row-first',

to  views-view-unformatted.twig.html:

{% if title %}
  <h3>{{ title }}</h3>
{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
      loop.first ? 'views-row-first',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>
    {{ row.content }}
  </div>
{% endfor %}


The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are no search results.

If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.

Open that file up for editing and you'll see the following at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

This is what's displayed if search results are not found (thus the 'else')...  Modify the text to be anything you want here.  The second line, which calls the search_help() function is the one that displays the search suggestions.  Feel free to replace that too....

And as always, before you can see your changes, you'll probably need to clear cache!

Let us know if this works for you!


The problem is it starts from 0, isn't it?

If you use that for your path: [node:title]_a.[file:ffp-extension-original]

my_node_title_a0.jpg
my_node_title_a1.jpg
my_node_title_a2.jpg

OR

You can use the [file:original:fid] pattern, it gives serial values but the fid increments for all the nodes, not for each nodes. I mean, if you upload 10 images to your first node and then for your second node if you upload 3 images, second node's images' names are as below:

my_node_title_a11.jpg
my_node_title_a12.jpg
my_node_title_a13.jpg


Showing nested links in Drupal but still add classes to list elements

Check out the Menu Attributes module. Here is a quote about it (from the module's project page):

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
You want to give a menu item an ID so you can easily select it using jQuery
You want to add additional classes or styles to a menu item


How can I programatically change the content of a block and keep Full HTML formatting

The body field has at least two properties, value and format. To replace the complete field content, you have to use an array:

$my_block->set('body', [[
  'value' => '
' . $my_processed_string . '
',
  'format' => 'full_html',
]]);

Normally you don't need to do this. Set only the value property:

$my_block->body->value = '
' . $my_processed_string . '
';

So that you don't overwrite properties you don't want to change.


How to restrict each user to making only 1 comment per node?

Implement hook_form_alter() in a module. If the form is the node comment form, check if the currently logged-in user has commented on this node earlier. (You might have to write a custom function for this.)  If the user has commented on the node, disable the submit button and the textarea.


Display members with same taxonomy using Views

Create a view block of users and show all the required fields.

Add a contextual filter for school.

Now here ideally we need some way to dynamically get the school id
of the current logged in user. But we only get these kinds of values:

So in order to dynamically get the term id of the user's field. we can either write a custom hook hook_views_pre_view See its documentation and modify the correct $arg by loading the current user and getting the user's selected term for school.
or

Create a custom views argument plugin, or use this module : https://www.drupal.org/project/user_field_value


Create View on Content, and click "save and edit".
Add necessary fields. Title, body, post date, etc.
Expand the "Advanced" pane.
Add new Contextual filter.
Check "Content: Author uid"
When the filter value is NOT in the URL -> Provide default value  ->  User ID from logged in user (if you are putting this View in profile pages, better choose "User ID from URL")
Apply and save.
:)

Update:

Here is a short list for Views 2:

Create a View on node as primary table.
Add necessary fields as you want.
Click Add new argument(Little plus sign under arguments pane).
Check "User: UID" and click add.
When the argument is not given, choose to use a default argument, and set it to logged in user.

Update 2:

If you want to restrict access to own content, see https://drupal.stackexchange.com/a/41899/1899


CKEditor 4.2 and Media Module, Has anyone gotten this to work?

CKEditor 4.1 introduced a feature called Advanced Content Filter. It might be stripping some code. You can test if it's the cause by adding this code your ckeditor/config.js file:

CKEDITOR.config.allowedContent = true

Granted, you shouldn't just leave it true, but it will give you an idea if that's the problem.


How do I create a link that points users to the edit profile page?

You might want to try using the Menu Token module, so you could add a user id token in the path.

Otherwise you'd need to create a page callback in a custom module using hook_menu(), say to 'user/edit', and in that callback, redirect the user to 'user/[uid]/edit'. That way you could add a menu link to 'user/edit' and it would work. See this comment for an example.


How to set language for user register page / form per subdomain

Maybe you can use the Domain Locale module. It allows you to change the available and default languages per domain.


How to convert URL aliases back to node ID

You can use drupal_get_normal_path function.

  Return value

  The internal path represented by the alias, or the original alias if
  no internal path was found.


How-To call a module when a user clicks a node title or read more link if($page)

That's not how it works in Drupal.

You need to use Hook_node_view() in a custom module .module file, NOT in the template.tpl.php file. Which executes the code inside it whenever a node is viewed.

Ex:

hello_world.module

hello_world_node_view($node, $view_mode, $langcode){

  //code to run when node is viewed goes here.

}


how to add a remove coupon button to commerce checkout page

I was not able to recreate your issue. 'Remove' button was available next to the applied coupon.

The version of coupon code, I'm using is 7.x-2.0-rc2.

The steps I took were:

Added a discount and associated a coupon code with it.
Added an item to cart and checked out.
After confirming checkout was given option to add coupon code.

Checkout settings:

Note:

  The problem could be with checkout page. You can use order_coupon_list
  view block below the coupon code apply form.


How to add link around each rows in views?

Sounds like it would be easier to create a View Mode for this. Add a View Mode under Admin > Structure > Display Modes, arrange the fields and configure their formatters. Then if you need to, create a node--node_type_name--view_mode_name.html.twig template to get the markup you want.

Back in the view, change the output to rendered entity, and select your new View Mode. This reduces complexity when it comes to displaying views that are basic entity fields, because that all happens in the View Mode configuration now instead of dealing with views fields and overwriting and theming.

In your new node view mode twig template, wrap your fields and use the appropriate twig function to wire it up:

https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

So, something like:

    // all node content fields + markup here
    {{ content|without('comment', 'links') }}

Also note that your twig file name for the unformatted view will (I believe) affect all views using the unformatted display. You likely don't want that.


You can use query alter will help you out

function custom_views_query_alter(&$view, &$query) {
    if($view->name == "tag_cloud"){
        print_r($query);// before modifying the query.
        $query->table_queue['taxonomy_index']['join']->type = "LEFT OUTER JOIN";
        //sample field change where  ever you want
        print_r($query);// after modifying the query .
    }
}

hope this helps


How to pass rendered form results to page

in your submitForm function you need to set rebuilt to true (the default is false) on the FormStateInterface then add the result as a value to the form_state. And in the buildForm function you need to check for the presence of the results variable and accordingly you can add it to the form. Something like this:

  public function buildForm(array $form, FormStateInterface $form_state) {

    ...

    $result = $form_state->getValue('result');
    if($result){
      $form['calculation'] = $result;
    }

    ...

    return $form;
  }

and

public function submitForm(array &$form, FormStateInterface $form_state) {

  ...

  // Result overview.
  $result = [
    '#theme' => 'THEME_calculation_overview',
    '#name' => !empty($values['company_name']) ? $values['company_name'] : $form_state->getValue('firstname') . ' ' . $form_state->getValue('surname'),
    '#product' => $product,
    '#address' => $address,
    '#results' => $result_clean,
    '#urls' => $product_urls,
  ];

  $form_state->setRebuild();
  $form_state->setValue('result', $result);

}


How do I get a list of all taxonomy terms assigned to a node?

Taxonomy terms are implemented in fields in Drupal 7. Assuming you have defined a taxonomy field named field_category for your content type, you can access it as:

$language = 'und'; // or will be provided by some Drupal hooks
foreach ($node->field_category[$language] as $delta => $value) {
  $term = taxonomy_term_load($value['tid']);
}

If you don't have access to the field name, probably the easiest way for nodes is to query the database directly:

$results = db_query('SELECT tid FROM {taxonomy_index} WHERE nid = :nid', array(':nid' => $node->nid));
foreach ($results as $result) {
  $term = taxonomy_term_load($result->tid);
}

Keep in mind though, that you may end up dealing a jumble of terms from different vocabularies if you have more than one taxonomy field.


Add icon to menu link that has system.admin as a parent

As per the answer by @mradcliffe, styles for the regular and active states would need to be created.  However you'd want to add them as a separate library which you'd include on admin pages, rather than edit core files.

So take the styles in @mradcliffe's answer, or whatever you determine to be correct, and save it to your module in css/webtrack-update-reminder-toolbar-icon.css.

In your module's webtrack_update_reminder.libraries.yml file, something like this:

toolbar-icon:
  version: 1.0
  css:
    theme:
      css/webtrack-update-reminder-toolbar-icon.css: {}

Then in your module's webtrack_update_reminder.module file, something like so:

/**
 * Implements hook_page_attachments().
 */
function webtrack_update_reminder_page_attachments(array &$attachments) {
  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
  if ($is_admin){
    $attachments['#attached']['library'][] = 'webtrack_update_reminder/toolbar-icon';
  }
}

That should be all that's needed to load the library (i.e. your stylesheet) on any admin pages, which will in turn apply your styles to the toolbar item and show your custom toolbar icon.


Same SKU but different product - Drupal Commerce

Short Answer: No, SKUs must be unique.

Longer answer:
SKU is acronym for Stock Keeping Unit. It is a specific produkt that you have have on stock, like a gray medium sized T-shirt with V-neck for men. Had it had a different size, color ... it would have been an entirely different product.

SKU's were create to be able to keep track of these different products, even if there only is a slight change. This also means that SKUs must be unique, since a SKU is the code for a specific product.

The above is general for e-commerce and originates from physical stores with stock keeping etc. Drupal Commerce conforms to these standards, and so it is impossible to create two products with the same SKU.


Where is the Drupal Syslog module log file in Cpanel?

As mentioned on the documentation page for the syslog module, syslog is generally not suitable for shared hosting.

This is because it requires access to server level functionality and configuration that you aren't allowed to access on shared hosting.


views slideshow jquery interfering with nice menus

I think it's z-index and it's a CSS issue, not a Javascript issue.

Put the following in your CSS sheet (any one of them that's included in your homepage):

#views_slideshow_singleframe_teaser_section_slideshow-block_1 {
  z-index: 1;
}

ul.nice-menu li {
  z-index: 10;
}


How to display upvoted posts by user in a view?

Hi Please check the data filters and widget type, for more details read readme file of module, there is (Views integration section)

Its working great if you configure according to documentation.
Thanks!


Help with adding different stylesheet to one specific page in Drupal 7 using the template.php

drupal_get_path_alias("node/{$variables['#node']->nid}") will be equal to "games" only in the case "games" is the path alias for the node being shown.

If you just want to verify the content type of the node being shown is "games," then you need to use code similar to the following one:

if ($variables['node']->type == 'games') {
  drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
}

To notice that a page preprocess function is called also for pages that are not associated to nodes; the function should first verify if it gets a node object, before to access it.
The complete code of the preprocess function should be like the following:

function bluemasters_preprocess_page(&$variables, $hook) {
  if (!empty($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;

    if ($variables['node']->type == 'games') {
      drupal_add_css(drupal_get_path('theme', 'bluemasters') . "/games.css");
    }
  }
}


Which html div classes are relevant when styling Views in Drupal 7 (for CSS)?

I can only speak to my personal experience. I use these classes to style my views primarily:

.view-myview .view-content the main content of the view, encapsulates all rows
.view-myview .views-row this is the row in your view, add a border, some margins, etc.
.view-myview .views-field-myfield a singular field in a view

You also get views-row-even, views-row-odd and views-row-first, views-row-last, etc.

The classes can handle all tags, it doesn't matter if they're divs, spans, etc. I did a presentation at DrupalCon SF 2009 which explains a lot of different ways to customize views if you're interested it is here: http://sf2010.drupal.org/conference/sessions/jquery-views-and-view-themeing.html


How to redirect to frontpage when a node is deleted?

I found the module Save Redirect on Delete which looks like it addresses your problem. From the description:

  The Save Redirect On Delete module gives the functionality for saving redirects after deletion of entity(supported by pathauto module) having some url alias.

I haven't tried it myself but would be interested to know if it helps.


Drupal 6 webform: send email if a checkbox is checked?

You can use the rules module to send an email if the checkbox was checked

Install drupal [Rules module][1]
Install drupal [Webform Rules][2]
Create a rule
On condition section you need to custom PHP to check if the checkbox was checked
Make sure that you can access the field in data selector
Chose the operation equal
For the "Data Value" field, you can input values in two modes, make sure you are using "direct input mode". You should then be able to check the checkbox that represents TRUE for that field. Translated, what you are saying is, "Is this field equal to TRUE?" You can also negate it by leaving it unchecked or using the "negate" option below.


Install Token Filter.
Got to Configuration > Text Formats and enable Token Filter ("Replace Tokens") for a text format.
In your view add Header/Footer "Global: Text Area" and choose the text format from step 2.
In the text area write [current-date:short] and optionally check [x] Display even if view has no result.

Source: https://ffwagency.com/digital-strategies-blog/how-add-current-date-view-drupal-7

To do this in the fields section use Advanced Text Formatter, which allows you to choose a text format for "Global: Custom text" fields.

Source: https://www.drupal.org/project/views/issues/1417266#comment-12245061


Try using a aliases.drushrc.php file to specify project details.

Create an aliases.drushrc.php file in one of the following places:

/etc/drush
$HOME/.drush

If you don't have /etc for /etc/drush perhaps it would work in: /Macintosh\ HD/Users/me/Documents/workspace/drush

aliases.drushrc.php contents

<?php
$aliases['dev'] = array(
  'uri' => 'dev.example.com',
  'root' => '/Macintosh HD/Users/me/Documents/workspace/drupal',
);

// or perhaps root with the escaped space char '/Macintosh\ HD/Users/me/Documents/workspace/drupal'

then from anywhere in the filesystem, you should be able to go

drush @dev dl views
drush @dev sqlc
drush @dev updb

etc..

Fully commented example drush aliases file here


Custom reference field settings in different content types

The solution a colleague proposed is to add the following code in the hook_form_alter():

$language = $form['field_user']['#language'];
$form['field_user'][$language]['#multiple'] = 0;

If you want to be a bit more aggressive on data consistency you can also hook into the form validator and check that the correct number of values is inserted.


You want to use references and something like the Inline Entity Form module.

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.


Capturing cache metadata from file_create_url?

This code seems to be OK to me until file_create_url() is transformed into a service which can handle cacheable metadata like UrlGenerator.

An easier way to avoid this error message would be to return an uncacheable RedirectResponse:

  $url = file_create_url($file->getFileUri());
  $response = new RedirectResponse($url);
  return $response;


Using Fields as Attributes in Node Templates

Is there a reason to not just set the format to "<hidden>" in the content type's "manage display"? Then it will never render but you still have it if you want it.

If you really want to do this programatically, the best practice, for me, is to use a module not your theme. Why? Because if your theme changes... do you want extra to show? Nope, so make it independent of the theme by putting it in a module.


Only Drush 8 is compatible with Drupal 8. See http://docs.drush.org/en/master/install/#drupal-compatibility


You can do this in two ways.

Option 1:
Add a textarea field to the file content type, with the necessary text options (fe html on etc), and create two various displays via Display Suite. Create a view block with the nid as contextual filter.
And select the node display for showing.

Option 2:
Install the prepopulate module and setup a rule that after saving the html content type node redirects to file content type with the right url + prepopulate information. Have 2 separate content types. In the file content type add a reference field with prepopulate settings.

Now after you create the node with html information it redirects to the file content form with the reference field filled... So no searching and no hassle.


How to send user password during registration?

This doesn't answer the question, but it has to be said.

You should not e-mail users their password.

It's highly irresponsible to do so.

There are strong reasons for Drupals default behaviour.

People tend to re-use their passwords in lots of places, and e-mails are not a secure communications channel.

If your end user re-uses the password for their VPN tunnel, and login to their e-mail over an unencrypted channel, (no https for the e-mail, and no password on the local wifi for example), then you have just broadcasted that password for the world to see. And now you've facilitated the cyber attack on their workplace. There's probably a large number of both known and unknown ways to compromise the passwords as well. NSA are practically guaranteed to get it.

Don't do it.

Yes, it's the users fault for re-using their password and not requiring HTTPS to their mail and a strong password on the wifi, but you are the developer and need to know better.


Cache busting for images in Drupal 7 and lightbox 2

OK, I solved it. Cachebuster can be implemented as discussed in shared url for drupal 7 by editing includes/theme.inc, and theme_image function. Just add attributes['src']with a random string say time().
Further, lightbox2 module can be tweaked to append random string in a href, by editing lightbox2/js/lightbox.js, just edit start: function(imageLink, slideshow, lightframe, lightvideo, lightmodal) {} and append anchor.href with new Date().getTime().

These two tweaks will make sure that drupal is giving img src appended with time and lightbox2 inserting time() in anchor href.
Browser will never cache these images.


Dynamically link /sites/default/css/css_***.css file for WordPress template header

To answer your direct question, drupal's CSS and JS aggregation contains a random MD5 hash to guarantee uniqueness, and also to guarantee that there is no programmatic way to work this out.

In order to include CSS and JS from an aggregated site into another CMS there are a couple of options:

Use un-aggregated CSS and JS and link to the files direct (bad)
Compress the files yourself and host them in a known location - e.g. /css/main-compressed.css
Or another option is what we have used in the past where you basically make a really simple page.tpl.php which includes basically no content, and is for all intensive purposes a blank wrapper for your site. You have your other CMS drag this template down after every deployment, and then used it for it's page wrapper. This way you do not need to worry about the CSS and JS changing as you always have the most up to date versions in the <head> section.

Hope this helps


How do I show an image in a Drupal 7 module?

The following code example presents how to get the full path to an image-test.jpg image included in a simpletest module.

$image = theme('image', array('path' => drupal_get_path('module', 'simpletest') . '/image-test.jpg'));


How do I make variables available for all blocks in a page?

Yes this can be done in hook_preprocess_block.

inc file:

function get_some_vars() {
  static $vars = array();

  if (empty($vars)) {
    $vars['foo'] = expensive_function_1();
    $vars['bar'] = expensive_function_2();
  }

  return $vars;
}

.module/template.php file:

function MYMODULE_preprocess_block(&$vars) {
  require_once 'my.inc'; // or module_load_include, depends where your code is

  $vars += get_some_vars();
}

It's not the exact desired workflow you described in the question, but it has a similar effect; require_once will only include the file once per request, and the variables will only be prepared once per request. There is the function call overhead, but given that themes don't have the concept of always-available-vars (as far as I know each theme call is an isolated instance as it were), I think this is the closest you'll get without patching the theme system.


How to decide in hook_nodeapi() if it was invoked after creating/updating node via Services module?

I think there's a point in the system not normally telling you this, since we want to avoid any kind of coupling between the systems. Based on that I guess there's no built in way to get the information you want. Strictly speaking, you should probably consider why you are doing what you are doing, as it's not good practice.

Possible methods:
You could implement a custom node resource, which hands over node creation to the regular services callback after having done

$node->creator = 'services';

or possibly:

$node_origin = &drupal_static('node_creation_tracker');
$node_origin = 'services';

after which you could retrieve this data with the same method. Implementing a resource is not a complicated process, but requires quite a bit of knowledge about services.


If you're on UNIX based system (e.g. MacOSX, various Linux distros), the patch utility is a great tool here. I typically use the command:

patch -p1 < patch-file.patch

With the -p1 option being important for installs already under a git repo.

It sounds like your use case is a bit different though. drupal.org has a good documentation page for applying patches in various environments.


According to realpath API, you can Get it with :

\Drupal::service('file_system')->realpath(file_default_scheme() . "://");


How to set up webhooks with the Mailchimp module

I had the same problem with my site, which is fixed now. It seems like the error message pops only if you are on HTTPS secure protocol. If you are on HTTPS try disabling it and try enabling your mailchimp lists. After you enable the mailchimp list now you can re-enable the HTTPS.

There is a bug on 7.x.3.1 version Make sure you are using the latest version 7.x.3.2

On secure pages settings you can ignore these pages loading from HTTPS.

example.com/admin/config/system/securepages

admin/config/services/mailchimp
admin/config/services/mailchimp/*


Given a book node nid, programmatically get all child node nids

To get the complete list of child node nids for the book:
use the BookOutlineStorage::loadBookChildren from the book.outline_storage service.
like the following:
/** @var \Drupal\book\BookOutlineStorageInterface $book_outline_storage */
$book_outline_storage = \Drupal::service('book.outline_storage');
$childrens  =  $book_outline_storage->loadBookChildren(NID);


I solved this by making the Content Type nodes published again.  So in my View I check to see if the checkbox is check AND if the node is Published.  The slider works as it should.  I was then left with the task of deciding if allowing access to the actual node was desirable.  Viewing the direct node in my case was not all that bad, it's not restricted content or anything but I felt it would just be sloppy.  So since I had Panels already installed, this solution https://drupal.stackexchange.com/a/19072/12881 worked out great.  If someone stumbled upon one of the nodes of that specific Content Type they're just sent to the front page.


Is this the correct way to make a panels layout

You can use Panels to create your own layout over at   /admin/structure/panels/layouts/add-flexible

This Video Tutorial covers on how to create one.

Basically, you add a column, and for each column you need to add a region. You can choose to use a flexible region or a fixed region, which you can resize by draging the grey bar.


How to implement a secure video streaming website?

This is quite a complicated problem with a lot of possible approaches; a whole book could be written about it (your question is probably too broad).

That said, have you checked out Videola?  Videola is a Drupal-based distribution for creating subscription-based websites.  It's made by Lullabot, one of the leading Drupal companies, and they use it to power their learning network, Drupalize.me.


By the time your page template is built, drupal_get_messages() has already been called (by way of theme_status_message(), which is called from template_preprocess_page()).

Since drupal_get_messages() clears the message cache unless the second argument to the function is explicitly set to FALSE, and theme_status_message() doesn't provide that second argument, the next time it's called the $_SESSION['messages'] var has already been cleared.

You already have access to $messages in your page template file, but if you're looking to get hold of each individual message you'll probably have to do this in a preprocess function:

function MYTHEME_preprocess_page(&$vars){
  $messages = drupal_get_messages(NULL, TRUE);
  $vars['message_list'] = $messages;
}


How can check if current user is node author in node template

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
   $uid = \Drupal::currentUser()->id();
   $author_id = $variables['node']->getOwner()->id();
   if ($author_id == $uid) {
     $variables['is_author'] = TRUE;
   }
   else {
     $variables['is_author'] = FALSE;
   }
}


Drupal 7: How to create a slideshow using Twitter Bootstrap Carousel?

It's very late to answer this question, but I guess it will be helpful to any other like me who seeks for assistance in creating a carousel with the use of TB(Twitter Bootstrap).
Drupal community has come up with a module called views_bootstrap or bootstrap_carousel

which will help you create a responsive carousel powered by TB and Drupal.
The instructions given in the project page should almost give you what you want cheers!


Drupal allows calls to .php files out of the box. Take a look at the .htaccess file and you will see that .php files will be handled just like any php application.

So... just create your .php file and make sure you are including it at the appropriate path.

That all said, in D8 (or in D7 + elbow grease) you get some pretty powerful autoloader capabilities out of the box so ideally you could take advantage of that in your module.


D7:

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print $block['content'];
?>

'module_name' = The machine name of the module (i.e. the module's folder name). This is true for core modules too, so for instance 'search', 'user' and 'comment' would all work here.

'block_delta' = The machine name of the block. You can determine what this is by visiting the block administration page and editing the block. The URL for editing a webform block, for instance, would be something like:

Drupal 7: admin/structure/block/manage/webform/client-block-11/configure

In this example, 'webform' is the module's name, 'client-block-11' is the block's delta.

Custom blocks will have module name of 'block' and a number for a delta, which you can also find by editing the block.

More information: http://drupal.org/node/26502

====== OR =============

<?php
//suppose 98 is the id of the block

   $block =block_load('block',98);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
   print $output;
?>


How can you get the route name/path of groups?

There is probably a *.routing.yml in the group module where you can find the route name, but routes can also be defined dynamically. So better use a tool, for the command line Drupal Console or for UI the devel module:

Install the devel module, visit the page you want to find out the route name for and click on "Current route info". The route name is in the variable _route. You find also the route parameters you might need to further narrow down the route.


I think you have a problem with plugin file organization. It should be :

content_search/src/Plugin/views/filter/ContentSearchFilterPlugin.php

...instead of

content_search/src/Plugin/Filter/ContentSearchFilterPlugin.php

And the namespace for this file should be

namespace Drupal\content_search\Plugin\views\filter;


restrict shipping of particluar item for paticular shipping zone

I'm fairly certain there isn't a module that does this. You can build this with rules, but the effect will be very rudimentary.

Create a rule reacting to order updates:

Checks for a particular product included in the order.
Checks to see if a shipping address condition is met.
For your action, display a system message.
Set the status of the order to cart or perhaps checkout:shipping.

That way you wouldn't be able to advance past the shipping status without having it fulfilled.

Not knowing your situation, cancelling an order is a bit extreme, but you could forward the user to a webform, change the status of the order to some new, internal value for review, or even just remove the product from the cart so that the customer can continue.


If you want to use a variable for the page title, it is better to use a title callback.

function menufun_menu() {
    $items['menufun'] = array(
        'title callback' => 'menufun_title',
        'page callback' => 'menufun_greeting',
        'file' => 'menufun_greeting.inc',
        'page arguments' => array('Jane', 'Doe'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
function menufun_title(){
    $tryk = 'test'; // dynamic title set here.
    return $tryk;
}


How do I integrate a Media library to Image Field?

You are looking for entity_browser.

Setup isn't that easy, so you may want to use an existing browser like media_entity_browser as a starting point.

The media library as shown in your image can be found at admin/content/media, but it's not that helpful when it comes to reusing images on a node.


The Values module is a field for users to enter their own list of values in a key-value format.

Core taxonomy module is used to create lists of terms which can be placed as a field on the registration form using a 'term reference'. This would then appear as either a select list, radios or checkboxes (checkboxes if the field is multi select).

The difference is that with Values, users enter their own values and with term reference and Taxonomy, users choose from your list of terms in the taxonomy. Which do you want? I think if you're looking for subscriptions, it's term reference and Taxonomy.


JSON through Services View- Authenticating through Parameters when accessing JSON through external app

There exit many ways of authentication through services module.

The easiest is to use session authentication by authenticating the user using his username & password, Then let the app send the cookie header in each request with the session id like COOKIE: SESS_ID:SESS_name.

Or use that module that seems matching your approach a lot services_basic_auth

Another way is to authenticate the app itself by letting the app get an access token using a secret app id and password created on the website.   using oauth2

Examples for auth methods


What's the use of creating another CKeditor profile

Because it's also possible to create as many/few text formats as you want...

If you had installed Drupal using a non-standard profile, you might not even have full_html and filtered_html as text formats, and the CKeditor profiles would be different.

If you don't know why you need to add one...don't add one :)


D7 theme field items of a "List (text)" input as

The "right" way of rendering a list, that is, one that interacts properly with all the other systems in Core is theme_item_list.

Code example:

// In this case, $result is a list of nodes returned from a database query.
$list = array();
$list['type'] = 'ul';
$list['title'] = 'List of nodes';
$list['attributes'] = array('class' => array('list-of-nodes'));
$list['items'] = array();
foreach($result as $record) {
  $list['items'][] = l($record->title, 'node/' . $record->nid);
}
$output = theme('item_list', $list);

This should be applicable in your node.tpl as well.


Ajax not getting triggered on change event of selectbox field

For select list, the ajax should be
$form['field_select_box']['widget']['#ajax'] = [
  ...
];

and please try to code as Drupal standard.


How to change the button name after click on it using ajax

In hook form alter define your submit value . Below is small piece of code .

   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
     '#prefix' => '
',
     '#suffix' => '
',
    '#ajax' => array(
        'callback' => 'example_ajax_form_callback',
        'wrapper' => 'div-example',
         'method' => 'replace',
      ),
     );

function example_ajax_form_callback($form, &$form_state) {
  $form['submit']['#value'] = 'New value';
    return $form['submit'];
  }


How do I clear settings from the Drupal object?

drupal_add_js adds javascript to the page <head>, so as far as I know you can't change that anymore with AJAX. Thus placing it in an AJAX callback doesn't work. You need to solve this at Javascript level in the the browser.

You'll have to make sure all data for all options is sent to the client during rendering and then use simple jQuery selectors to enter the correct part of data into the visualizer.


Restrict content access by term reference in profile

Turns out I went with Access by Terms module after finding that the Term Access module did not work for me.  Access by Terms also has permissions the make the field editable by certain roles in the profile and nodes, so that takes care of administration requirements too.


How to get the node id the comment is attached to in hook_comment_insert?

the correct way to load nid is,

$entity->get('entity_id')->target_id

and not

$entity->get('entity_id')->value

In case of doubt which key to use,

try,

$entity->get('entity_id')->getValue()

and inspect the returned value.


Configure connection to mongodb for querying only

You don't need to set a function in settings.php to define the connection. The documentation lists this as an example:

https://fgm.github.io/mongodb/install/#settings-configuration

// In sites/default/settings.local.php.
$settings['mongodb'] = [
  'clients' => [
    // Client alias => connection constructor parameters.
    'default' => [
      'uri' => 'mongodb://localhost:27017',
      'uriOptions' => [],
      'driverOptions' => [],
    ],
  ],
  'databases' => [
    // Database alias => [ client_alias, database_name ]
    'default' => ['default', 'drupal'],
    'keyvalue' => ['default', 'keyvalue'],
    'logger' => ['default', 'logger'],
  ],
];


You want the Subpath Alias module.

  For example, if node/1 is aliased to
  content/alias, this module rewrites
  the link to the node edit page
  node/1/edit to use the aliased URL
  content/alias/edit instead.


Is there any Russification of the Simple MCQ Drupal 7 module?

It looks like it is partially translated: Translate Simple MCQ to Russian.

To import the translation that exists into your own site, enable the core Locale module and add Localization update.  You can now use the standard Drupal translation site interface to translate the bits that are not translated.

Please help the community by adding your own translations to Localize.Drupal.org


Views - how to display a column showing who made the last update

Edit your content type's Publishing options & enable 'Create new revision'.
In Views' Advanced pane, add a Relationship of type 'Content revision: User'.
Under Fields, add the field 'User: Name' AND use the relationship you just created.

Voilà!


My suggestion: You could make this a great deal easier for yourself if "Has payed" a field on the User entity instead.

Answer to your question: You need to expose the custom table to Views, by telling Views that it exists and what type of data there is in it. The canonical way of doing that is with hook_views_data, although the Data module claims to be able to do this automatically.

Once you have the data in Views, you create a View based on "User", and add a "Filter" to remove all users in the "Payed" table.


How do I get the form submitted data in a custom module?

You have to get submitted data based on sid, I think below code will be helpful for you

 function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'WEBFORM_'){
module_load_include('inc','webform','includes/webform.submissions');
$sid = 10;
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;
}


How to display the user email on account pages?

You can implement the following hook in the template.php of your theme:

/**
 * Process variables for user-profile.tpl.php.
 *
 * The $variables array contains the following arguments:
 * - $account
 *
 * @see user-profile.tpl.php
 */

function YOUR_THEME_preprocess_user_profile(&$variables) {
  $account = $variables['elements']['#account'];
  //Add mail to $user_profile variable
  $variables['user_profile']['mail'] = $account->mail;
  // Preprocess fields.
  field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

And in your user-profile.tpl you can use:

print $user_profile['mail'];


How to prevent duplicate entity reference items from being entered on a field?

Using form alter, you could add an #element_validate function to the field.

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

  if (isset($form['field_articles'])) {
    if (empty($form['field_articles']['widget']['#element_validate'])) {
      $form['field_articles']['widget']['#element_validate'] = ['mymodule_prevent_duplicate_entity_reference'];
    }
    else {
      $form['field_articles']['widget']['#element_validate'][] = 'mymodule_prevent_duplicate_entity_reference';
    }
  }
}

Then in your custom validation function, if there are duplicate entity reference items, set a form error.

function mymodule_prevent_duplicate_entity_reference(array &$element, FormStateInterface $form_state, array &$complete_form) {

  $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

  $ids = array_filter(array_column($input, 'target_id'));

  // Check that there aren't duplicate entity_id values.
  if (count($ids) !== count(array_flip($ids))) {
    $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
  }

}

If you would like to create a reusable widget, you could extend one of the entity reference widgets, for example,  EntityReferenceAutocompleteWidget:

namespace Drupal\mymodule\Plugin\Field\FieldWidget;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Component\Utility\NestedArray;

/**
 * Plugin implementation of the 'entity_reference_autocomplete' widget.
 *
 * @FieldWidget(
 *   id = "no_duplicate_entity_reference_autocomplete",
 *   label = @Translation("Autocomplete - Disallow Duplicates"),
 *   description = @Translation("An autocomplete text field that validates against duplicates."),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class NoDuplicateEntityAutocomplete extends EntityReferenceAutocompleteWidget {

  /**
   * {@inheritdoc}
   */
  public static function afterBuild(array $element, FormStateInterface $form_state) {
    parent::afterBuild($element, $form_state);

    $class = get_class();
    $element['#element_validate'][] = [$class, 'validateNoDuplicates'];

    return $element;
  }

  /**
   * Set a form error if there are duplicate entity ids.
   */
  public static function validateNoDuplicates(array &$element, FormStateInterface $form_state, array &$complete_form) {

    $input = NestedArray::getValue($form_state->getValues(), $element['#parents']);

    $ids = array_filter(array_column($input, 'target_id'));

    // Check that there aren't duplicate entity_id values.
    if (count($ids) !== count(array_flip($ids))) {
      $form_state->setError($element, 'Field "' . $element['#title'] . '" doesn\'t allow duplicates.');
    }

  }
}


I had similar issue with emails sent from webform module (Drupal 9.0.7 & webform 6.0.0-alpha20), solved using following steps.

Install and enable Mail mail module https://www.drupal.org/project/mimemail
Ensure email format is "Full html" at /admin/config/system/mimemail
Go to /admin/config/system/mailsystem and choose "Mime Mail mailer" for
"Formatter" and "Sender" fields under default mail settings.
In your webform, go to settings-> Email/handlers -> Advanced tab. Make sure "Send email as HTML" is checked.


On quantity change, create individual line items of the same item in Drupal Commerce cart

It would be possible to create a new views handler based on commerce_line_item_handler_field_edit_quantity that worked the way you want, but IMHO it would be weird from a UX POV to enter 5 into the quantity textfield of 1 line item, submit, and then see 5 distinct line items with quantity 1.

A simple alternative would be to modify the cart view to have something like an Add 1 more button:

Remove the quantity field;
Add a relationship to the product;
Add the product's add to cart form as a field;
Configure the field to not combine products (and you can also modify the text here, eg Add 1 more).

I haven't tested this, but I think it should work.


How to get all records of a view with paging?

If you don't mind installing another module, try Views Bulk Operations.  Views Bulk Operations (often abbreviated VBO) allows you to add "select all on page/select all everywhere" checkboxes and also offers additional functions such as using batch API to process operations when there are too many to do at once (if you had 20,000 records instead of 20).

Node One has a tutorial on VBO.


Access denied PDO Exception - other users are getting it but not me

Have them check sites/default/settings.php and see if the credentials for your database user (assuming 'root') are correct.

If it is, they should also be checking to see if:

The user 'root' has access to the local database and
Root has that same password as an sql user


How to add twitter tracking code to a Drupal site?

The proper way is to use hook_page_alter() in your template.php or a custom module. But there's also a module out there to accomplish this task:

Take a look at the module Tracking Code. It allows you to inject arbitrary code inside <HEAD>, after <BODY> or before </BODY>.


how to make multiple ajax callbacks from a drop-down field?

In your ajax_command_replace where the form is rendered, do this: ajax_command_replace("#checkboxField", render($form['checkboxField']['values']=$text)), where $text is the value from the checkboxes, as shown below:

function ajax_checkbox_callback($form, &$form_state) {
    return array(
    '#type' => 'ajax',
    '#commands' => array(
    ajax_command_replace("#checkboxField", render($form['checkboxField']['values'] = $value_text_form_text_field_1)),
    ajax_command_replace("#txtField", render($form['txtField']['values'] = $value_text_form_text_field_2))
    )
  );
}