How to load a file located in core/includes? I'd like to execute PHP code that requires functions available in the includes files of core located in core/includes.

I found ModuleHandler()->loadInclude() and module_load_include() but I am afraid this 2 options can load files from core/modules directory only, according to the doc, but may be I misinterpreted it:

  Loads a module include file.

For example if I execute:

\Drupal::moduleHandler()->loadInclude('core', 'inc', 'install');
drupal_rewrite_settings(); // the func that I want located in install.inc

I get:

Call to undefined function drupal_rewrite_settings()

which means install.inc has not been loaded.

You can use a good old fashioned include_once (or require_once):

include_once DRUPAL_ROOT . '/core/includes/install.inc';

Core uses the same method any time it needs to source a file in core/includes. Case in point, ModuleHandler::loadInclude itself does exactly that if the file extension provided is "install":

public function loadInclude($module, $type, $name = NULL) {
  if ($type == 'install') {
    // Make sure the installation API is available
    include_once $this->root . '/core/includes/install.inc';
  }

  ...


Displaying uploaded files Preface -- I'm a newbie with drupal and have watched too many youtube flicks on jCarousel and slideshows.  So totally confused.

My question:
I've created a web form in drupal 7 and would like to do a jCarousel of all the images that have been uploaded via the web form.  Is there a way to point to a directory and have the jCarousel load the image files.  I tried creating a view with show files, but it didn't load the image files.

I'm trying to do this without css or javascript.  I don't pantheon service provider will let me add javascript (I think).

Thanks in advance.

I figured out how to display the image file in the jCarousel.  In a view add the file:Name field and set the style settings to HTML and add the image source hmtl  tag to rewrite results.  Example:


extract a field and the link to content from all nodes i have a content type and it stores user_email,title,body etc.

Every node has a URL alias.

How can i go through all the node, and extract the email field + the URL of that node.

any clue  .
thanks

If you want get node of page content type ,you can try another content types

$type = "page"; // machine name for Basic Page
$nodes = node_load_multiple(array(), array('type' => $type));
$arr=array();
foreach($nodes as $node){
     arr[$node->nid]['email']= $node->field_email['und'][0]['value'];
     arr[$node->nid]['url_alias']= drupal_get_path_alias('node/'. $node->nid);
    }


Best method to enable/disable modules depending on the environment What would be the best solution to enable/disable modules depending on the site environment (dev, stage or production)?

Created a database dump containing the system table for each installation. Then when deploying I use mysql -uuser -ppass database < dump-<type>.sql where the type reflects the kind of environment.
Created a shell script for each environment, that uses drush to enable or disable needed modules and set specific site settings.
Wrote a small deploy script for each site that looks something like this:

// change working directory to drupal installation path
chdir('public_html');

// define root, include bootstrap.inc and start drupal
define('DRUPAL_ROOT', getcwd());
require_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// modules that should be disabled/enabled on stage site
$modules = array(
   'field_ui' => 1,
   'toolbar' => 1,
   'update' => 1,
   'overlay' => 0,
   'feeds_import' => 0,
   'feeds_ui' => 0,
   'feeds' => 0,
   'menu' => 1,
   'advanced_help' => 1,
   'job_scheduler' => 1,
   'wysiwyg' => 1,
   'views_ui' => 1,
   'dblog' => 1,
);

// enable/disable modules and set site specific variables
foreach ($modules as $module => $state):
  if ($state == 1):
    if (!module_exists($module)):
      module_enable(array($module), FALSE);
    endif;
  else:
    if (module_exists($module)):
      module_disable(array($module), FALSE);
    endif;
  endif;
endforeach;

variable_set('error_level', ERROR_REPORTING_DISPLAY_ALL);
variable_set('preprocess_css', 0);
variable_set('preprocess_js', 0);
variable_set('cache', 1);
variable_set('page_compression', 0);
variable_set('block_cache', 0);

Does anyone have a better solution?

One possible answer is the Environment module (the 7.x dev release works just fine). It allows you to define arbitrary environments (comes configured with "Development" and "Production", but you can have more if necessary). It then provides drush environment-switch to switch between environments. You can then implement hook_environment_switch() to do anything you want when the environment is switched. There's no built-in support for enabling and disabling modules, but that's easy enough to do in code, as you demonstrate above. It's also convenient for doing things like changing variable values and blocking development users.

You then put something like drush environment-switch production in your deploy steps.

This also has the benefit of being able to switch back to Development easily. For instance, I have views_ui disabled in Production, but enabled in Development. If I need to urgently check a view in the ui on the production site, I can switch the environment to Development, do what I need, and switch back.

It's also nice that since it's implemented in hooks, you can keep different types of functionality in different modules, and you can keep these things in the code base and under version control.


How to resolve the SSL error with local copy of site on Dev Desktop? I am running a local copy of my site on Acquia Dev Desktop and everything is working fine.

The site is set to enforce SSL connection when logging in to the sitename.com/admin page. However, since it is now installed on my localhost, it does not have an SSL certificate and throws the error like so:

SSL connection error
Unable to make a secure connection to the server. This may be a problem with the server,
or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR

What can I do in order to get around this, and log in to my page administratively?

DevDestop now supports this.
https://docs.acquia.com/dev-desktop2/sites

Acquia Dev Desktop now provides simulated HTTPS support using a self-signed SSL certificate, which supports local testing and development of websites that rely on SSL. Learn more.

Just download a new version of DevDesktop. I'm currently on Version 2, Control panel rev: 032976b and have it working with sites that use SSL.


Warning of the permission in Aegir I'm trying to add a site with Aigir and i'm getting this warning:

Warning in features rebuild of permessi. No module defines permission "create article content".

Warning in features rebuild of permessi. No module defines permission "create slides content".

Warning in features rebuild of permessi. No module defines permission "delete any article content".

Warning in features rebuild of permessi. No module defines permission "delete any slides content".

Warning in features rebuild of permessi. No module defines permission "delete own article content".

Warning in features rebuild of permessi. No module defines permission "delete own slides content".

Warning in features rebuild of permessi. No module defines permission "delete terms in tags".

Warning in features rebuild of permessi. No module defines permission "edit any article content".

Warning in features rebuild of permessi. No module defines permission "edit any slides content".

Warning in features rebuild of permessi. No module defines permission "edit own article content".

Warning in features rebuild of permessi. No module defines permission "edit own slides content".

Warning in features rebuild of permessi. No module defines permission "edit terms in tags".

all permissions are exported with features & features_roles_permissions.
the problem is on the new created site this permissions are not set for any of the roles set in the module.
any idea?
thanks

It looks like the issue is that the permissions are created before there are defined (since you need to have the content types created before the permissions are created).

This could be fixed with proper dependencies (since the feature with the permissions depends on the feature(s) with the content types.


What file or data I should NOT give outsourcing developer for security when they need a copy site of my site? I'm asking a outsourcing developer to modify some part of my site and then he needs the copy of my site as a test site.
My site is already working site and has users registered. What comes in mind first is deleting user table from database to protect the personal information.

And the what else I should NOT give the developer? I trust the one who works on my site of course. But in generally is there any files or database table that can be harmful if　the third party obtains?

Deleting the user table might break features that rely on node authors or some other user information. Try setting every user's email to email@mail.com and their password to 'password'. You shouldn't give the settings.php file, since it has your database credentials and the cryptographic salt Drupal uses to hash users' passwords.


Show a webform input if user selects certain option from select list? Im making a webform with a select list. If you chose a certain option in the select list I need a text input field be be revealed.

Can this be done by Drupal or should I write some jQuery to show / hide the input?

Update to a newer version of Webform where webform_conditional has been merged.

  Description: This modules enhances the existing Conditional Rules of
  the Webform Module. It adds the ability to make components dependent
  on select components(i.e. listboxes, radio buttons, and checkboxes)
  that appear on the same page.

  Important As of Webform version 7.x-4.0-alpha2 this module has been merged into Webform and is no longer necessary. The 7.x-2.x
  version of this module handles this upgrade. See: #1616376: Create
  Migration to Webform 4.x

Then when you make a webform node you will have additional local task labeled conditionals. Once you've added form fields to the webform -- you can set conditions using the administrative form found there.


How can I find all the listeners or subscribers to the KernelEvents:REQUEST event? More specifically, how could I find the subscribers performing the routing system for Drupal?

We tried using ddebug_backtrace(), but I couldn't get anything.

Instead of ddebug use the Symfony Webprofiler, that is included in the D8 version of the module Devel:

https://www.drupal.org/project/devel

WebProfiler (D8+)

Add a powerful footer to all pages of your site. There, admins can review resource utilization, cache effectiveness, database queries, Views, and so much more.


pass cck email value to webform block I currently have 2 webforms displayed on a page - these are inserted dynamically from a node.tpl.php file.

However, I also have a cck field on the current node for an email address - I would like to be able to pass this email value directly to the "Email To" field of the webform.

This would create a new email recipient depending on which node you were viewing. For example:

The "About Us" page contained the field "email: hello@mydomain.com" - therefore the webform loaded in the sidebar would be sent to this address.

The "Location" page contains the field "email: location@mydomain.com" - now this would be the email address that receives any submissions from that page.

The idea is to have 1 webform and dynamically change the email its sent to based on a cck field. Is this possible at all?

Thanks,
Garry.

In your webform add an "email field" for the recipient (say email_recipient).
Go to node/123/webform/emails to set the recipient to be your previously created field.
Create a hook_form_alter to put the email address you your webform field.

<?php
function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  //you need to set up a CUSTOM module to store this.
  //use devel with dsm($form); to figure the name of each field
  if ($form['#id'] == 'webform-client-form-123') {
    //load the node from the url
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node_email = node_load(arg(1));
      //set your webform field to your email
      $form['submitted']['con_email_recipient']['#default_value']
           = $node_email->field_email_recipient[0]['value'];
    }
  }
}
?>

Add some CSS to hide the field, and it should work, code untested but I'm pretty confident about the steps, also have a look at Working with Default Values.


Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason? Somehow, edit/delete has been changed to node->title/edit or node->title/delete for one of my project. Can anyone have idea what could be a reason?

Any lead towards the debugging would be appreciated.

On one of my projects, for this kind of functionality I have used Sub-path URL Alises module. Maybe it's enabled on your project ?


Views image fields render slow causing overlaping results I have a view displaying some content fields including images being used as the background. I also have 2 attachments with the same fields.

When i visit the page for the first time, or when i do a hard refresh of my browser (hold shift and refresh) the main content and the two top attachments squish together. if i then refresh all looks ok.

Im using bootstrap theme as my base theme. If I disable my CSS file, the error still occurs.

I was thinking it had something to do with the image resizing and loading later than the text content.

Please let me know if you need more information.

http://dev-tangrm-test.pantheonsite.io/

This is not a views or a Drupal issue...

Things to do are:

Make sure the image size in terms of KiloBytes is not huge. If you
have fairly large sizes this will affect your site speed in general,
especially on mobile devices.
Make sure you are using an appropriate Image Style. Meaning the size of the image you are rendering, in terms of pixels is not
bigger than the container you are rendering in it.
In any case to remove this overlapping effect set a static height to the container the image is rendering into. In this way the text
is not going to overlap even if the images are still rendering.

Hope this helps.


Template file naming with alias I have a few template node overrides in my theme using Drupal 7.

For example: page--node--53.tpl.php

This might be a lazy request, but is there anyway to name these files instead with the alias I have chosen rather then using the node number? That way I don't have to memorize all of the associated pages.

For example page--node--about.tpl.php

In THEMENAME_preprocess_page (in template.php located in your themes directory) you can set as many template hook suggestions as you wish. Drupal then goes through the list from bottom to top and once it finds the existing template suggestion, it stops and uses that one.

function THEMENAME_preprocess_page(&$vars) {
  // Add theme hook suggestions based on path for nodes only.
  if (isset($vars['node'])) {
    // get whatever you want here into $path variable
    $path = $vars['node']['type'];
    $vars['theme_hook_suggestions'][] = 'page__node__' . $path;
  }
}

in the $vars there should be the node object that you can check for
$vars['node']. also don't forget to sanitize anything you are adding there. good choice would be to use the drupal_clean_css_identifier function


Calculate Database Field Value and Send to Views as New Field I have a database field which stores a timestamp. This timestamp is sent to a custom views provider via hook_views_data(). This timestamp field is created as a date field to utilize the date format options from views.

$data['module']['timestamp'] = [
  'title' => t('Timestamp'),
  'help' => t('Timestamp from module'),
  'field' => [
    'id' => 'date',
  ],
  'sort' => [
    'id' => 'date',
  ],
  'filter' => [
    'id' => 'date',
  ],
];

In another views field (but with the same DB field), I would like to get the raw field value and run it through something like:

if (field_value > (time() - 800))

This is a custom module and would prefer not to have any more dependencies. Can this be achieved with hook_views_data() or hook_views_pre_render() or such?

I know there is a contributed module https://www.drupal.org/project/computed_field, but again hoping there is a way in those hooks, or in the view...

The DB table is created with hook_install() and the desired timestamp field output after check would be markup. Happy if it is just sent as markup to the views field.

I've figured how to access the field values with hook_views_pre_render() as such:

function hook_views_pre_render(&$view) {
  $result = $view->result;
  foreach ($result as $key => $row) {
    kpr($result[$key]->field_name);
    if ($result[$key]->timestamp > (time() - 800)) {
      // Can I do anything here?
    }
    else {
      //
    }
  }
}

Unfortunately, that is not the most important piece of the puzzle. And it is not possible to just add $data['module']['key'] to my hook_views_data() as this requires the unique DB field to exist.

In my use case, I'd be happy if I could rewrite the original timestamp field and append this markup to it.

Take a look at this, it shows how you can create custom fields that you can use within views https://www.webomelette.com/creating-custom-views-field-drupal-8

I've followed this recently and seems to work well


How do you change the default sort in apachesolr? I've been trying to get this figured out for a couple days now, and I feel like I'm close, but as of yet no cigar. I need to make the apache solr search on the site I'm working on to have two sorts, 'created' and 'score'. The default search sort is score, but I need to change it to created.

I've got as far as changing the default itself, but then change is added unconditionally, so obviously it will always occur over score. Do I have to rebuild all the URLs to use arg, or is there an easier way? Here's my code:

Note: there's some code to remove some filters, but that's not related to the problem. I included them just in case.

   function myhook_apachesolr_prepare_query(&$query, &$params) {
     // Remove sorts
     $query->remove_available_sort('type');
     $query->remove_available_sort('sort_title');
     $query->remove_available_sort('sort_name');
     // Rename/Reorder sorts
     $query->remove_available_sort('created');
     $query->remove_available_sort('score');
     $query->set_available_sort('created', array('title' => t('Most Recent'), 'default' =>     'desc'));
     $query->set_available_sort('score', array('title' => t('Most Relevant'), 'default' => 'asc'));

     // Change the default sort to by date
     $query->set_solrsort('created', 'desc');
   }

You can implement hook_apachesolr_query_alter() and add new sort criteria as below

/**
 * Implements hook_apachesolr_query_alter().
 */
function my_module_apachesolr_query_alter($query) {
  $query->addParam('sort', 'ss_date_field asc');
}


Displaying a block only for nodes of a specific content type, how do I check the content type using PHP? I have a block which I would only like displayed on a KYN node. I'm currently using the option to display the block only on pages with "node/*" which worked when I only was using one node type but now that I have two (kYNs and Pages) I need to come up with a solution.

I'd like to use some PHP that returns TRUE when the content type of a node KYN.

How can I achieve this?

// Only show if $match is true
$match = FALSE;

// Which node types
$types = ['kYn'];

// Match current node type with array of types
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  $node = node_load($nid);
  $type = $node->type;
  $match |= in_array($type, $types);
}

return $match;

source : http://drupal.org/node/115419


Drupal 7 permission to editor type user showing certain admin menus I have created the editor type user and now I would like to show only content menu and block menu to show in administrator area. But even I have change the permssion but top admin menu is not showing. if i assigned the admistrator role to editor user whole administrator menu showes up. but I only want to show certain options in top menu.

How can I do this.

sorry for being stupid. if you give the rights to "toolbar" in permission area. toolbar will show up :) you can also use Content access


Change directory where MySQL saves its data Is there a way to get Acquia Dev Desktop to save the MySQL data to a different location other than the one it chooses by default?

Imagine to reinstall Acquia and thus needing to save the MySQL data from a Drupal instance into an alternate drive.

Acquia Dev Desktop places the database in C:\Program Files (x86)\DevDesktop\mysql\data.

Looking into the preferences, the config files contain the following.

[client]
port=33067
user=drupaluser

[mysql]
max_allowed_packet = 128M

[mysqldump]
max_allowed_packet = 128M

[mysqladmin]
user=root
port=33067

[mysqld]
pid-file="C:/Program Files (x86)/DevDesktop/mysql/data/mysql.pid"
log-error="C:/Program Files (x86)/DevDesktop/mysql/data/mysql.err"

# The TCP/IP Port the MySQL Server will listen on
port=33067

#Path to installation directory. All paths are usually resolved relative to this.
basedir="C:/Program Files (x86)/DevDesktop/mysql"

#Path to the database root
datadir="C:/Program Files (x86)/DevDesktop/mysql/data"

#set innodb as default
default-storage-engine=InnoDB

innodb_log_buffer_size=32M
innodb_buffer_pool_size=512M
innodb_log_file_size=32M

innodb_file_per_table=1

#Max open files
open_files_limit=10000

#Max packets
max_allowed_packet = 128M

#The log buffer is written out to the file at each commit. Flushing on the log file takes place once per second
innodb_flush_log_at_trx_commit=2

#Enable slow query log
long_query_time=1
slow_query_log=1
slow_query_log_file=slow.log

If the data directory is changed, then I get the following error.

Stopping the Acquia Dev server and moving/copying the files form the original data directory to the new data directory appeared to address the issue - thanks to cilefen for help

The following lines were updated to reflect the new location of the data directory

[mysqld]
pid-file="<<new path>>/data/mysql.pid"
log-error="<<new path>>/data/mysql.err"

and

#Path to the database root
datadir="C:/Program Files (x86)/DevDesktop/mysql/data"


CRUD operations with custom fields I am using Services 3.x with Drupal 7 and trying to expose a custom field added to the User object through the services. What is the easiest way to implement it for all operations (create, retrieve, update, delete)?

After the field has been created you will see the field on retrieve user resource (not index), and you will be able to send data on crud operations.


View not displayed for other roles I have a block view that displays own articles created (this view is inside a panel page). But this view didn't displayed for other users except administrators, or when I check the permission 'Bypass content access control' to the other roles.

You know that this permission is a risk when it's checked, and I won't that other users have access to everything for nodes.

I checked the permissions like that :

inside the Views UI edit page : access option => View published content (I changed to 'none' also)
inside user permission page : "View published content" && "View own unpublished content" of "node" section are checked (also other permissions : create new article, edit own article ...)
there is no restriction in the block settings for a specific role.

Is really weird what happen here.
doese anyone have this problem before? Or how you can advise me to resolve this permission issue?

Thanks in advance.

ADD:

this is a list of modules in the website:

EDIT

I found from where is this problem :
my articles are not yet published and only published articles are shown in the view content. I made sure that the permission "view own unpublished content" is checked, but content still not shown when i unpublish again the articles (views content is not shown to the AUTHOR of these nodes)

I found this module to grant users to see all unpublished content but this is not good for me, because i need users to see only their content.

Any ideas ?
Thanks in advance.

My best guess is that you haven't configured the contextual filter on author_id in views. and take it for logged users. In that case it will show the other users pages aswell


Page body content updated only after second load I want to programmatically update the HTML contents of a page (a node of bundle type 'page') on my Drupal 7 site, by doing the following:

function my_page_generate() {
   // Find and load the page I want to update (can't do it by nid since
   // it might differ)
   $query = new EntityFieldQuery();
   $entities = $query->entityCondition('entity_type', 'node')
   ->propertyCondition('type', 'page')
   ->propertyCondition('title', 'Last News')
   ->propertyCondition('status', 1)
   ->execute();
   $node_key = array_keys($entities['node']);
   $node = node_load($node_key[0]);

   //Update its HTML contents
   $node->body[LANGUAGE_NONE][0]['format'] = 'full_html';
   $node->body[LANGUAGE_NONE][0]['value'] = '<h1> BREAKING NEWS </h1>';

   node_save($node);

   return node_view($node, 'full');
}

This method is called when requesting a URL by using the hook_menu hook, like this:

function my_module_menu() {
   $items = array();
   $items['last-news'] = array(
    'title' => 'Last News',
    'page callback' => 'my_page_generate',
    'menu_name' => 'main-menu',
   );

   return $items;
}

However, when I navigate to /last-news on my site, the old contents of the page are displayed. If then I reload the same page again (using the same path), the new contents I created show up. I have tried to disable the page cache for this page by calling $GLOBALS['conf']['cache'] = FALSE, but it keeps showing the same behavior.

Any ideas how to solve this?

Check http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_view/7

You should clear cache programmatically if you want to use current solution or just load node again (http://api.drupal.org/api/drupal/modules!node!node.module/function/node_load/7) after save.

Third argument of node_load must be true


Config split ignore dependencies I'm using the config_split module to split configuration to an installation profile, that I use in multiple Drupal sites.

I have 2 sites using the same installation profile, both using the same config split settings.

Here's a list of configuration that I have split to the profile.

The content type (article)
Taxonomy vocabularies
Media types
Media library views and settings

I have 4 content types on one of the sites, but I only want to split the article content type.

The problem is that some fields from the other content types are automatically split because they depend on either media or taxonomy.

This is the node configuration that I'm splitting:

  core.base_field_override.node.article.*
  core.entity_form_display.node.article.*
  core.entity_view_display.node.article.*
  core.entity_view_mode.node.article.*
  field.field.node.article.*
  field.storage.node.article*

All fields from the article content type are all named article_FIELD_NAME.

How can I avoid that config split also splits depending configuration?

I solved that problem using Features for Drupal 8 as suggested by @leymannx.

I have exported media, taxonomy and the article content type to one feature that I can now use across multiple sites.

The cool thing is that configuration still lives in the config_sync directory, so other content types that depend on media and taxonomy don't need to be exported to features as well.


Display different account fields for my account vs public account How can display/hide some fields when viewing an account that isn't the current user vs. is the current user (e.g. the users/steve vs /user)?

I want to have a public profile that shows most of the same fields but hides a few fields that only the 'current' user can see.

Field Permissions

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

You would want to use the view own value check and view any value unchecked.


Role based User profile template I would like to have a different user template for each role, but I can't figure it out how do do it.

I've added a preprocess function in my themename.theme like this:

function ras_preprocess_page(&$variables) {

    $variables['role'] = \Drupal::currentUser()->getRoles();
}

and then used role in my user.html.twig like this:

{% if role == 'administrator' %}

Hello, admin

{% elseif role == 'anonymous' %}

Hi, stranger

{% endif %}

But it doesn't work as I would expect.

You can use hook_theme_suggestions_HOOK_alter() like below:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $roles = \Drupal::currentUser()->getRoles();
  if (in_array('YOUR ROLE',$roles)) {
    $suggestions[] = 'user__'.ROLENAME;
  }
}

and you have to create

  user--YOURROLE.html.twig

in order to get a specific template for the user based on their role.


How to create a custom Webform handler to submit to a SOAP API I have a Webform that when submitted needs to be posted to a SOAP web service. I have search for a bit of direction but I can't seem to find anything about SOAP and Drupal 8/Webform. Can anyone point me in the right direction to create a custom handler to submit to SOAP.

I'm using Drupal 8.6.16 and Webform 8.x-5.2

In your custom module add a folder src/Plugin/WebformHandler and create a file Subscription.php. Add the following code:

<?php
namespace Drupal\<mycustommodule>\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "subscription",
 *   label = @Translation("Subscription"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Administers subscriptions via SOAP"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

class Subscription extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  const SOAP_URL = 'x'; // url of soap call here

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // The data to send to the API
    $values = $webform_submission->getData();
    $email = strtolower($values['e_mail']);
    $first_name = $values['first_name'];
    $last_name = $values['last_name'];

    // Add your SOAP Call here
    $client = new SoapClient(self::SOAP_URL);
    // .. Go on here
  }
}

Enable the module and clear cache. Now, in your webform backend, go to settings and then emails / handlers (/admin/structure/webform/manage//handlers). Add your handler here. For a little more detail and instructions, see: https://stefvanlooveren.me/blog/how-create-mailchimp-subscription-drupal-8-webform-module


DC2 Tax rate configuration DC2 - latest
I have promotions (discounts/coupons) working so can see adjustments etc.
I have set up a custom tax type - 20% and territory - UK
set values on my Order item types (Physical goods, Digital goods,Services,Events)
* How are these values related to assigning tax on a product in cart?

I can add a tax manually via order UI as admin.
I'm not seeing tax entries on checkout, and no tax entries in adjustments table (other than manual one).
* How is link between tax and order made?
thanks

Answer to second question is that the tax cannot be calculated until Billing address is present (as depends on 'territory' of store & user) - so tax line is not seen initially until user reaches review stage.  Once the tax (as an 'adjustment') is added to order, it then stays visible - eg if user goes back to cart to add/remove items. The tax value then gets updated to reflect new cart contents on clicking 'Update cart', or clicking Checkout.


change field value in a view using preprocess_views_view_fields I'm trying to change the value of a field in a view programatically but i find some problems.

first is  that even though I created a Global: custom text field which field id is 'nothing', It's value remain unchanged and the value is applied to a new field created at the end of the view.
Second is that this function creates some errors and drupal send lots of notices:

  Notice: Undefined property: stdClass::$wrapper_prefix in include()
  (line 32 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).

  Notice: Undefined property: stdClass::$label_html in include() (line
  33 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).

  Notice: Undefined property: stdClass::$wrapper_suffix in include()
  (line 35 of
  /my/path/sites/all/modules/views/theme/views-view-fields.tpl.php).

My code is:

function real_estast_sub_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];

  foreach ($view->field as $id => $field) {

    // change the global custom text content depend on result (node id)
    if ($vars['row']->nid == 1625){
      $vars['fields']['nothing']->content = '666€';
    }else{
      $vars['fields']['nothing']->content = $vars['row']->field_data_field_price_field_price_value."€/noche ";
    }
  }
}

What's the problem here? I tried to follow all the steps explained in:

How to insert values into Global custom text field of views programmatically?

  Edit:   I soolved the notices form drupal by adding:

  $vars['fields']['nothing']->wrapper_prefix = '';
  $vars['fields']['nothing']->wrapper_suffix  = '';
  $vars['fields']['nothing']->label_html = '';

  But it's like I'm defining a totally new field instead of assigning a
  value to the existing one

You are probably not accessing the fields array correctly, and creating your own additional renderable array within $vars.

Install the Devel module if you haven't already and put

dpm($vars);

at the top of your function.  That will allow you to view the structure of the object on the screen (make sure you're logged in as user 1).


How do I create hierarchical select for state, district, city, and location using AHAH? I have a site for Indian tour places where I need to add the information for the "Location" content type.
For example, in http://www.indiantourplaces.com/andhra-pradesh/hyderabad/hyderabad/saroornagar-lake-51.htm we have the information for the location "SAROORNAGAR LAKE" which is located in India (country), Andhra Pradesh (state), Hyderabad (district), Hyderabad (city). I want to create all the above state, district, city as different nodes, and when I add the location details, I want to first select the state; then another list box will be populated with the list of districts which are present in that state, and once the district has been selected, another list box will be populated with the list of cities present in that district.

I am stuck up with this from may days.

It seems Hierarchical Select does exactly what you need.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!


Programatically create user that needs admin aproval When creating a new user with user_save, it seems to get the "approved" role automatically, even though I pass an empty array to $user->roles.

How can I force the programatically created user to need admin approval before being activated?

Step1

Not need to follow it compulsary

You don't need any third-party modules. Drupal core has the option to verify the email the user enters, and the option for the administrator user to approve the accounts users create. In Drupal 7, those settings are on /admin/config/people/accounts.

Step2

Once you prepare your $user object and use it on user_save function you have to follow below steps to send the mail.

$userData = user_save($user);
$account = user_load($userData->uid);
$op = 'register_pending_approval';
$status = _user_mail_notify($op, $account);


Replace frontpage to a page with wildcards I've created a page that receives a term name argument and displays a panel with several views which serves content according to this term name.

The thing is, I want to make that page my default frontpage, with a default term, but everytime I try setting it Drupal sents an error message:

  You cannot make this page your site home page if it uses %
  placeholders.

I'm even trying to set the url manually, such as myCustomPage/myCustomTerm i.e. customFrontPage/NaturalUser and it shows the following error message:

  the url 'myCustomPage/myCustomTerm' is not valid or you don't have permission
  to access it.

Is there any other way to change this?

Make the term context of your page optional using ! rather than %, then set up your views so the default argument (when no term is supplied) is the one you want.

Your page should then work with no argument, ie. at path "myCustomPage". When all OK, you can assign that path as the front page for your site.


Control fields of views on different pagination I use pager (as 1 2 3.. 9 >>Next >>Last) in a views and displaying only 3 articles on one page with the fields title and body.

I need to hide body of the articles on 3-6 pages.

Note: It should be done by only using views or views handler but not with css or JS.

Kindly guide me to do that.

Thanks

The simplest solution I can think of is this:

In a custom module you implement hook_views_pre_render

Here's the code:

function test_views_pre_render(&$view) {
  // Current page in Views is 0 based.
  $currentPage = $view->query->pager->current_page + 1;

  // Exit early if not in the 'to be modified' page.
  if ($currentPage < 3 || $currentPage > 6) {
    return;
  }

  // Exclude the body from display.
  $view->field['body']->options['exclude'] = TRUE;
}


How to display a Leaflet map in modal window? I produce geospatial data in a content type with addressfield and geofield. I can display this data in a Leaflet map as field without any problem. But I have to use here a modal, therefore I render the map programmatically:

<?php
$map = leaflet_map_get_info('google-high-res');
$map['settings']['zoom'] = 15;

$lon=$entity->field_terkep['und'][0]['lon'];
$lat=$entity->field_terkep['und'][0]['lat'];

$features = array(
   array(
        'type' => 'point',
        'lon' => $lon,
        'lat' => $lat
      )
    );
print leaflet_render_map($map, $features, $height);
?>

When I display this map as a field, everything is OK, visitors can see the map as intended (marker in the middle etc.) But if I place it in a modal, multiple issues appear (see in the attached screenshot): Only one map tile is generated and the marker is in the wrong place in the modal as well, it's in the top left corner. I have tried Bootstrap Modal and Colorbox, it doesn't make any difference.

I found similar issues either with Leaflet or Google maps, like this one here. So I have to reload or re-render the map after the modal window become visible. For this purpose I inserted this jQuery code which does the trick:

drupal_add_js('
jQuery(function($) {
$(document).ready(function(){
$(\'#myMap\').on(\'shown.bs.modal\', function(){
var map = Drupal.settings.leaflet[0].lMap;
map.invalidateSize();
});
});
});
', 'inline');


Drupal 7 cron does not run civicrm Scheduled Jobs I'm using Drupal 7, and set the cron job to run every hour.

However, when drupal cron runs, my CiviCrm schedule jobs does not run. These schedule jobs run only when I click the link "run all scheduled jobs manually".

Is there any way I can configure drupal cron job to run CiviCrm schedule jobs too?

Or I need to install any additional module, or configure setting so that the CiviCrm schedule jobs can run automatically?

You should configure a separate cron entry for CiviCRM on your server. CiviCRM's Managing Scheduled Jobs is the reference documentation here.

Best practice is to run your CiviCRM cron separately.

Many CiviCRM tasks (eg delivering large email runs) are not suited to Drupal's typical cron schedule.
Running CiviCRM cron from Drupal means that an issue with another Drupal module timing out or causing cron to fail may prevent CiviCRM tasks running.
Likewise, running CiviCRM cron from within Drupal might prevent other Drupal cron tasks firing if CiviCRM cron timed out or failed.

While it may be possible to configure Drupal to run CiviCRM's cron (eg CiviCRM Cron or Elysia Cron modules), I wouldn't recommend that approach.

Things to check when debugging CiviCRM cron -

Are you calling cron from the same user account that your webserver runs as? CiviCRM cron tasks may write access to the templates_c/ directory and can fail if called as a user which can't write there.
Do the tasks execute when called from the CiviCRM Scheduled Tasks page? Visit civicrm/admin/job?reset=1 then click More > Execute Now
Is there output from the PHP command to execute CiviCRM cron? If so it may indicate errors. Use su to assume the user account your webserver runs as when doing this.

Since we use Drupal extensively with CiviCRM, we fire most site crons using

drush -u 1 @example.org civicrm-api job.execute auth=0 --out=json

where @example.org is a configured alias for the site in question.

We call CiviCRM cron frequently (max wait for a site is a few minutes) to reduce wait time and avoid queue buildups.

A cron entry for a site might look like this in /etc/cron.d/civicrm

MAILTO=webmaster@example.org
*/7 * * * *    www-data    drush -u 1 @example.org civicrm-api job.execute auth=0 --out=json

... but you'll need to adjust this for your environment. You might want to call specific tasks frequently and others once a week; you definitely would need to check the user, Drush alias, and path to Drush shown above!

We also route our cron output to syslog for analysis, but that's well outside the scope of this. CiviCRM cron doesn't set the Drush output status (drush_log()'s $type parameter) as other Drush commands do.


Show a list of all forms Possible Duplicate:
  How to list all the form IDs

I have been searching for a way of listing all forms that are hooked to a Drupal site. I have read this post How to list all the form IDs, saying that it is impossible.

Now impossible is a big word in my vocabulary;-) If need be I can scan every single module file for the hook_form () function. Yet I am seriously hoping there will be a less hack like solution no matter what the resource cost might be. Any suggestions?

Well I ended up using Hook_form_alter () to add every form that was being called (and was not on my form list yet) to a form list.

Then I wrote an admin interface that enables the administrator to select what forms are still active/should be listed. Next to this I implemented a REST service for the Services module to GET the list of forms.

The fact that the hook_form_alter () has to preform a DB request to see if the form is on the list everytime a form is viewed is some what performance heavy, but since there is no help, this is the best I can think of. If anyone has interest in the code, drop me a line, ofcourse better ideas are welcome;-)


Modify the node title with the node ID before saving it I need to modify the node title while saving the node ID. I implemented hook_form_FORM_ID_alter() as follows.
/**
 * Implements hook_form_FORM_ID_alter()
 */
function module_name_form_form_id_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['title']['#access'] = FALSE;
  $form['#entity_builders'][] = 'change_node_title';
}

function change_node_title($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {
  $node_id = $node->nid->value; // Not getting the node details
  $node->setTitle('Custom Title -' . $node_id);
}

The node details aren't found from the #entity_builders callback.
How can modify the node title before saving it? I don't want to use any custom modules for this. I don't want to use hook_node_presave() either, as it would affect the cloned nodes.

Never tried entity_buildres but you could probably use the old and tried way of adding a submit handler

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // this is the create form id, edit form would be node_article_edit_form
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_change_title';
  }
}

function MODULENAME_change_title($form, $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $node->setTitle('Custom Title - ' . $node->id());
  $node->save();
}


Module Page Keeps Redirecting I inherited someone else's project.

I see he created a module called bcompanies.module.  In that module file I see this:

function bcompanies_menu() {
    $items['company'] = array(
        'title'     => 'Company',
        'page arguments'    => array(1),
        'page callback' => 'company_page',
        'access callback'   => TRUE,
        'type'          => MENU_CALLBACK
    );
    $items['company_page2'] = array(
        'title'     => 'Company',
        'page arguments'    => array(1),
        'page callback' => 'company_page',
        'access callback'   => TRUE,
        'type'          => MENU_CALLBACK
    );

}

function company_page()
{
      return 'hello world';
}

When I go to the url http://site.com/company, I see the text "hello world".  When I go to the url http://site.com/company_page2, I am redirected to http://site.com/welcome .   Does anyone know why the second url keeps redirecting me while the first does not, even though they seems exactly the same in terms of set up?

I did a test and wrote a die() statement in company_page(), that forced it to not redirect.   But that's not that great, because it prevents subsequent drupal hooks from firing.

Additional Notes

I noticed that if I login as an admin user, then there is NO REDIRECT when i go to http://site.com/company_page2 - I see hello world wrapped nicely by the header html template and the footer html template.  The redirect only happens when i login as a regular user going to that page.

So is this a permission/role issue?  But I never set the permission or role or anything...

There can not be a permission issue in your code (because you code is very simple:) ). Just try to change your code as documentation says:

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

    $items['company'] = array(
        'title'     => 'Company',
        'page arguments'    => array(), // I removed arguments because of callback function doesn't require in your case;
        'page callback' => 'company_page',
        'access callback'   => 'user_access', // I changed your access callback, it's a bad practice to set just TRUE as an access callback
        'access arguments' => array('access content'),
        'type'          => MENU_CALLBACK
    );
    $items['company_page2'] = array(
        'title'     => 'Company',
        'page arguments'    => array(),
        'page callback' => 'company_page',
        'access callback'   => 'user_access',
        'access arguments' => array('access content'),
        'type'          => MENU_CALLBACK
    );

    return $items; // I added this line, because I don't know you 're returning a value in your module or not..

}

function company_page()
{
      return 'hello world';
}


Payment methods not showing I've installed - drupal commerce +  paypal + payment + commerce payment- modules.
Commerce seems to be working fine with regards adding and displaying products.
But in 'configuration', there is no list item there that says 'payment methods'.
I've enabled all related modules, so 'paypal wpp' and '..wps' etc.
Also installed and enabled 'payment' and payment commerce'.
What am I missing?

Any help would be great,thanks
Jon

Drupal Commerce payment  methods can usually be found at      /admin/commerce/config/payment-methods. They are rules in fact. If for any reason that menu doesn't exist, check your rules.

To get that menu you need ro enable Payment UI module.

You also need to properly enable and setup your checkout panes at admin/commerce/config/checkout


How to pass form input to ctools modal I have a regular Drupal form that is not in a modal. When the user submits the form, a ctools modal popup opens (as per http://drupal.org/node/1482968).

My question is, what is the best method for passing form input to the modal? So that e.g. if the user enters their name ("Alex") in the form, the modal popup can read, "Welcome Alex!" ?

I am using Drupal 7 and the latest stable release of Ctools. (Also, I've asked this question in the ctools issue queue at http://drupal.org/node/1556856, but haven't had a reply in twenty days.) I've been trying to crack this one for a while, so would be incredibly grateful for any help!

Ended up just grabbing the passed variables from $_GET.


Have configuration form use a different theme than the currently set Admin theme I built a custom configuration form with the following settings

The contents of my aaep_settings_main.routing.yml

my_settings:
  path: '/admin/config/system/my_settings'
  defaults:
    _form: 'Drupal\my_settings\Form\SettingsForm'
  requirements:
    _permission: 'administer site configuration'

And then inside my SettingsForm.php I have

class SettingsForm extends ConfigFormBase {

protected function getEditableConfigNames() {
    return array(
        'my_settings.settings',
    );
}

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

    $this->config('my_settings.settings')
         ->set('test', $form_state->getValue('test'))
         ->save();
}

public function buildForm(array $form, FormStateInterface $form_state){
    $config = $this->config('my_settings.settings');
    $form['test'] = [
         '#type' => 'textfield',
         '#title' => t('Test'),
         '#default_value' => $config->get('test'),
    ];
}

It works just fine, but when I visit the page it's using the admin theme instead of the regular theme. I'm assuming that's because it's using a configuration form and extending ConfigFormBase. I'm assuming that that's the default behavior. But is there a way to override that and have my configuration page use my site theme instead?

You can control this in the route definition.

If you give non admin users access to the form they will see it in a regular theme:

my_settings:
  path: '/admin/config/system/my_settings'
  defaults:
    _form: 'Drupal\my_settings\Form\SettingsForm'
  requirements:
    _permission: 'access content'

If you want to have admins see the form in a regular theme then move the path outside of /admin:

my_settings:
  path: '/other-path/my_settings'
  defaults:
    _form: 'Drupal\my_settings\Form\SettingsForm'
  requirements:
    _permission: 'administer site configuration'

Or do both at the same time.

Details:

If you give a non admin user permission for an admin route, then the form will be displayed in the regular theme, because the admin theme is only accessible for admin users or users who have the "administration theme" permission.

Whether a route is considered as admin route is controlled by the route option _admin_route. If this option is not set, it is added by AdminRouteSubscriber::alterRoutes to all routes with an admin path:

  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      if (strpos($route->getPath(), '/admin') === 0 && !$route->hasOption('_admin_route')) {
        $route->setOption('_admin_route', TRUE);
      }
    }
  }

If you want to override this you can set the option to false:

  options:
    _admin_route: FALSE


How to create a view which would list related content for current article? I try to create a view which would list related content (some articles) to a content type article.

Here is what i’ve done. I’ve created a field "Entity reference"  in the content types "Article". It works. I can see in database the related article ID .

Then, I create a view with a block. It works, i can see all articles listed in that view (which is visible on each article).

Here is my issue. I need to display only articles related to the current article. So, in contextual filter, i have tried with
Content: ID and also tried with advanced/Relationships but without success. I don’t see my related articles.

How can I do ?

I’ve also tried a different way (create a twig) and even if it works, it is not the best solution i think

Ignore using fields in the View. This has been and will always be problematic IMO for 95% of Views people are making.

You need the Content ID argument from the URL so the correct node is selected, but here is where it takes a turn:

Set the view to show "Content" and give it a view mode, for instance, create a view mode called "Related Content" for nodes. In the field display for that view mode, only set the "Related Articles" field to be visible. Set its field formatter to "Rendered Entity", and create a view mode for that content type and theme it. On that content type, you would have title and body, or whatever fields you want to show (hard to tell without seeing a design).

Now the View will pull the node, render it, and in turn render the nodes that are being referenced in a view mode.

Then, you would get something like this, for example:

That is a View that looks at the current node, and renders it. The view mode has a field (Related Content), which is a node reference, and those nodes are rendering in a "Preview" view mode - and this is the result. All of the markup lives in two twig files (for the node--node-type--view-mode.html.twig) and the Views configuration is super simple.

The Views display would be a block, and you can place that block in whatever region works for you.


Using Views to add comments to user profiles My goal is to create an additional "ratings/comments" tab to user profiles in drupal 7 to allow authenticated users to leave comments/ratings for other users.  I've created a "ratings" content type (which naturally has comments enabled) and created a view around this type and added it as a user menu tab.

The problem is, since it is one content type, all the comments that have been left by any authenticated user show up on every single user's "ratings/comments" tab.  Of course I only want the comments that were meant for that particular user to show up.

Is this possible using filters?  I've been playing around with it but haven't been able to find the right setting just yet.  I know there is a guestbook module but I don't really want to go this route.

Thanks.

Some hints which might push you in the right direction:

Ratings can be handled with the five star module.
I didn't test this, but the profile 2 module gives you the ability to tye a content type to a drupal user. Enabling comments for this content type could get you going.


How can I eliminate duplicate Drupal nodes in a View when one CT references the other? Drupal 7 with relevant Modules: Views & Entity Reference

I have a view that simply shows the "Teaser" display type of two different Content Type records, we'll say they are Article and Page. This is built into a Views Page.

My Article CT has some simple fields that are shown.

My Page CT has a few fields, but also an Entity Reference field (unlimited entries). The Entity Reference field points to other Article nodes.

My View then, as expected, shows each record's Teaser display and of course when a Page record references another Article record, that Article's teaser is shown as part of the Page teaser.

This is great. The problem is, I do not want to show duplicate Article teasers. That means, if a Page references an Article, I don't want to show that same Article teaser as an individual listing.

Think of it like this, I have these Articles:

Article 1
Article 2
Article 3

And I have these Pages:

Page 4
Page 5
Page 6

Page 4 points -> at Article 1 and Article 2

Page 6 points -> at Article 2

TL;DR

Right now the view would show something like:

Article 1
Article 2
Page 4

Article 1
Article 2

Page 5
Page 6

Article 2

Article 3

What I want is this:

Page 4

Article 1
Article 2

Page 5
Page 6

Article 2

Article 3

Here's a Diagram:
http://i.stack.imgur.com/2joEr.jpg

My guess would be to use fields instead of teasers, first. Then, use filter to undisplay Articles that are nodereferenced by pages - you then would only have pages and unreferenced articles showing up.

You might be able to do that with the relationship entityreference - reverse, or with views PhP if it doesn't work.


Get page title of view and panel page via url Is there any way to get page title of view and panel page using url. I tried

$normal_path = drupal_get_normal_path($path);
$item = menu_get_item($normal_path);
$title = $item['title'];

and it is giving empty title while it is working well for normal node.

Please suggest.

For pannel you can pass the page title in url
let say xyz/page_title
then add content to panel and choose New custom content in the body field your code will somewhat look like

<?php
  $title = arg(1);
  drupal_set_title($title);
?>

check screenhot for better understanding:

For views its a simple 2 step process
step1: Set the view path to take the title as wildcard
i.e. your view path will be view_path/%

step2: now change the title field on views to use the title wildcard by changing it to %1 as this is the first argument in the url

hope it helps you :)


Gmap and many markers with popup Situation

We use gmap module to generate gmap and display markers on it.
When user click on marker we display popup, it works well if website display 100-200 markers only, however when it gets to 1000++ Drupal can't display such page.

Issue

Issue happens because Drupal exports all required information to display popup directly on page and it takes to much time generate that.

What I've done so far

I googled and did not find anything that could help me.
I know that google map API may deal with feed/xml (that's a direction I'm moving to), however I do not wanna create new wheel if it is already exist.

Thanks!

In order to move information for popup from the page we have to use options: RMT callback path in a view.

It allows to make AJAX request to load content and so you do not need to put it on page with map. It's big performance improvement.


Drupal7: Linked template node file How I can define my node-title.tpl.php via dashboard?

Here what I did:

I created new content type page (our locations)
I uploaded a file to the templates: node-our-locations.tpl.php
I added new (our locations) content, and I set (our locations) in the title field

You should read the page about Drupal 7 Template suggestions - you would see that the proper template suggestions for Drupal 7 nodes are :

node--NODEID.tpl.php
node--NODETYPE.tpl.php

I'm unsure from your question whether you want a template for a particular node (in which case you should use the node id, not the node title - node--NODEID.tpl.php) or for all nodes of your content type "our locations" (in which case you want to use the second form, which depends on the node type, not the node title, node--NODETYPE.tpl.php)
Note that NODETYPE is your content type's machine name - on your site you will see this next to the content type name when you go to "admin/structure/types", and that hyphens should be replaced by underscores. So if your content type machine name was our-locations, the template file you want is node--our_locations.tpl.php)
Finally remember that once you've added the new template file, you must clear your cache before it gets noticed. You can do this on the performance page on your site at "admin/config/development/performance".


Documentation of Drupal Content Types and Views Drupal 7, Views 3

Ok, I've got a bunch of content types and views, all working happily together, what would be really nice is a way of automatically documenting things, say a printable page of what fields are in a content type or what fields are used in a view. Searching on Google gives lots of info on creating document types but I haven't been able to find anything on actually creating documentation.

Has anyone seen anything like this?

admin/reports/fields - Field list with node type relationships.
admin/reports/fields/views-fields - Used in views.

You need Field UI module enabled.


CiviCRM Profile form buttons showing but not linked in Drupal profile We are using CiviCRM profiles to allow members to update addition information. We have marked these profile forms in CiviCRM as 'View/Edit Drupal Account' and 'Drupal User Registration. The buttons appear (and disappear if you remove these settings) in the user profile editing screens. When the buttons are clicked on the user is taken to their Drupal profile, not the screens to capture the CiviCRM data as per this screen shot.

This was working on this site. What changed? We did a general drupal upgrade. Drupal 7.19, CiviCRM 4.2.

Thanks
Interlated

Just a guess, but try opening the Advanced field set at the bottom of the Edit Profile Settings page, and deselect requiring creation of Drupal user account. You might get more responses if you posted more info on the fields in the profile, for example, what you expect to see.


How to quickly tell what a URL maps to? I'm in a new position working on an existing Drupal 7 site that I didn't help build. None of the original devs are here. Amongst other modules, the site makes uses of panels, panelizer, aliases, and redirects.

I get requests from marketing to update or change a page, and they include a URL. The URL is often an alias, but sometimes it can be a panels page, or a drupal entity "overriden" by panelizer.

Is there an easy way to see what exactly a URL maps to when I get a URL from marketing?

There is no easy way. You have to have deep knowledge of the site's content to know how to edit what appears on the page. This is only obtained through poking around the site or asking a knowledgeable colleague.


How to extend or "hook" Drupal Form AJAX? I'm working with standard admin form, which has 'add_more' button for one of fields.

My task is to move some fields to jQuery UI Dialog just for usability. When dialog was closed I manually append it's content to form so It sends normally.
The problem appears when some core ajax is sending while some form parts are in the dialog (i.e. outside of form tag because jQuery UI Dialog appears in the bottom of body). The 'add_more' button as example. When I click on it, the form serializes for AJAX without some inputs in the dialog.
Оh..
The jQuery Form Plugin (which used by Drupal) has option beforeSerialize. I think it can help me but I don't know  how I can extend Drupal.ajax.options to set something custom.

If you can recommend other ways to solve my problem or give some links to documentation about Drupal JavaScript, I will be very happy :)

Thanks.

Thank you, @yvan, for answer. Links you added are good.
But there are better documentation in source code comments. If you want to understand how it works you should look through files includes/ajax.inc and misc/ajax.js.
My problem was solved like this:

(function($) {
Drupal.behaviors.MyModule = {
    attach: function (context, settings) {

        // Overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSubmit = function (form_values, element, options) {
            // ... Some staff added to form_values
            // return false; // to prevent AJAX call if needed.
        }
        //Or you can overwrite beforeSubmit
        Drupal.ajax['some_element'].options.beforeSerialize = function (element, options) {

            // ... Some staff added to options.data
            // Also call parent function
            Drupal.ajax.prototype.beforeSerialize(element, options);
        }

                    //...

These functions are calling in jQuery Form Plugin.


Commerce Product Collection View Block: What Determines CSS For Each Header Link? In Kickstart 2 there is a view called collection_products which displays a list of products in a given collection, grouped by category.

There is a header which uses a Block display to give anchor links to each Category Header on the page. The format of the fields is 'Unordered List' yet the fields are styled as

...not

...as I would like.

How do I change the generated styling of these? I've searched all over the view and can't find it.

HEAVY EDIT. Big Thanks to J. Reynolds!

The issue is that this view is actually a list of group headings. The reason it displays as it does is that it's showing a list of all categories... each as a 'Title'...

...for each category and then a -hidden- list of the products.

So it's not that each 'row' is being themed not as a list, but that what I -thought- was a 'row' is actually a 'title'.

So: What I need to do is create an unordered list with the -title- of each category (the Grouping No. 1) as the actual li using each of these headings.

How do I do this?

BONUS: Is there a way to get Drupal to not even generate that hidden UL of products? It seems wasteful, not just for the client, but at the server.

It is the same as with any view: You have to override the view template.

In your views UI click on 'Theme:information'. This will open up a dialog with views templates and suggestions. As the block is using grouping, you need to override the 'Style output' theme template:

views-view-list.tpl.php

If you override that template it will override it for all views of HTML List format, so you now have to select a suggestion. Second in the list is:

views-view-list--collection-products.tpl.php

which will be fine.

Create a new file in your theme templates folder called

views-view-list--collection-products.tpl.php

Then click on the 'Style output' link back in the view theming information. It will open up a file and you copy everything from the

Now you can edit that file to get the markup you want. You can take out the h3 tag for example and replace with a div.


How to have a node which displays & interacts differently with different type of users? Title might not be very clear. But to clarify my question, I'll take example of a Book Content Type.

I've 3 different types of users: Authors, Reviewers, Admin. Now this is what I want to achieve:

On the Book Page [a display which is shown to even unauthenticated user], Registered Reviewer submits a review for a book which should appear in Approve Reviews page of Admin, When the admin approves it should Appear in respective Author's Reviews for my books page and when finally the Author approves, it should be displayed on the Book Page.

And the reviewer must have a Submitted Reviews page which should list all the reviews he submitted each showing its present status like:

"Waiting for Admin's Approval", "Waiting for Author's Approval", "Approved"

I don't know how to achieve this.

There are many ways to accomplish this but here's one:

create content type Book
create content type Review
add a custom status field to Review (select list) and add the three states (admin approval, author approval, approved)
download and enable references module (also enable submodule node reference)
download and enable rules module (also enable rules ui submodule)
add a node reference field to Review (e.g. autocomplete widget)
create roles admin_reviews, author, reviewer
create view lists for reviews content and set permissions per role for admin_reviews, author and reviewer pages. Filter on field status of review for each role
use field permissions module to show / hide fields per role

create rules to set status of review (After saving new content -> set data value)


How to jump to another know page on a button click? I need to implement a select list (something like auto-complete in JQuery UI) with a Go button on a mini-panel (or block). I can do this in Javascript. When the user selects a value, a corresponding page (for example: article) URL is computed.

Assuming we know the URL of that page, how do I get Drupal to jump to that page when the user clicks on the Go button? I am no expert in PHP, but could implement some if necessary, or is there a better solution?

If the whole implementation (including the URL computing) is done on the client side with javascript then the easiest solution would be to simply use code like the following:

$('#go_button_id').click(function() {
  location.href = 'url_to_the_computed_page';
});

On the server side you could use Drupal's block hooks and form API to create a block with a simple form and then use $form_state['redirect'] = 'url_to_the_computed_page'; in the form submission handler for the redirect.


Login/register web service I am creating a web service for login and register, but I want a single URL for register and login so that, when a user registers, it will automatically log in. No need for two services for register and login.
How can I get this?

When user gets saved in DB using user_save() it returns the user object. All you have to pass it to $GLOBAL['user']; and save session

   //Here is your previous code I assume where you have user_save()

   $user = user_save($userData);

   if($user) {
        drupal_save_session(FALSE);
        $GLOBALS['user'] = $user;
        drupal_save_session(TRUE);
   }

Hope this may help you


How to integrate properly Kerberos based SSO in Drupal 7 I'm trying to install Drupal with Single Sign On over Active Directory.
My customer does not have any SSO suite like CAS, and their general recommendation are to use Kerberos (or NTLM as a second choice). I am clearly agreed with that.
Each time I had to integrate SSO with Active Directory using Kerberos, I use "native" product facilities, or apache mod_auth_kerb with headers rewrite.
Does someone implemented such a working module ? Everything I read about that is around "on developpement modules" on "snapshots realeases". We are currently using a ldap module that allow authentication over LDAP, and it seems that it provide SSO features, but I don't have any feedback on it.
So : Should I implement SSO over Kerberos using Apache mod_auth_kerb, or is there a real functional module that would encapsulate all those tedious configuration and dialog ?
What is the best pratice, at this moment ?
Could you provide me "real" (anonymised) examples ?
As soon as I would installed it and put in in production (around the end of december), i would give you my feedback.
Thanks in advance

After some researches and tests, I finally made a choice.

In most cases, I'd prefer use native or add on features. This provide better integreation with the product (here Drupal) and it's more a Logic solution than a technical one (which is quite easier).
The LDAP_SSO module allow this kind of configuration.

Nevertheless, I was not able to configure it this time, mainly due to poor debug facilities. Even with watchdog, I am not able to know what is the matter. Moreover, my customer have clear procedure to install and use Kerberos, with Apache HTTP and mod_auth_kerb.
Hopefully, LDAP_SSO module allow this too.

After some tries, I will get back here to share with you more advanced comments, but at this time, we clearly go to apache+mod_auth_kerb+fowarded REMOTE_USER.

Edit a few monthes later :

That works great with Mod auth kerb on apache server and ldap module v1.0-beta12 on drupal.
Even if v2.0 is available, we were facing some issues because some fields were empty and this were causing troubleshootings.
But nevermind, we are able to authenticate et identify users, collect groups and map them to  drupal profiles etc.


Automatically scroll to content when block link clicked? On responsive themes, where both sidebars and content areas collpase to 100% width,the distance between block links and their corresponding node content which come before or after all blocks is usually large. So user need to scroll down a lot to reach the desired content, which is obviously not a good user experience.

So I am wondering if there is any module/javascript/other solution to slide to the node's content whenever user clicks the link?

First, you need to know the ID of the Drupal region/element that you want to jump to when the responsive theme is activated. With the standard Bartik theme the id is the main content region is "block-system-main".

Then you could append #block-system-main to all links within your side. This will cause the browser to jump to the HTML element with that ID after clicking the link. You could append this tag to all links using javascript. See this question. It could also be done in PHP. This would be a good module and AFAIK no exists currently.


How to set user flood limit role wise? If user account is locked after entering wrong password 5 times. That's a default setting.
That can be changed via
drush cset user.flood user_limit 10

I have different roles. I need to set flood user_limit role wise
Role A, It will be 10
Role B, It will be 7

Can we achieve same thing via CLI?

No you can't.
The user.flood user_limit config setting feeds into the DatabaseBackend::isAllowed() method as the $threshold arg, which is used to compare the row count for this query:
  $number = $this->connection
      ->select(static::TABLE_NAME, 'f')
      ->condition('event', $name)
      ->condition('identifier', $identifier)
      ->condition('timestamp', REQUEST_TIME - $window, '>')
      ->countQuery()
      ->execute()
      ->fetchField();

It only compares the threshold login count against a unique user ID, $identifier.
You'd have to do some sort of modification to the flood core service to make some sort of per-role flood limit.


Use a custom install profile for Nightwatch tests? How can you set a custom install profile to run a Nightwatch test in? I am not seeing it in the docs. The definition of the .drupalInstall() command has:

commandAsWebserver(
        `php ./scripts/test-site.php install ${setupFile} --install-profile nightwatch_testing --base-url ${process.env.DRUPAL_TEST_BASE_URL} ${dbOption} --json`,
      ),

Which looks like the profile is hardcoded with no way to set.

As you understood it's been hardcoded. if you want to make it dynamic you can  create your custom parameter.

you can do it in a way like the following  :

https://www.drupal.org/project/drupal/issues/3017176

this patch help you to know what you can do : https://www.drupal.org/files/issues/2019-11-11/3017176-16.patch


Display a View of Private Organic Groups for 'Requesting Access' Right now I have it set up so groups are 'Private' in OG 7.2.x on D7

When using og_extras there is a view that lists the 'Groups'. However, when they are set to private, because the og permissions module is enabled, the groups do not show when an anonymous user acceses the page.

With the correct permissions, non-members can request access to groups, and a URL like this will let users join a Private Group:

example.org/group/node/6469/subscribe

Now, the BIG QUESTION:

How can I get views to show the Group name, Group Description, 'Private', and 'Request Access links' in a public facing view, yet have the content/members of the group be private?

It seems like the idea of a 'Private Group' is that people can't even see the name of it. That assumption is irrelevant to my site, I just want them to not be able to access the groups homepage/content unless they are members, I want them to see the groups they 'could be a part of'.

Thanks! And apologies if this was too indirect.

Answer: edit the OG Extras Group view and do the following. Answer taken from here:https://drupal.stackexchange.com/a/865/2957

You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

  Disabling SQL rewriting will disable node_access checks as well as
  other modules that implement hook_db_rewrite_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.


SQL query for phpMyAdmin to delete authenticated users Question 1: I would like an sql statement to use in phpMyAdmin to delete the users with the role: authenticated user. Looks like rid = 2.

Related Question 2: I show thousands of users in admin/people but the query:
SELECT * FROM drup_users WHERE 1
only shows 30 users. Shouldn't they all be there?

Related Question 3: I created several roles but only the three standard roles appear using:
SELECT * FROM drup_role WHERE 1
Where are all the roles I created?

I think I'm having some gross conceptual error. I would appreciate any guidance :)  Thanks!

As mentioned in the comments, directly modifying the tables could be disastrous.  If you need to get rid of large numbers of users I would suggestion Using Views with Views Bulk Operations:

  You need Views if

  You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month.

This module augments Views by allowing bulk operations to be executed
 on the displayed rows. It does so by showing a checkbox in front of
 each node, and adding a select box containing operations that can be
 applied. Drupal Core or Rules actions can be used.


Editing content with views This is a very basic question so please check for idiocy as I haven't worked with views that much.

I want to edit the main page of a content type like an article through views. To me it seems views only works with the "listing" of the contents not the content itself. I might be missing an option right in front of me but I can't seem to figure out what it is.

Repeat, I want to edit the main content page not the listing. Please help!

EDIT: This is the screenshot of my content page. I want change this layout through views like reorder the fields or add new ones like it's typically done in views. So is it possible?

Drupal has done this ugly presentation itself and I want to change it.

You are basically right regarding views. Views is a way to see data aggregated together in some fashion. Think visual SQL.

The original request seems a bit confusing to me. I think you are asking for 2 things. Theming the content based on type as well as theming the views output.

For content type, take a look at theming nodes by content type . Drupal 6 and 7 are different in the way they go about this but for drupal 6 you are more or less looking to use the template node-[NODETYPE].tpl.php. This will adjust your node's output on a full view.

For theming your view, take a look at your view in the edit mode. Under basic setting you will see Theme: Information. Click on that and you will get a listing of possible templates that you could use to theme your view. Generally the same way you would edit your node type template you would edit your views template file. Check Theming Views for more info.


Drush installation issue I am trying to install the most uptodate version of Drush as I begin working on Drupal 8.

Apt-get only installs Drush version 5.10.0. So, I'm attempting to install Drush via composer with the following effect:

sisko@li184-76:~$ composer global require drush/drush:dev-master
Changed current directory to /home/sisko/.composer
The "fxp/composer-asset-plugin" plugin was skipped because it requires a Plugin API version ("1.0.0") that does not match your Composer installation ("1.1.0"). You may need to run composer update with the "--no-plugins" option.
./composer.json has been updated
The "fxp/composer-asset-plugin" plugin was skipped because it requires a Plugin API version ("1.0.0") that does not match your Composer installation ("1.1.0"). You may need to run composer update with the "--no-plugins" option.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drush/drush dev-master -> satisfiable by drush/drush[dev-master].
    - drush/drush dev-master requires consolidation/robo dev-master -> satisfiable by consolidation/robo[dev-master] but these conflict with your requirements or minimum-stability.
  Problem 2
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - fxp/composer-asset-plugin v1.0.0 requires composer-plugin-api 1.0.0 -> no matching package found.
    - Installation request for fxp/composer-asset-plugin 1.0.0 -> satisfiable by fxp/composer-asset-plugin[v1.0.0].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.
sisko@li184-76:~$ drush status
The program 'drush' is currently not installed. You can install it by typing:
sudo apt-get install drush
sisko@li184-76:~$

Can anyone please help me out?

If you want to install Drush via composer require rather than git clone followed by composer install (which is slightly easier), then I would recommend:

Use the stable version of Drush, ~8
Install with cgr


Add a field between name and email I'm running Drupal 7.39 and I'm trying to add a textfield exactly between the  "name" and "email" field. I also tried with the #weight property as noted by the Form API but it does not work.

If you are doing it by custom code, you have to move the field to 'account' container, example code looks like

function my_module_name_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Change weight in respect of user name field.
    $form['field_test']['#weight'] = $form['account']['name']['weight'] + 1;
    // Use machine name of field as form field, replace 'field_test' with your machine name.
    $form['account']['field_test'] = $form['field_test'];
    unset($form['field_test']);
  }
}


For logged in user, let them view a list of content they have created (front-end user) I have a user called a creator who can create a 'skill' content type. When they are logged in, I want them to be able to view a list of the skills they have created. I am a beginner with drupal when it comes to users. What kind of settings would I need on my view so that the view showed only content by the logged in user. I know how to do this with custom code, but would be more convenient to do with views.

Add the fields you want from your skill content type to fields and then simply add a relationship of User: Author and then  create a filter using field User:current and make sure you use setting logged on user


Ajax callback does not replace the form but add a new field I use his code to populate a select after giving à zipcode.

$form['responsible']['zipcode'] = array(
      '#type'               => 'textfield',
      '#title'              => t('Zipcode'),
      '#default_value'      => empty($account->Dossier->responsable->adresse->codePostal) ? Null : $account->Dossier->responsable->adresse->codePostal,
      '#required'           => True,
      '#maxlength'          => 5,
      '#ajax' => array(
        'callback' => 'ajax_get_cities_callback',
        'wrapper' => 'edit-city',
        'method' => 'replace',
      ),
    );

    $form['responsible']['city'] = array(
      '#type'               => 'select',
      '#title'              => t('City'),
      '#options'            => array(),
      '#required'           => True,
    );

My callback

function ajax_get_cities_callback($form, $form_state){
  $client = new SoapClient('myWebservice',array("trace" => true,  "exceptions" => true,));
  $requestParams = array(
    'parameters' => array (
      'numSite' => 1058,
      'typeListes' => array(
        'RechercheTypeListe' => array(
          'typeListe' => 'LST_VILLE',
          'param1' => $form_state['values']['zipcode']
          )
        )
    )
  );
  $dataresponse->requestParams = $requestParams;
  $response = "";
  try {
      $response = $client->__Call('GetListes',$requestParams);
  }
  catch (Exception $e) {
    var_dump($e);
    return False;
  }

  $form['responsible']['city']['#options'] = array(
    0 => "aaaa",
    1 => "test2",
    2 => "test3"
  );

  return $form['responsible']['city'];

}

When I give a zipcode, a new select is created behind the first one.( picture here: https://www.uploady.com/#!/download/zjKvglzRTSe/ZIMYkjSAAaLrUFUq)
I tried to return only $form['responsible']['city']['#options'] but it does not fixe.

Any idea ?

Thank you

You have to setup a wrapper on the field you want to update :

$form['responsible']['zipcode'] = array(
      '#type'               => 'textfield',
      '#title'              => t('Zipcode'),
      '#default_value'      => empty($account->Dossier->responsable->adresse->codePostal)
                                    ? Null
                                    : $account->Dossier->responsable->adresse->codePostal,
      '#required'           => True,
      '#maxlength'          => 5,
      '#ajax' => array(
        'callback' => 'ajax_get_cities_callback',
        'wrapper' => 'div_city_wrapper', // Changed here
        'method' => 'replace',
      ),
    );

    $form['responsible']['city'] = array(
      '#type'               => 'select',
      '#title'              => t('City'),
      '#options'            => array(),
      '#required'           => True,
      '#prefix'           => '
', // Added this
      '#suffix'           => '
', // Added this
    );

The callback function seems to be fine as it returns the wrapped form element ($form['responsible']['city'])


theme() parameters sent to output.tpl.php What I am trying to do, is to set some variables in my function and to send this to my output.tpl.php.

My steps are the following.

Declare my theme template

function mymodule_theme() {
  return array(
    'my_file' => array('template' => 'output')
  );
};

Define the following function

function mymodule_myfunction() {
  $build['variables'] = array(
    '#theme' => 'my_file',
    '#variables' => $my_vars
  );
  return $build;
}

I use the following code for my output file (output.tpl.php)

<?php echo $my_vars[0]; ?>

I get an error saying $my_vars is unknown.

What am I doing wrong?

As described in Override template files based on template filename as well as hook name, if you theme function is my_file, your template file needs to be my-file.tpl.php; you cannot use output.tpl.php because Drupal would not recognize it as template file, at least until Drupal code is not changed as per the issue I linked.
The variables that you pass to the template file needs to be defined in your implementation of hook_theme().

Your code should be similar to the following one.

function mymodule_theme() {
  return array(
    'mymodule_output' => array('template' => 'mymodule-output', variables => array('my_vars' => NULL))
  );
};

function mymodule_myfunction() {
  // Add here the code that initializes $my_vars.
  // …

  $build['variables'] = array(
    '#theme' => 'mymodule_output',
    '#my_vars' => $my_vars
  );
  return $build;
}

// mymodule-output.tpl.php
<?php echo $my_vars[0]; ?>

I used mymodule_output as name of the theme function and mymodule-output.tpl.php as name of the template because the coding standards used from Drupal suggests to use the module name as prefix; it would not change if you used output where I used mymodule-output or mymodule_output.

If all you are doing is printing a variable, then you don't need a theme. Theme functions (and template files) are used when you plan to allow themes or other modules to alter the output of your module. That is why Drupal uses node as theme function: to allow themes to alter how a node is rendered. The Node module defines its own node.tpl.php file, and the Bartik theme uses its own node.tpl.php.


Why is unchanged and new value always the same in my Rules condition? I have a boolean field called verified defined in profile2. When this field changes from not ticked to ticked I would like to send out an email to the user. Easy I thought with rules

Starting using "After updating an existing profile" then comparing the fields
profile2-unchanged:user:profile-directory-information:field-verified
and
profile2:user:profile-directory-information:field-verified
(bascially saying equal and then negating the condition)

   "IF" : [
      { "user_has_role" : {
          "account" : [ "profile2:user" ],
          "roles" : { "value" : { "12" : "12" } }
        }
      },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3", "28" : "28" } },
          "operation" : "OR"
        }
      },
      { "NOT data_is" : {
          "data" : [ "profile2-unchanged:user:profile-directory-information:field-verified" ],
          "value" : [ "profile2:user:profile-directory-information:field-verified" ]
        }
      }
    ],

However they are always the same value and the rule never fires. However when I take out the condition and send myself an email with the two values. One is true the other one is false.

also tried this in the condition:

  { "data_is" : {
      "data" : [ "profile2-unchanged:user:profile-directory-information:field-verified" ],
      "value" : 0
    }
  },
  { "data_is" : {
      "data" : [ "profile2:user:profile-directory-information:field-verified" ],
      "value" : 1
    }
  }

which is also not working. Tried to move it in before saving a profile, and also in various save user events. Always the same result. So why are the values different in Actions then they are in conditions?

Am I missing something here?

Rule refinements

Entity has field

Make sure to add a Rules condition Entity has field (related to your additional profile2:user:profile-directory-information:field-verified-field in your Rules condition). And make sure to add that Entity has field condition BEFORE the condition you already have.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

Add ":value" to your fields

Adapt your rule by adding :value to both of your fields, so that they look like so:

profile2-unchanged:user:profile-directory-information:field-verified:value
profile2:user:profile-directory-information:field-verified:value

Rules debugging

If none of the above helps, then move on to Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

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 profile2:user:profile-directory-information:field-verified).


How to change permissions to a role when a content is set as published I have been working with Drupal 8 and need help: I have a News content type, and an Editor role type. This Editor role can view/edit/delete his own content. I want that Editor roles can't edit/delete their own content when this content is published by Admin roles.

I have been searched and I found Permissions by fields, Permissions by terms, Groups and Custom Publish options modules, but I can't make this works.

Maybe this can be done with php, but I don't know how.

Please, any help?

You could use the following code.

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $type = $node->getType();
  // Is it published?
  $nodeIsPublished = $node->isPublished();
  if ($type == 'news' && $operation != 'view' && $nodeIsPublished == 1) {
    if($account->hasRole('rolename')) {
       return  AccessResult::forbidden();
    }
    else {
      return AccessResult::allowed();
    }
  }
  return AccessResult::neutral();
}

Also, the Override Node Options module allows permissions to be set for each field within the Authoring information and Publishing options fieldsets on the node form.


Get title field from another content type in exposed filter I have two content types: Project and Task. Project has an node reference field of Task - when you create a Task, you add reference to one of Project.

I need to create a view of Project and add the expose filter of title of the Task. I've selected both content type like Project and Task in a filter, I can see all of the fields from the Task content type EXCEPT Title. The only Content: Title that's available is the one from the Project nodes.

Need help.

You need to create views of one content type ie Project and add a relationship to your views which should say something like this Task Content referenced from Project. Require this relationship to exclude those projects which don't have tasks.

Now come to your filters and add title. In the setting now you will see use relationship dropdown. Select the relationship you added and you will get the required results.


Drupal javascript file loading and jQuery I have several javascript files in custom modules containing many functions which are used across the code.  In D6 I simply added them during hook_init() and it was fine.

drupal_add_js("/scripts/jquery.url.js", array('group' => JS_LIBRARY));
drupal_add_js("/scripts/jquery.cookie.js", array('group' => JS_LIBRARY));
drupal_add_js("/scripts/mymod.funcs.js", array('group' => JS_DEFAULT));
...
drupal_add_js("/scripts/otherfuncs.js", array('group' => JS_DEFAULT));

However, in D7, I am now getting the "$ is not a function".  Wrapping all my code as described in the D6 to 7 conversion wasnt't seeming to work since I was then getting "<one of my functions> is not defined".  Using

var $ = jQuery.noConflict();

at the start of my 'parent' file resolved the error.  But that doesn't seem like a good idea either.  Below is an example of the javascript.

//in main file: mymod.funcs.js, global functions
function my_storage(key) { return value; }

//in another file: otherfuncs.js
Drupal.behaviors.myMod = { attach: myMod_Splash }

function myMod_Display(splash) { ... }
function myMod_Splash() {
  var splash = my_storage('splash');
  if (splash) { myMod_Display(splash); }
}

What is wrong when simply wrapping all of it with the recommended? What else should be done, aside from converting the function groups to objects (which still wouldn't necessarily resolve the wrapping problem)?

EDIT: I was wrapping my code like:

//(function ($) { //tried here
Drupal.behaviors.myMod = { attach: myMod_Splash }

(function ($) { //and here
function myMod_Display(splash) { ... }
function myMod_Splash() {
  var splash = my_storage('splash');
  if (splash) { myMod_Display(splash); }
}
})(jQuery);

UPDATE: I just removed the "var $ = jQuery.noConflict();" from my file to begin messing with the problem again, and am now getting no errors at all, in Web/Error Console or Watchdog.  None of the code was wrapped.  I was constantly clearing cache in Drupal before so really have no clue what is going on now.  Could the JS aggregation still have been placing the files in the wrong group, hence loading in a conflicting order?

By the docs You should wrap your code that way:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

})(jQuery);

What's wrong with other methods? Nothing fundamental, only Drupal's own scripts are not tested to work with them, and redefining $ globally may interfere with non-jQuery libraries some modules use, rendering either their or yours code not working.

For "jQuery is not defined", there are couple of possible problems. My surest bet was to skip drupal_add_js() altogether. Unconditional module (or theme) scripts can be added in info files:

scripts[] = somescript.js

and form related ones can be added directly to a form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/js/a.js',
  drupal_get_path('module', 'mymodule') . '/js/b.js',
);

I prefer to leave conditions in javascript itself, it means I only need one aggregated file for all pages on my site (plus one per form), so this is a performance boost in addition to problem prevention.