How to give users with role Role2 the right to edit only user accounts with role Role1 I need to make a user edit users that have a specific role.
In fact we have two user roles here.

Role1 -> is able to edit a particular kind of node
Role2 -> is only able to  administer users with the role "Role1".

My question: how to give users of Role2 access to edit only user accounts of Role1?

You may want to try Administer Users by Role module.

  This module allows site builders to set up fine-grained permissions
  for allowing "sub-admin" users to edit and delete other users — more
  specific than Drupal Core's all-or-nothing 'administer users'
  permission. It also provides and enforces a 'create users' permission.

One of the extra permissions that this module provides is

Edit users with custom roles - Allows editing of any authenticated user with the specified role.


Content Type vs Webform vs Form API vs Custom Form vs? I'm currently working on a new Drupal 7 site, which will be used as a data collection and reporting site. After much research / trial and error / etc, I've decided to bring this question to this forum, and am sincerely hoping that it won't be thrown out as being "too generic."

I've created a Content Type, which consists of roughly 25 fields, and am wondering what the best approach for having users populate that content would be? Out of the box (even using Manage Display) the form itself still resembles nothing that I'd actually want to present to the users. And, it seems a bit insane to alter the form using one of the hook_form_alter flavors, because the code involved seems way overkill just to hack the form into looking/acting like I intend it to. I've also spent a bit of time with the Webform module, which is ok, but there's still quite a bit of customizing that needs to be done in order to have the form look/act like I intend it to, and there seems to be mixed reviews on that module in general (no offense to anyone!). Same goes for using the Form API...lots and lots of code just to come up with a basic form to collect data.

My latest approach is to simply use the markup type to create the form itself (basically, just straight html / css / javascript, and then populate / update the Content Type behind the scenes. From a developer's point of view, this approach is very, very straight forward - no rocket science - easy to maintain, but I'd certainly like to hear from those of you that know your way around Drupal. Am I overlooking something?

Thanks in advance!
cmmsites

I'm using Drupal for exactly the same purpose. Basically, what I'm doing is using the Field Group module to wrap particular items together in DIV tags so that I can use CSS styles to properly layout my forms.

Drupal provides a very structured set of container elements with appropriately named classes. Accordingly, leveraging the power of CSS to your advantage should be the first thought that goes through your mind when it comes to manipulating layouts.

I mucked with the Webform module, and although it is quite capable, I've found that just sticking with Drupal's standard content type system for collecting information has suited me best.  Utilizing Views and the Rules module, I'm able to generate reporting pages that show me the critical information I want with less modular bloat to my Drupal installation.

So definitely read up on Views, Field Group, and the Rules module to see if the functionality as described will fit your bill.


How to add form on ubercart checkout complete page? I have latest Ubercart 7.x-3.6 on Drupal 7.31 installation.
I want to add a form on cart/checkout/complete page. which api can I use to add a form on checkout complete page.

EDIT:

Ubercart's core cart checkout complete page contain an order submit message and created order link, right? Now I want to add a form bellowed to the contents of checkout complete page. I think its enough detail.

Create a custom module and use hook_form to create your form.

Then I would do as suggested in this post to add your custom form to the ubercart page you wish to edit, only instead of rendering items, call your new function.  Does that make sense?


Drupal Queue example : form_state->get('XXX') always empty In D8 Queue example (QueueExampleForm.php), why $form_state->get('insert_counter') is alway empty during insertion into queue (after submit)?

Lets try with

$form_State->getValue('insert_counter');

or

$form_State->get('insert_counter')->getValue();


Disable link on username in comments? How can I disable the link on authenticated an authenticated user's name in the comment submission form in Drupal 6?

I just tested this out, not sure if it is the best way, but it works.  Create a really simple custom module and implement hook_form_FORM_ID_alter().
YOURMODULE.info
name = YOURMODULE
description = Description of YOURMODULE goes here...
core = 6.x

YOURMODULE.module
<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  $form['_author']['#value'] = $form['author']['#value'];
}

Place these files in a directory named YOURMODULE, inside contrib modules directory. Then enable the module.
(Be sure to replace YOURMODULE with the name you choose to give to the module everywhere it occurs.)


How to add redirect section to node edit on Drupal 8? On Drupal7 using Redirect module there was a section on node/nodeid/edit view where we could add a "Redirect" section. This was helpful because it allowed redirects to be created from the node/nodeid/edit view.

In Drupal8 that option is not available. How do you replicate the redirect section on the node/nodeid/edit view?

That's not a Drupal 7 feature but one from the redirect module. It partially exists in Drupal 8 as well but only lists the existing redirects, there is an issue open to add the ability to create a new redirect


How do I in code add new field values to a D8 content entity? How do I in code, create a new field value, add it to a content entity, and then have it saved to the DB?

Field API is dead. Long live Entity Field API! clearly shows how to read values, but doesn't mention inserts/updates.

I'm not sure what you mean with "field value", do you mean field items with multiple values?

It's the same as reading them, nothing special:

// Those are identical, not specifying [0] results in that using by default.
$entity->some_field->value = 'Whatever';
$entity->some_field[0]->value = 'Whatever';

// To add a value for the second item:
$entity->some_field[1]->value = 'Something';

// And persist to DB:
$entity->save();

Edit, the following script works for me and gives me the following output:

<?php
use Drupal\node\Entity\Node;

$node = Node::create(array('type' => 'article'));
$node->field_tags->target_id = 5;
var_dump($node->field_tags->getValue());

$node->field_tags[] = 6;
$node->field_tags[] = array('target_id' => 7);
var_dump($node->field_tags->getValue());

unset($node->field_tags[1]);
var_dump($node->field_tags->getValue());

Output:

array(1) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
}
array(3) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [1] =>
  array(1) {
    'target_id' =>
    int(6)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}
array(2) {
  [0] =>
  array(1) {
    'target_id' =>
    int(5)
  }
  [2] =>
  array(1) {
    'target_id' =>
    int(7)
  }
}

The delta is off then in the last example, but this will probably be fixed in https://www.drupal.org/node/2164601, which might also affect how the code above works..


Micro commerce feature I need to add a new feature to my site that allows users to buy a services.

We have 1 service now to be sold, and may extend to have 3 in the future with no attributes nor shipping, just a sales price.
 What should we use to implement this?

Commerce, ubercart or none of them?

you can sale services in both Commerce and Ubercart. But if you look for simplicity I should tell you Commerce is simple and light enough.

At this time I can't remember any other solution on D7 except writing custom module. which I don't recommend.


Drupal user profile image alt text is showing special characters Drupal user profile image alt text is showing special characters instead of a quote in the user name. My user name is Derek O'Rourke  and the alt text for user profile image is showing Derek O&#039;Rourke's picture"which is not correct.

I couldn't find a way to update it. Please help me.

Assuming Drupal 7, in the template.php of your theme, add this function:

function themename_preprocess_user_picture(&$variables) {
  $variables['user_picture'] = htmlspecialchars_decode($variables['user_picture'], ENT_QUOTES);
}

The problem arises from the template_preprocess_user_picture() function in user.module. It passes the alt text through the t function, which in turn calls htmlspecialchars() and it is here the apostrophe is encoded as &#039;

In your theme function, the HTML code of the user picture tag will be available in $variables['user_picture']. Passing the HTML code through htmlspecialchars_decode() will convert &#039; back to an apostrophe.


Sharing the same templates by importing PHP files: Where should I store those PHP files? I want to be able to just edit standard PHP files which are then imported into many themes.

I feel like a module is an overkill, so I'm happy with just a folder of files.

Your question states "I feel like a module is an overkill", but (according to your own comment) the Domain ThemeKey module works perfectly for your use-case along with importing php files.
Some details about this module (from its project page):

Integration of Domain Access and ThemeKey.
Module provides additional ThemeKey properties:

domain:site_name - returns current domain's site name
domain:id - returns current domain's id
domain:machine_name - returns current domain's machine name
domain:is_default - returns true if current domain configured as default domain
domain:is_alias - returns true if system:host is an alias for current domain


How to manually make sure the database schema is right? I updated my drupal installation to 7.7 and now it keeps giving me an alert that the database schema needs to be updated for views and google analytics. I click on it and follow the onscreen instructions and there are NO errors, and the message is still there. Can I manually make sure the schema is up to date and deactivate the warning message?

The Schema module gives you a lot of different tools to handle your schema; for example, it checks whether your schema is in sync with your database.


Form API: fomatting the date select lists? I'd like to format my date select input, using the following time formats:

12-hour format of an hour without leading zeros
Minutes with leading zeros

Here's my form definition:

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
  );

However, the hours format as 24-hour format of an hour without leading zeros (code G).

It's as if 'g' is being turned into 'G'. Any ideas? Thanks.

In date_parts_element() there's the line

$hours_format  = strpos(strtolower($element['#date_format']), 'a') ? 'g': 'G';

This is deciding on whether to be 24 hour on the presence of the AM/PM specifier. If you change the format to d-F-Y g:i a it should work I think.

If you don't want to display the AM/PM specifier, but fix it at a particular value, you can do something like this

  ...
  // Add a new process function to this date_select to hardcode am/pm.
  $info = element_info('date_select');
  $process = $info['#process'];
  $process[]= 'MYMODULE_date_select_process_am_only';

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i a',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
    '#process' => $process,
  );
  ...

/**
 * #process callback for a date_select element that removes the AM/PM specifier
 * and hardcodes its value to AM.
 */
function MYMODULE_date_select_process_am_only($element) {
  $element['ampm']['#type'] = 'value';
  $element['ampm']['#value'] = 'am';

  return $element;
}

It's untested but works in my head (: If you wanted to do the same thing on a number of different forms, there's a more elegant way (let me know if you're interested).


After update to Drush 7 still version 6 Running on Debian I have updated Drush to version 7:

composer global require drush/drush:7.*

composer global update

But the command 'drush --version' still tells me:
Drush Version : 6.2.0

I have looked everywhere but didn't find a solution.

Thanx for any help.

The problem is that the old version of Drush is still in your $PATH, and comes before the new version.

The Drush installation instructions says:

Now add Drush to your system path by placing export PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac OS users) or into your ~/.bashrc (Linux users).

What it does not mention is that changes to your .bashrc file are not immediately reflected in your running system.  You need do one of:

Restart.
Close and re-open all of your terminal windows.
Type source ~/.bashrc in all of your open terminal windows.

(Listed in order from easiest and most disruptive, to more work but less disruptive.)  Substitute .bash_profile in place of .bashrc if you made your modification there.


webform module in drupal I've installed the webform module in my drupal site and want to configure it so that the submission limitation is by email instead of cookies. I dont want users who have already submitted to submit twice if their email is in the system. Is there a way to do that? Would I Have to create a new module for this? If so, how do I communicate my new module with the webform module? Or would editing this webform module be the solution (which I dont think is a good idea in case I have to upgrade it and lose the changes I've done).
Please help. Thanks.

You can use the webform validation   to create a rule that compares the e-mailaddress with all e-mailaddresses in the table where the webform data is stored (you will have to look it up but I believe it is the email field in the webform_emails table).
Or you can create a custom module depending on webform_validation to compare data, there is a similar issue in the issues..


How to add users under a specific role We have 4 type of users -

Admin   -  can view and manage all other users
Parent  -  Can view and manage students but own child
Teacher -  Can view and manage students assigned to him
Student -  Can view and manage own profile & details

So it's clear that everything is around students can be accessed by 3 other roles as per rules.

I am trying with different role and users modules but not getting exactly how to setup this structure in drupal.

I am sure there is definitely a way to do this because it's a general requirement and drupal has a way to implement this. But I am newbie and trying from couple of hrs but not able to set this.

Anyone please guide me on this or share any link where I can get exact information regarding this.

Thanks is Advance

I assume you use something like Entity reference to add children to parents and to teachers.

I don't think that default Drupal supports this kind of user permissions. As I couldn't find any modules for this functionality, you probably need to do some coding.

The easiest approach would be altering the user/%uid/edit menu item with a custom access callback in a custom module. This ensures users can only access the user edit pages matching your criteria:

function MYMODULE_menu_alter(&$items) {
 if (isset($items['user/%user/edit'])) {
   $items['user/%user/edit']['access callback'] = '_mymodule_user_edit_access';
  }
}

function _mymodule_user_edit_access($account) {
  global $user;

  // May edit own profile
  if ($account->uid == $user->uid) {
    return TRUE;
  }

  // Check if $user has permissions to edit $account
}

The access callback should check if the $user has role Teacher or Parent and if it is referencing to the $account->uid.

Edit:

I just realize you also need to manage profile view rights, this could be done with the same hook, on path user/%user.


How to get Users Email address in an Rest Export View for auth users i build a Rest export view for autocompletion of an textfield. The input should autocomplete email addresses of all logged in users. As admin thats possible, but not as authenticated user, the email addresses get stripped from the result on field access level.

The use case is a share form between users on the same platform ( contact form is not suitable ).

I know this is a security measurement but this platform is for logged in users only and all users are from the same company.

I could hack around the core functions but i wanted to ask if there is a better way to do this?

Greetings,

yobottehg

Access to the user fields is controlled by \Drupal\user\UserAccessControlHandler::checkFieldAccess(). Which returns forbidden() for email except if it's the current user or the user has administer users permission (which you obviously don't want to grant your normal users).

That is called by \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess(), collects the default access and everything returned by hook_entity_field_access(). You can't directly overrrule a forbidden(), but you can implement hook_entity_field_access_alter() and replace the default access check with one that allows access.


8 autocomplete pass current value to function I am trying to use autocomplete in a custom form, but I don't know how to pass the current value of the field to the autocomplete function.

This is my form element:

  $form['gs_name'] = [
    '#type' => 'textfield',
    '#title' => $this->t("Name"),
    '#autocomplete_route_name' => 'gseight_autocomplete',
    //'#autocomplete_parameters' => array(),
    '#required' => TRUE,
  ];

Route:

gseight_autocomplete:
  path: 'gseight_autocomplete'
  defaults:
    _controller: '\Drupal\gseight\Controller\GsEightAutoComplete::content'
    _title: 'Autocomplete Results'
  requirements:
    _permission: 'access GS simple page'

Inside GsEightAutoComplete

public function content($q = '') {

    //get user
    $userCurrent = \Drupal::currentUser();
    $uid = $userCurrent->id();

    $selectthree = db_select('gs_plans','g');
    $selectthree->addField('g','gs_name');
    // Filter only current user".
    $selectthree->condition('g.uid', $uid);
    $selectthree->condition('g.gs_name', '%' . db_like($q) . '%', 'LIKE');

    $currentone = $selectthree->execute()->fetchAll();

    $jsonarray = array();

    foreach($currentone as $eachcurrentone) {
        $jsonarray[] = $eachcurrentone->gs_name;
    }

    return new JsonResponse($jsonarray);

    }

The array fills with items from the database that belong to the current user when i have $q = ''at the start. But how do I pass the current value of the field to q?

The form value is automagically added as a query parameter so it is not necessary to pass the current value. This is accessible in the Request object. The controller class method should be:

public function autocomplete(\Symfony\Component\HttpFoundation\Request $request) {
  $value = $request->query->get('q');
}


How to check if a user has privs to access a node in organic groups Does someone know what function within Organic Groups I can use to check if a user (the signed in user) as access to a given node? Do you have an example?

Thanks

The same function you should always use in any context: node_access('view', $node);

Modules are expected to use node access hooks to implement access control, so this function will consider all of the modules that may grant or remove access to the given $node object.


Is it possible to get node alias during hook_node_insert() I need to get the node alias during a hook_node_insert() when creating a brand new node. Function drupal_lookup_path() returns blank because the node actually isn't created yet per hook_node_insert() docs.

Does anyone know of a way to accomplish this or of an alternative to hook_node_insert().

A couple of options there, if drupal_lookup_path isn't returning the alias yet.

Get the alias using pathauto_create_alias without the _pathauto_set_alias save part ( update: can use the 'return' option)
Add the node id to a cron queue defined with hook_cron_queue_info and get/process the alias in a worker_callback a little later.


Recoverable fatal error when trying to run hook_query_TAG_alter() I used the approach provided here to reverse comments order in Drupal 8:

    /** Implements hook_query_TAG_alter().
 *
 * Alter comments query to order by DESC as well as the default ASC.
 */
function MYMODULENAME_query_comment_filter_alter(QueryAlterableInterface $query) {
  $orderby = &$query->getOrderBy();

  // Sorting for threaded comments.
  if (isset($orderby['torder'])) {
    // Sort by root parent first, then normal threaded.
    $query->addExpression("SUBSTRING_INDEX(c.thread, '.', 1)", 'rparent');
    $orderby = array('rparent' => 'DESC') + $orderby;
  }
  // Sorting for flat comments.
  else if (isset($orderby['c.cid'])) {
    $direction = 'DESC';

    $orderby['c.cid'] = $direction;
    $orderby = array('c.created' => $direction) + $orderby;
  }
}

but I receive the followig error when run the module:

  Recoverable fatal error: Argument 1 passed to
  mymd_query_comment_filter_alter() must be an instance of
  QueryAlterableInterface, instance of
  Drupal\Core\Database\Query\PagerSelectExtender given, called in
  D:\wamp95\www\drupal83\core\lib\Drupal\Core\Extension\ModuleHandler.php
  on line 501 and defined in mymd_query_comment_filter_alter()

what is the problem and how should I solve it?

I used Drupal\Core\Database\Query\AlterableInterface $query as argument.

It solved the problem.


phpcs rule or sniff for detecting usage of the "ksm()" or "kint()" function? Would it be possible for my local PHPCS standard to warn me when I use certain PHP functions like kint() or ksm()? It's not part of the Drupal Standard but I'm running a modified version with some improvements like this.

Yes, it is possible by Checking Drupal coding standards. You can configure PHP code sniffer to check for Drupal coding standards by following the instructions from https://www.drupal.org/docs/contributed-modules/code-review-module/installing-coder-sniffer and https://www.drupal.org/node/1587138
Edit: It turns out you can not identify all the debugging functions with standard Drupal Coding standard functions.In my testing drupalcs was able to identify only dpm()and dsm() functions but not ksm() or kint() .
There is an alternative way to identify debugging functions. You can add pre-commit hook to identify the debugging functions.
You can add the below script to git hooks.
#!/bin/sh

#
# Git pre-commit hook that prevents code that is not Drupal coding standard compliant of being committed.
#
# Fork of https://git.io/fNXBi by Dave Hall http://davehall.com.au
#

# Fetch the list of files that have changed.
FILES="$(git diff --staged --name-only HEAD --diff-filter=ACMRUXB)"

echo "Running PHP lint check" >&2
LINT_FAIL=0
for filename in $FILES; do
  if ! php -l $filename; then
    LINT_FAIL=1
  fi
done;

# There is no point in running PHP Code Sniffer on broken files.
if [ $LINT_FAIL -gt 0 ]; then
  echo "Commit aborted. Fix your code. Then 'git add' and 'git commit' again."
  exit 1
fi

echo "Running PHP Code Sniffer Checks" >&2
echo $FILES | xargs phpcs --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
if [ $? -eq 0 ]; then
 # Exit executing the git commit.
 exit 0
else
  # Ask what to do, not executing the commit. Source: https://unix.stackexchange.com/a/121255/139407
  read -p "Fix the marked Sniff violations automatically [Y/n]?" line </dev/tty
  case "$line" in
    y|Y) echo $FILES | xargs phpcbf --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
      ;;
    *) echo "No automatic corrections made."
      ;;
  esac

  echo "Commit aborted. Make remaining manual code fixes if necessary. Then 'git add' and 'git commit' again."
  exit 1
fi

Source : Drupal git pre-commit hook


Allow commenting on front page? My client wants a comment section on the front page only. I can't figure out how to allow commenting on the front page. I tried allowing commenting on basic pages, but it wont show on the front.

Thanks.

Excerpt from modules/comment/comment.module inside function comment_node_view($node, $view_mode):

// Only append comments when we are building a node on its own node detail
// page. We compare $node and $page_node to ensure that comments are not
// appended to other nodes shown on the page, for example a node_reference
// displayed in 'full' view mode within another node.
if ($node->comment && $view_mode == 'full' && node_is_page($node) && empty($node->in_preview)) {
  $node->content['comments'] = comment_node_page_additions($node);
}

commenting for the node must be turned on
The node must be shown in the full-view_mode (normally this is node/<nid>)
node_is_page(): Whether the current page is the full page view of the passed-in node.
It must not be an edited preview of this node.

If you still feel like showing the comments on the frontpage for a specific node, try this:

$frontpage_commenting_node = node_load( **1** );
print render(comment_node_page_additions($frontpage_commenting_node));

Note:
 - You need to change the parameter of node_load to the effective node id in your system.
 - This is for Drupal 7


How to remove bullets from drupal menu? I have created a drupal menu and added a couple of links. Unfortunately, when displayed, these come with bullets. How can I remove these? I am using the Precise theme, but it does not seem to be added by this theme.

This could be default browser styles. It does't matter if they are added by the browser by default or by CSS, the solution is to remove them with CSS.

li {
  list-style: none;
}

You should create a sub_theme where you create and add your custom styles.


drupal image upload programmaticaly i am using drupal 7 . and i am trying to upload image progrmatically .. here is my code

$image = file_get_contents('http://drupal.org/files/issues/druplicon_2.png'); // string
$file = file_save_data($image, 'public://druplicon.png',FILE_EXISTS_REPLACE);
print_r($file); exit

and here is my output

stdClass Object
(
    [fid] => 4
    [uri] => public://druplicon.png
    [filename] => druplicon.png
    [filemime] => image/png
    [uid] => 1
    [status] => 1
    [timestamp] => 1378142542
    [filesize] => 0
)

now here filesize is 0 . as file doesnot contain any data.  i am working on local m/c.  here is no issue of permission.
Does anybody tell me how to solve this

Thanks

The ability for file_get_contents() to fetch contents from an HTTP server depends on the allow_url_fopen parameter in php.ini

If it's not set, $image will be false and saving this leads to an empty file.

You may use Drupal's system_retrieve_file() instead. It's a wrapper on top of drupal_http_request() that comes with its own HTTP client implementation.

Example:

$file = system_retrieve_file('http://drupal.org/files/issues/druplicon_2.png',
                             'public://druplicon.png', false,  FILE_EXISTS_REPLACE);


How to remove text from browser title? I'm looking for a way to change the text ' | Drupal' part from the  tag for all pages to ' | ToAnyThing'. I guess it should be possible to achieve this in the admin interface somewhere, but I cannot find where.

Thanks.

This question seems somewhat off-topic as you don't know what this thing is and how to generally change that, independent from Drupal, and I'd recommend to find that out first.

But to take a shortcut from here: that's the so called meta title. And you'll be able to customize it pretty heavily by using Metatag.

  The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about a website. In the context of search
  engine optimization, when people refer to meta tags they are usually
  referring to the meta description tag and the meta keywords tag that
  may help improve the rankings and display of a site in search engine
  results. In addition, the module provides support for meta tags (Open
  Graph Protocol from Facebook, Twitter Cards from Twitter) that allow
  control of how content appears when shared on social networks.


Remove post featured image I want to remove post featured image from http://bit.ly/XkE8vG.
I have tried a lot by looking in to theme files but couldn't find any way.

Go to the content types page on admin/structure/types, click on "Manage display," and drag the field to the "Hidden" set.

For D6

You can do the same in node-type/<type>/display. Click exclude/ make the select box to hidden.

Also you can use this code in node.tpl.php.

if ($teaser) {
  // node is being displayed as a teaser
  // Anything here will show up when the teaser of the post is viewed in your taxonomies or front page
} else {
  //all other cases
  //Anything here will show up when viewing your post at any other time, e.g. previews
}


How do I send an email to all users with a particular role? This was quite straightforward in Drupal 7 as I recall but, with Drupal 8  there's a lot of info I don't understand as a site builder that I am being asked to provide when creating a new rule.

I'd be very grateful for some step by step help.

I want to send an email to all users with the role of "Officer" when a node of type "Agenda" has been updated.

Right now (Feb 10 2018) I have:

"drupal/core": "8.4.4"
"drupal/mailsystem": "4.1"
"drupal/swiftmailer": "1.x-dev"
"drupal/rules": "3.x-dev"
"drupal/typed_data": "1.x-dev"

I'm a bit familiar with the (amazing!) Rules module. But to my knowledge the current answer to this question is a No go, that is: can't do that yet with the most recent D8 version of Rules.
Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.
BTW, Rules documentation for D8 contains the official Rules documentation specific for D8.
Plan B
While waiting for Rules to become more mature, you can use the Admin Content Notification module as a temporary alternative (which does have an official D8 release already). Some details about it (from its project page):

... can be used for receive email notification when a new content of any content type will be created on your site. Although one can use rules for the same functionality but it's not good to use rules only for notification as it is a huge module, so we can use this module for small websites.

The "...Although one can use rules for the same functionality ..." part of this clearly does not apply to the D8 version of Rules (yet).
The image shown on the project page gives an idea of what this module can be used for.
Obviously, your question is about updates of content. But even though it doesn't say so (yet) on the project page, just have a look at the issue "Also trigger event on update", which appears to be as in your question.


Print out the contents of node object in a node template How do I print out the contents of the $node object in a node template in a way that is easily readable. I thought that <?php dpr($node);?> would do it but that doesn't seem to work in my template.

Try below code

<?php
   print "
";
   print_r($node);
   print "
";
?>

Alternatively you can use below code too...

<?php
  drupal_set_message("
" . print_r($node, 1) . "
");
?>


Add style attribute to view fields I would like to add a style attribute to each title fields in my view. I have created one field for a color. I tried to rewrite the result like this:

[title_1]

But the style attribute will be removed. I'm using Drupal 7.

Any help appreciated.

You can set a class to the title field using Style Settings as shown below screen. You can user token replacements in style settings to set class to the title field.

Using small javascript or jquery read the class of title field and set the color same as class name using CSS property.


How to create a suggested content view using Flag and Flag Terms modules? I am using Flag and Flag Terms modules to allow users tagging the content and taxonomy terms they like or dislike.

How do I create a view or a block that shows and sorts content based on tags assigned to, the way that prioritizes tags the current user subscribed for ?

Set up as in my previous question:  How do I set up user's "Favorite Tags" and "Ignored Tags" tag subscriptions?.

I just tried it out. I need to add it to my site too and the 50 points bounty was enough incentive to move it up on my list ;-)

After installing flag and flag_terms you create a new flag and select "Taxonomy terms" as the "Flag Type". Configure the text options, select a vocabulary (or many),  permissions and select the "Display link on taxonomy term pages" checkbox.

Then view a few terms on the standard term page and flag them using the new link.

Then create your view for content from your selected "vocabulary". The trick is that you have to add the "Content: Taxonomy terms on node" relationship first. Only then can you add the "(term) Flags: termflag (by current user)" relationship and select your "term flag" you entered previously. If you "require this relationship" it will only show you nodes where the term has been flagged.


How to resolve my Open Atrium installation error? I am very new to open atrium.  I installed Open Atrium and now the home page is not loading properly. Instead I have the following error:

  Warning: file_put_contents(temporary://fil29F1.tmp): failed to open
  stream: "DrupalTemporaryStreamWrapper::stream_open" call failed in
  file_unmanaged_save_data() (line 1936 of
  C:\wamp\www\openatrium\includes\file.inc). The file could not be
  created.

Try this

open -> admin/config/media/file-system

Change Temporary directory -> sites/default/files


adding yet another domain to multi-site but this time symlink not working Have no idea what's going on here. I'm trying to add another new domain to my multi-site but keeps directing to apache test page - not install.php.

Have many subdomains installed now and one new domain added to root one but this next one is giving me problems for some reason. Everything has been done same way. Set up in server to point to IP; separate database created; name of domain in sites folder created with default.settings.php copied to it as settings.php and chmod 644 then a symlink from the /var/www/html folder to the sites one but as I say just keep getting apache test page. Not found if try going to install.php. This is happened to me before but don't have a thorough understanding why...i am suspecting has something to do with database- not sure.

This has nothing to do with your database. At this point you have probably a problem completely unrelated to Drupal. Instead your Apache is not aware of your Drupal installation.

Here is a list of things you should check:

Is that domain we're talking about pointing to your server (or do you see the test page of a different one): compare IP by ping yourserver.com

If it's a "testdomain" you might want to add an entry to /etc/hosts

Is your virtual host configured correctly?

Did you set a ServerName or a ServerAlias
If you were setting up a new VHost, did you enable it (sudo a2ensite yourhost for instance)
Did you restart Apache/reload configuration after doing this (sudo service apache2 reload)?
Did you configure your VHost/your root directory to follow symlinks?
Have you set NameVirtualHosts?

Are your symlinks pointing to the right folder?

Do you get the contents of your settings.php by typing cat /var/www/html/sites/symlink/settings.php in a terminal or an error?

As an example:

<VirtualHost *:80>
  ServerName yourdomain.com
  ServerAlias sub1.yourdomain.com sub2.yourdomain.com # etc ...
  DirectoryIndex index.php
  DocumentRoot /var/www/html
  <Directory /var/www/html>
    AllowOverride All
    Options -Indexes FollowSymLinks Multiviews
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Again, it's most probably not Drupal related. It would be if you'd see a different one of your multisites or Drupal complaining about something but since you got the Apache test page you might want to ask on a different board (serverfault) and provide some more information (OS, directory structure, current host configuration and so on) if my checklist didn't help you.


Thoughts on customizing the user profile page? I'm looking to really transform the user profile page for my drupal 7 site and community into something enganging and interative. Perhaps a friends block, list of social media links like fb, linked in, etc as well as to be able to see new posts and comments that that user has contributed to the site.

Certainly we can do better than the default drupal page these days!

What modules do you recommend to start putting together a recipe for a quality and informative user profile experience?

Also, does you have any links for tutorials that would be good resources? Perhaps even a cool profile page you have done as an example.

I think the two key modules for this would be Views and Panels. That should get you most of the way but, depending on what you want to display, you may need some other modules.


Add paragraphs item to user entity I want to create a new paragraph item to a user bundle. This is the code:

$name = "Test";
$userdata = user_load($user->uid);
$paragraph = entity_create('paragraphs_item', array('field_name' => 'field_userdata', 'bundle' => 'userdata'));
$paragraph->setHostEntity('user', $userdata);
$paragraph->field_name[LANGUAGE_NONE][0]['value'] = $name;
$paragraph->save();

But nothing happens, no errors, no new entity..
Are there differences to adding to a node bundle?

Thank you!

First make sure following things are configured properly:

Is Entity API module is enabled in your site?
Have you enabled Logging and errors from admin/config/development/logging page, to see site errors?
In second line you have not defined $user object, are you defined else where?
How are you calling this function?

If everything is configured properly then execute following code:

$name = "Test";
global $user;
$userdata = user_load($user->uid);
$paragraph = entity_create('paragraphs_item', array('field_name' => 'field_userdata'));
$paragraph->setHostEntity('user', $userdata);
$paragraph->field_name[$userdata->language][]['value'] = $name;
$entity->save();


Page not found return false Im using a custom query to display some content.
This query uses url arguments as MySQL variables.

Usually when I create a link with the variables the page does not exist and it returns a 404 error.

Is there a way of creating a page on certain urls to avoid getting an "page not found"?

EDIT:
To be more specific

The query is something like

SELECT * WHERE node.type = '.arg(0).' AND node_data_field_type.field_type = '.arg(1).'

The url intended would be: example.com/exhibition/speacial_feature or
example.com/program/speaker_series

The link exhibition/speacial_feature or program/speaker_series are not found.

Supposing that example.com is a site running Drupal, what Drupal does when you try to access  example.com/exhibition/speacial_feature is:

Verify exhibition/speacial_feature is a path alias
Verify there is a menu that uses exhibition/speacial_feature as path
Verify a module define a menu callback for exhibition/speacial_feature

If none of the conditions is verified, then Drupal returns a 404 error.

In your case, as you want to execute code when a path is entered, you need to create a module that defines a menu callback.

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

  $items['mymodule/%/%'] = array(
    'page callback' => 'mymodule_abc_view',
    'page arguments' => array(1, 2),
  );

  return $items;
}

function mymodule_page_view($first, $second) {
  // Execute the query, and show the result.
}

The code for hook_menu() I shown is the minimum required; see hook_menu() for more information.

As also noted from Berdir, you don't concatenate input given from a user to obtain the query to execute, as that causes SQL injection. You need to use query parameters, which are supported in any Drupal version. Also, with static queries, the name of the database tables are surrounded by { and }.


CKEditor oEmbed Plugin Shows up in config but not in actual Editor instance The issue I'm having is very similar to this question, but the solutions here did not work for me.

The steps I took:

Downloaded the latest version of the oEmbed plugin from https://ckeditor.com/cke4/addon/oembed.
I extracted the oembed directory from the archive and placed that in a custom Drupal module that I already had. This module was used to create simple CKEditor button plugins and worked fine with them.
I went to the configuration page for basic_html and full_html editors and saw that the oEmbed button was one of the new options (/admin/config/content/formats/manage/basic_html).
I moved the oEmbed button to the "Active Toolbar" as well as some other custom plugins.
I went to edit some content where the WYSIWYG would show up
The other custom buttons showed up, but the oEmbed one did not, despite the fact that I could see it on the config page.

I've tried an older version of the oEmbed plugin from the download page, as well as clearing my cache many times with drush cr, but still no luck getting it to show up.

What's weird is that when I load the node edit page with the Chrome console open, I can see that the Javascript/CSS for the oEmbed plugin is loading and executing. The button icon though is never requested.

The Drupal Plugin looks like this

namespace Drupal\custom_ckeditor\Plugin\CKEditorPlugin;

/**
 * Defines the OEmbed plugin, with CKEditor.
 *
 * @CKEditorPlugin(
 *     id = "oembed",
 *     label = @Translation("OEmbed Plugin")
 * )
 */
class OEmbed extends extends PluginBase implements CKEditorPluginInterface, CKEditorPluginButtonsInterface
{
    protected $pluginName = 'oembed';

    public function getButtons()
    {
        $iconImage = $this->getIconPath();
        return [
            'OEmbed' => [
                'label' => t('Insert OEmbed'),
                'image' => $iconImage,
            ]
        ];
    }

    // Other required functions such as getLibraries() and getDependencies() all return an empty array or false and are omitted from this example.

}

I'm using Drupal 8, with CKEditor v4.7.2.

I figured it out. On the Drupal side, everything was configured correctly. The error was in the Javascript. The original plugin.js file has the following:

editor.ui.addButton('oembed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

I modified this to

editor.ui.addButton('OEmbed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

Note the name passed to addButton() from oembed to OEmbed. I think there was some conflict in naming it oembed, possibly from some existing functionality. Not sure, but that was the fix for me.

In addition, I should note that for the Basic Editor, I had to modify the HTML filter to allow tags that the oEmbed plugin added to the source view. Hope this helps someone.


Is it possible to avoid using Views PHP? I have a number of values that I need to run a bit of logic on to get a value for a views math expression further down the chain. Im going to provide a much simpler example of what I am actually doing...

Variables set on custom module admin page...

twoyr_a = 5.4
twoyr_b = 12.4
threeyr_a = 5.6
threeyr_b = 12.7
fouryr_a = 5.8
fouryr_b = 13.3

Contract term (Factor A) - Overidden with views-views-field--factor--a.tpl.php

if ($output == '24') {
    print variable_get('twoyr_a');
} elseif ($output == '36') {
    print variable_get('threeyr_a');
} elseif ($output == '48') {
    print variable_get('fouryr_a');
} else {
    print '0';
}

Contract term (Factor B) - Overidden with views-views-field--factor--b.tpl.php

if ($output == '24') {
    print variable_get('twoyr_b');
} elseif ($output == '36') {
    print variable_get('threeyr_b');
} elseif ($output == '48') {
    print variable_get('fouryr_b');
} else {
    print '0';
}

Views Global:Math Expression

[factor_a] + [factor_b] = result

However, the result is always wrong. Instead of using the result from the PHP template, it is adding the Contract terms (24 + 24 = 48).

Im guessing this is because the math expression runs before the template files do.

So my question is, is there anyway to avoid using Views PHP for this? Or is there a fix for my current solution?

Note: $output is already defined in the database as 24, 36, or 48 in a "Contract Term" column. It relates to just a normal field in an ECK entity type called "Deal". It's an integer value to define the length of a contract for that deal. Each contract term has its own A and B factors to calculate my clients profit percentage when borrowing from a loan company.

A possible solution that might help to simplify the challenge in your question, is to use the fairly new Math Field module (for D7). Some more details about this module (from its project page):

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

By creating some auxiliary field(s) (calculated via the Math field), you may be able to complete your puzzle. Possibly via some additional logic implemented via the Rules module, to implement logic that is similar to what I described in my answer to "How to set the values of some fields depending on the value of a list box?".

For more details (step-by-step instructions) about Math Field, refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).


How to display all when input argument is wrong I create a view display a books depend on url argument (book type name) ... And when book type name is not exist in book types list ... view be empty .. how can I when the url argument is wrong, display all books?

thank you

For contextual filters, the Views UI allows you to specify two different cases:
Case 1: If the filter value is not passed to the URL
In the contextual filter configuration, in the "When the filter value is not in the URL" section, you need to set the "Display all results for the specified field" option.
Case 2: If the filter value is wrong
In the contextual filter configuration, in the "When the filter value IS in the URL or a default is provided" section, you need to check the "Specify validation criteria" checkbox. Then, you can set the "Action to take if filter value does not validate" to "Display all results for the specified field".
You can see more details in the Views documentation: https://www.drupal.org/node/1578574
Hope it helps,


Show Description Field on Individual Webform Submission Result I would like to include the description field when viewing individual webform submissions for each component. The standard webform individual submission display shows the label and the answer, but the description field for the component is not shown.

I had a look at webform-submission.tpl.php but wasn't sure how I could modify this to include the description being displayed.

Can anyone tell me how I can get the description to display?

I'm using Drupal 7 with Webform 7.x-4.19

After looking through the webform module I found out how to achieve this.

I used hook_webform_component_display_alter() which is there to enable customising the display of components in display only contexts. This function is in webform.api.php. I created my own function using this hook in a custom module to add the description to all textfield components as follows:

<?php
function my_mod_webform_component_display_alter(array &$element, array &$component) {
  if ($component['type'] == 'textfield') {
    $element['#description'] = $component['extra']['description'];
  }
}

For reference, the notes and example given from the webform module for hook_webform_component_display_alter() are:

/**
 * Allow modules to modify a "display only" webform component.
 *
 * @param array $element
 *   The display element as returned by _webform_display_component().
 * @param array $component
 *   A Webform component array.
 *
 * @see _webform_display_component()
 */
function hook_webform_component_display_alter(array &$element, array &$component) {
  if ($component['cid'] == 10) {
    $element['#title'] = 'My custom title';
    $element['#default_value'] = 42;
  }
}


How to remove a page from a books and/or delete a book? I placed a basic page into a book but now want it removed from every book. In the book outline settings I only see a way to move it to another book, I see no option to set it to none. I also don't see a way to delete a book in structure/books.

One option I've considered is uninstalling the book module and reenabling it but I'd rather not lose every book I have because of one page.

Is there a way to remove a page from a book, and/or delete a book without uninstalling the book module?

There is a option to remove the any page from the Book outline. Suppose I have created a basic page and put in a Book outline. Now if I want to remove, click outline as shown in the follwoing image

Now, you can see Remove from book outline in red in as show in following option. That will remove that Basic page from the book.

Update:

You can not delete entire book at a once. Why, because Book is just a indexing tool, It is not a content type. Book page is a content type. Book page and Book are two different thing. And it should be that way. Hence, you can delete all nodes of one content type by deleting that content type itself. But, if you are putting some node under book outline, you are not creating a entire group/content type, You are just indexing your node in specific order.

Hence, If you delete any Parent item in book, It shows a message that the child will be re-ordered automatically. Hence, you can understand its just a ordering/indexing tool.

Hence, to provide this feature Book Delete module was created. But still it does not have Drupal 8 Version.


How can I add  to all checkboxes? I just want to wrap checkboxes like this in all the forms, automatically.

    <input type="checkbox">
    Checkbox

How can I achieve this? Is there any hook available for this?

Yes, there is a theme hook that will let you alter every instance of a checkbox. The two theme hooks you'll want to look at are:

theme_checkbox() - https://api.drupal.org/api/drupal/includes!form.inc/function/theme_checkbox/7
theme_checkboxes() - https://api.drupal.org/api/drupal/includes!form.inc/function/theme_checkboxes/7

Sample Code

Here's some sample code, available in the API doc links I provided above.

function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

You can override the markup returned by implementing this theme hook.


Drupal 8 : Render a field collection item in a Twig template In Drupal 8, I have a content type which use Field Collection Module like that :

field_body (FieldCollection, repeatable)

field_image_alignment(Boolean)
field_picture (Image)
field_free_text (Long Text)

I want to theme this fields.
I overrided the field template with a file named field--node--field-body--news.html (news is the content type that contains theses fields.).

Default template is this :

{% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
{% endfor %}

And my template overrided is like that :

{% for item in items %}
  {% if item.content['#field_collection_item'].field_image_alignment.value == 1 %}
    {{ dump(item.content['#field_collection_item'].field_picture) }}
    {% endif %}
{% endfor %}

How can I render "child" fields field_pictures, field_free_text ?
I used item.content['#field_collection_item'].field_image_alignment.valueto access to the plain value but I would like to have the rendered view.

Thanks a lot.

I've just started learning Drupal and encountered the same issue.
I solved it by creating custom field formatter:

public function viewElements(FieldItemListInterface $items, $langcode)
{
  $elements = array();
  foreach ($items as $delta => $item)
    if ($item->value !== NULL)
    {
      $builder    = \Drupal::entityTypeManager()->getViewBuilder('field_collection_item');
      $elements[] = $builder->build($builder->view($item->getFieldCollectionItem()));
    }
  return $elements;
}


Is it possible to set multiple permission in hook_permission()? Let's say I have a custom module. Now I upgrade the module and add some new functionality which is bound to the old functionality. I already have a hook_permission() set in the old version. But now need a second permission to keep unauthorised users away from accessing the new function. Is it possible to set a second permission in the same module? How would I do that?

That's how my hook_permission looks for now:

function MYMODULE_permission() {
  return array(
    'name of permission' => array(
      'title' => t('Access Something'),
      'description' => t('Access Something to do something'),
    ),
  );
}

Of course:

function MYMODULE_permission() {
  return array(
    'name of permission' => array(
      'title' => t('Access Something'),
      'description' => t('Access Something to do something'),
    ),
    'name of another permission' => array(
      'title' => t('Access Something Else'),
      'description' => t('Access Something Else to do something'),
    ),
  );
}


Theme mobile optimization and upgrade suggestions I am running a medium trafficked Drupal 6 site with some custom modules, theme and a few thousand nodes. Our major woe is optimizing the site for different media displays or just responsify the current custom theme, and perhaps upgrade to Drupal 7 along the way.

What do you suggest about the following pathways?

Should I not worry about upgrading to Drupal 7, create a seperate jQuery mobile site and separate the mobile traffic to m.domain.com using domain module? It is very challenging to make themes responsive in Drupal 6.
Upgrade to Drupal 7, recode the theme to be responsive. But by the finish line, Drupal 8 would have matured enough. Should I even bother to upgrade to Drupal 7?
Wait for Drupal 8 release

Which one would you choose and why? Or any other optimal suggestions?

Cheers
[raises a pint of IPA]

Mobile developing for D6 shouldn't be any harder than for D7.
Actually, i remember that when i was building my last responsive website, there were a few useful modules only available for D6.

D8 much probably won't be out before 2014, and after the official release, it's going to take many months before all the themes and modules will get ported... many people may not be able to use D8 until 2015 or so. Probably.

It will be indeed much more mobile friendly, so it might be well worth the effort of porting.

But I don't really see the need to port to D7 at the moment.

Whether to make a separate site on a subdomain or a single responsive site is a very subjective question. Anyway, mobile_tools will probably have everything you need for both scenarios: https://drupal.org/project/mobile_tools


how to check in ajax form callback if form for failed validation I have a form and on and implemented a ajax submit callback which calls this function:

function popover_ajax_callback($form, &$form_state) {
    // watchdog("ajax_callback", "testing ajax callback", array(), WATCHDOG_ALERT);
    return '
' . $form_state['values']['first']['field_firstname'] . '
';
}

How do I check if the form failed or passed validation within this function?

function popover_ajax_callback($form, &$form_state) {
  $errors = form_get_errors();
  if( $errors ) {
    // error detected, do something
  } else {
    // everything is ok
  }
}

but your return value is not ok. You need to return an renderable array. You may want to try someting like this:

return array('#markup' => '
' . $form_state['values']['first']['field_firstname'] . '
');


How can I overwrite existing menu tree manipulators? Or: how can I prevent unpublished nodes' menu items to be removed in the menu select when the user does not have the bypass node access checks permission, but may actually edit various unpublished nodes?

Im facing the problem that in the node form, the menu item options are missing some menu items because the related node is unpublished although the user may actually see and edit those nodes.

In /core/lib/Drupal/Core/Menu/MenuParentFormSelector.php the function getParentSelectOptions builds the options list which is then used in the node edit forms.

The function is:

  /**
   * {@inheritdoc}
   */
  public function getParentSelectOptions($id = '', array $menus = NULL, CacheableMetadata &$cacheability = NULL) {
    if (!isset($menus)) {
      $menus = $this->getMenuOptions();
    }

    $options = array();
    $depth_limit = $this->getParentDepthLimit($id);
    foreach ($menus as $menu_name => $menu_title) {
      $options[$menu_name . ':'] = '<' . $menu_title . '>';

      $parameters = new MenuTreeParameters();
      $parameters->setMaxDepth($depth_limit);
      $tree = $this->menuLinkTree->load($menu_name, $parameters);
      $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
      );
      $tree = $this->menuLinkTree->transform($tree, $manipulators);
      $this->parentSelectOptionsTreeWalk($tree, $menu_name, '--', $options, $id, $depth_limit, $cacheability);
    }
    return $options;
  }

The critical part in that function is the manipulator
 'menu.default_tree_manipulators:checkNodeAccess'.

The manipulator (/core/lib/Drupal/Core/Menu/DefaultMenuLinkTreeManipulators.php) does the following thing (public function checkNodeAccess):

if ($this->account->hasPermission('bypass node access')) {
  $query->accessCheck(FALSE);
}
else {
  $access_result->addCacheContexts(['user.node_grants:view']);
  $query->condition('status', NODE_PUBLISHED); // <<< wtf?
}

TL;DR

So it assumes "either a user may bypass all node access checks or hide all unpublished nodes from the menu select" - which is weird...

How can I overwrite this?

I was unable to find a way to alter tree manipulators of an existing menu.
But it is possible if you render menu, let's say in a custom block.

Create your own tree manipulator service.

Copied from core.services.yml:

  menu.default_tree_manipulators:
    class: Drupal\Core\Menu\DefaultMenuLinkTreeManipulators
    arguments: ['@access_manager', '@current_user', '@entity_type.manager']

you can define your service in a similar way:

  mymodule.my_custom_tree_manipulators:
    class: Drupal\mymodule\MyCustomMenuLinkTreeManipulators
    arguments: ['@access_manager', '@current_user', '@entity_type.manager']

Then create MyCustomMenuLinkTreeManipulators class that extends DefaultMenuLinkTreeManipulators, define custom method, let's say checkAccessIgnoreStatus() and implement logic you need.

There are many ways to use it, I'd create a new block plugin for that.
Refer to my answer for details on how to render menu with manipulators.

Use your manipulators:

$manipulators = array(
        array('callable' => 'mymodule.my_custom_tree_manipulators:checkAccessIgnoreStatus'),
        // ...
      );


How to display Views exposed filters fields as a table? I would like to display Views "Exposed filters" fields as a regular table, where the first column would be the field label, and the second column would be the field options/select lists.

So for example from this:

I would like to create this:

What is a possible solution for this?

It's easier than I expected.

How-to steps:

Copy views-exposed-form.tpl.php (http://pastebin.com/V77CPxPG) from the Views module's views/theme directory to your own theme's templates directory (but some themes have their template files in their root directory! (or maybe even other directories like theme or sg. else)).
Copy ANOTHER instance of this file to the same directory, BUT now name it so that it also contains the particular view's machine name after two dashes:

views-exposed-form--page_test_ct.tpl.php

(like it's explained here; you should give a unique machine name to your view!)
So in my example, the machine name of the view is page_test_ct, like you can see it here:

Modify views-exposed-form--page_test_ct.tpl.php like this:
http://pastebin.com/1qfim7VX
Clear cache (theme registry).

SCREENSHOTS

BEFORE

AFTER

AFTER; having some exposed operators and descriptions too


admin/content/file missing I have some problems with files. Everyone is talking about admin/content/file, but I just don't have the link under /admin/content, and going to the url by hand returns me to admin/content.

I seem to be pretty much up to date (drupal 7.50, file_entity 7.x-1.5) and media is working (it's just buggy in strange ways).

Where should I look to find why the link is not showing under /admin/content ? Iow, who should be providing the view ? That would give me a clue.

You have to install and enable the File Entity (fieldable files) module:

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

7.x-2.12 works flawlessly.


How can I update a module to a specific version using Drush? I am trying to update module entityform 7.x-1.4 to entityform 7.x-2.0-beta4.

The current version of the entityform module is 7.x-2.0-rc4. But I don't want to update at this version.

Can we update module at specific version using drush?

By default, drush pm-update will update Drupal core and all enabled projects to the latest recommended releases. The optional project argument allows you to provide a list of installed projects to update, thereby limiting the scope of the update.
You can also pass a specific version of Drupal core as a project argument and Drush will limit the upgrade to that version of core (and core only, unless you pass other projects along as arguments.)
drush pm-update entityform-7.x-2.0-rc4


Use Bias with apachesolr module I want to use Apache Solr in my site build with Drupal7.
The server is UP, simples searches are working but I can't boost a field with bias.

For example, I boosted the title (or label in the administration page), giving him a 5 in the select field.

After re-index the node, I searched and the order of the result still the same.

I tried to create a little module with apachesolr's hook to watch the document it send to solr server.

hook_apachesolr_index_documents_alter():

[_fieldBoosts:protected] => Array
(
[id] =>
[site] =>
[hash] =>
[entity_id] =>
[entity_type] =>
[bundle] =>
[bundle_name] =>
[path] =>
[url] =>
[language] =>
[path_alias] =>
[label] =>
[content] =>
[teaser] =>
[ss_name] =>
[tos_name] =>
[ss_name_formatted] =>
[tos_name_formatted] =>
[is_uid] =>
[bs_status] =>
[bs_sticky] =>
[bs_promote] =>
[is_tnid] =>
[bs_translate] =>
[ss_language] =>
[ds_created] =>
[ds_changed] =>
[ds_last_comment_or_change] =>
[is_comment_count] =>
[type_name] =>
[created] =>
[changed] =>
[last_comment_or_change] =>
[comment_count] =>
[name] =>
[tos_content_extra] =>
[access__all] =>
)

All the data are empty.

This is a screenshot of my module setting page.

screenshot http://img338.imageshack.us/img338/7984/drupalsolrconf.png

To verify the boost values are included in your queries, tail the Solr request.log file.  You'll see things like &qf=label%5E5.0 (%5e is a caret ^, which marks the boost value).

Another useful trick for optimizing the scores is to include the score in your themed results output.  You may find the boosts are affecting the scores, but aren't high enough to substantially change the ranking.  This can be added with a small hook:

function hook_preprocess_search_result(&$variables) {
  if (user_access('administer search')) {
    $variables['title_suffix'] = '<code>[score: ' . $variables['result']['score'] . ']</code>';
  }
}


Creating a temporary content type on the fly? I want to create a temporary content type, and a node of that type, in code. It preferably should not live past page load. Can I do that?

For the reason to this very strange request, please see Using field widgets in non-field forms.

If you have suggestions for completely different solutions, then please take those to the linked issue, since this question is mainly a "support" question to the current answer to that question.

$node_type = array(
  'type' => 'temporary_node_type', // This is the machine name.
  'name' => t('Temporary Node'), // This is the human name.
  'base' => 'node_content', // If you set this to your module name, then
                            // *your module's* hook_insert(), hook_delete(),
                            // etc. will get called in addition to
                            // hook_node_*()
  'description' => t('Description.')
  // A full list of options is at http://api.drupal.org/hook_node_info.
);

$node_type = node_type_set_defaults($node_type);

node_type_save($node_type);

// Do something with your node type. You can also add fields here if you
// would like.

node_type_delete($node_type);

Note 1: People with the "administrator" role will see this type on node/add every once and a while, depending on how often you do this.

Note 2: You want to use something more then a hard-coded string for your type attribute to avoid collisions.


Changing "Product [product:title] added to your cart." message in Drupal Commerce I'm trying to change/customize this message and have found that it is generated by "Display an Add to Cart message" rule from Drupal Rules. Everything would be fine but I can't find this text and I also don't know what to alter (and how) to change this message. Does anyone tried to do this?

There are several Options,

got to rules and disable the add to cart rule, then create your own.
Use this module https://drupal.org/project/stringoverrides to override the string. The string to override is this "%title added to your cart."

I wouldn't edit the module file commerce_cart.rules.inc -> function commerce_cart_rules_add_to_cart_message($product) as when you update it will just overwrite what you have done


Where do I store custom values/content? I'm creating a page "from scratch", with routing, controller, etc. The content of my page is created by code, buy I want to add a editable component (the description of the page).

I don't want to use blocks, because I don't wanto to give too many permissions to editor role.

I could create a "custom content" content type to store content and then add node content from code.

Other ways? I was thinking to use configurations, but if I export all configurations with "drush cex", this config will be overridden after editing. A good way could, if it's possibile, to exclude this single component from export.

Other ideas?

I am not sure about what is the question here. In general:

If you want to store content, create a ContentEntityType that extends ContentEntityBase. If you want to create a configuration, create a ConfigEntityType that extends ConfigEntityBase.

What you need sounds like a ContentType where you create your main content by code and have another Form to add/modify the content of a "page description" field in the ContentType. Maybe you can also use "Node" that could save a lot work.


Changing default domain in domain access causes 'access denied' for admin I'm using Drupal 7 with the Domain Access module version 7.x-311. I've successfully configured a bunch of subdomains running sites correctly, with one subdomain as default.

All worked well until I swapped out the default domain with a new one. Now, every login attempt for admin including  user 1 hits an 'access denied'.

I've updated the domain access settings to set the new domain as default. I've also ensured that the default domain is not set in the settings.php file, plus set the domain cookies settings reflects the top-level domain.

I've also cleared cache and cleared browser cache and cookies, still I get an access denied. I cannot work it out.

Has anyone got advice on where to look next?

N

Caching would be my first thought, make sure to clear cache (through drush since you can't log in). Also if you have any heavy caching like Varnish - clear that too. You may have an active session still in Drupal for the admin account, try removing that via - drush sql-query 'TRUNCATE TABLE sessions;'


How to display all terms for specific taxonomy in views incl. ones without content? How to set up a view that displays all terms for a specific taxonomy including the ones that have no content assigned?

I just can't figure it out to do it with a view:CONTENT and mainly found posts about hiding them.

In the results table, I also want to show a count of # nodes for each term (which I managed to do with Aggregation > Count).

I also tried creating as a View:TERM which does list all terms associated but then I can't display a count of nodes for it.

If the goal is to also show terms that have no content related to them, it doesn't make sense to start with the Content Views. How could you get terms information from non-existing relations? You could code a custom solution for that, logic that pulls out all terms and if no nodes are tagged display zero.

But there are ways to go forward with core Views.

Display node count on Terms nodes

Create Views of type Taxonomy term displaying terms for the Vocabulary you want
Add a Relationship Content using field_yourtaxreffield
You should already have the Taxonomy field, now add a new Field Title (or NID) and set it to use the Relationship from the previous step (to show nodes titles)
Turn Aggregation on
Edit the Aggregation settings on the Title field, change it to Count DISTINCT. Now you should be able to see the counts, next to all the terms from your chosen vocabulary, including the one with 0 nodes.
(Optional) you can Override the output of this field with custom text to place the count in brackets. The Text might be something like ({{ title }}), check under Replacement patterns

The problem here is extending this result to list node titles. Adding another content related field messes up the Aggregation results because it breaks them into separate rows and count becomes meaningless in that context.

I don't know if there is a clever way to solve it without an additional module. Maybe someone else can come in with the solution.

If using more modules is ok you can look into Views Field View (instructions on how to use it are in Readme file, you could create Embed display with your content and a term contextual filter, then embed it as the third field in the above Views), Views Aggregator Plus has more aggreagator options, Views Distinct (D7 only, might be used to create a new view with its "Aggregate Repeats" and then use regular Aggregation on it).


Force Creation of New Node With hook_feeds_presave Rather Than Node Update I want to have very specific control over the node update process for Feeds. Using hook_feeds_presave() I can stop a node from being updated with $entity->feeds_item->skip = TRUE; but how can I force a new node to be created.

If a node would otherwise update an existing node I want it to create a new node.

This is for Drupal 7.

Thanks!

You can make use of Entity::isNew function to check if the entity is new, and skip the setting of skip to true:

  if(!$entity::isNew()){
    $entity->feeds_item->skip = TRUE;
  }


Adding custom variable to twig's html.html.twig which is not cachable In the html.html.twig file of the theme I'm using, I want to add a custom variable called {{ amount }}
like:
Amount of items in cart: {{ amount }}

And I want it to be (in php): count($_SESSION['cart']).

If I add this to my custom module's hook_preprocess(_html) function:

$variables['cart'] = count($_SESSION['cart']);

Then it will work when I clear the cache, and then it will remember the value. So let's say there are 3 items in cart (variable $_SESSION['cart']), then it shows 3. If I then add one more, then next time I refresh the page, it shows 3 again, but it should say 4!!
If I clear the cache, then it says 4! How can I make it "dynamic" without clearing the cache all the time.

Ok - so to write your own extension see this answer, refeer to the twig tweak module. Or follow this article, that's it's content adapted to session (using a funcition) - like twig tweak, but different form the linked answer:

In this exemple, we built an extension du display a Drupal block directly from a twig template :

{{ session_var('my_var_name') }}

To to it, you must create a custom Drupal module. You can use the Drupal console to easily create your module.

In your module folder, frist create a new class in in a src subfolder :

For exemple : src/MyTwigExtension.php

<?php
namespace Drupal\MyTwigModule;

/**
 * Class DefaultService.
 *
 * @package Drupal\MyTwigModule
 */
class MyTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   * This function must return the name of the extension. It must be unique.
   */
  public function getName() {
    return 'session_var';
  }

  /**
   * In this function we can declare the extension function
   */
  public function getFunctions() {
    return array(
      new \Twig_SimpleFunction('session_var',
        array($this, 'session_var'),
        array('is_safe' => array('html')
      )),
  }

  public function session_var($key) {
    return \Session->get($key);
  }

}

In a second time you must register your extension as service :

Create a service configuration file

# src/MyTwigModule.services.yml
services:
  MyTwigModule.twig.MyTwigExtension:
    class: Drupal\MyTwigModule\MyTwigExtension
    tags:
      - { name: twig.extension }

And you are done :-)

You can now enable your module and use your Twig extension.

The simple workaround could look like this in twig:

{% app.session.get('cart')|length %}


Send "Request new password" email for individual users I'm looking for a way for the administrator users to quickly send out a password reset for a specific user. Ideally, this would be a link/check on the account edit.

I have seen and made use of the Mass Password Reset module which works per role, but I need it for individuals too.

At the moment my thought is to make a "reset password" role then have a rule along the lines of: after saving user, if user has "reset password" role, send account recovery email, remove "reset password" role, but that seems pretty convoluted. Am I missing an easy solution?

I am using Drupal 7.

If you'd create an appropriate view (using Views) of your users, wit whatever filter criteria you'd want, you could use that view to combine it with the Rules Link module. And with that you have the full power of the Rules module available also to implement whatever logic you'd want.

Refer to the accepted answer to "How to show authorized users a link for relevant Views results using the Rules Link module?" for an in depth explanation about using the Rules Link module, related to a scenario which is a variation of your question here (i.e. show a link to unblock blocked users).


Drupal workbench for each department I'm new to drupal and would like to build a workflow with the below functionality.

I'm able to create extra states through workbench module.

But the above workflow needs to be applied for each department in the company. ex:- Library services, Finance, Tourism. Therefore each department has different content authors and department managers, but the Marketing team will be the same for the entire company.

I'm guessing there should be a way to specify the department from a dropdown menu or something (with the help of taxonomy) so that when a new node is created from a specific content type, the content creator can specify the department which it should be forwarded to.

Can anyone please tell me how I should create this through workbench?

Thanks in advance!

You use Workbench Access and a Roles per department and 1 Marketing Role to make this happen.

  Workbench Access creates editorial access controls based on
  hierarchies. It is an extensible system that supports structures
  created by other Drupal modules.

  When creating and editing content, users will be asked to place the
  content in an editorial section. Other users within that section or
  its parents will be able to edit the content. A user may be granted
  editorial rights to a section specific to his account or by his
  assigned role on the site.

So you place Finance Editors (a role) users in the finance section, and Finance Manager(s) in the finance section. And the Marketing role is assigned to the root level section (which implies all subsections -- and secretly adds that role to each section).

So prior to using the site you would have to assign each user into sections of the site, which Workbench has an Administration page for.

Workbench Access provides 2 means to define sections out of the box. A section can be a menu path, or Taxonomy terms. Additionally you can create your own section logic using the supplied API functions of the workbench suite.

Be aware that Workbench only works on Node based content (unless this has since changed since I last checked). So for instance you cannot create Messages and moderate them, messages are (custom) Entities.

EDIT:

I suggest seeing the official linked Documentation of Workbench Access and reading all the info and further 3rd party videos/documentation on that page.


How to load a view with ajax so that additional js/css files needed by the view are also loaded? Currently I'm using jQuery to load a view, like this:

$.ajax({
    type: 'POST',
    url: Drupal.settings.basePath + 'views/ajax',
    dataType: 'json',
    data: 'view_name=' + viewName + '&view_display_id=default&view_args=' + viewArgument, // Pass a key/value pair.
    success: function(data) {
      var viewHtml = data[1].data;
      target.children().fadeOut(300, function() {
        target.html(viewHtml);

        var newHeightOfTarget = target.children().height();

        target.children().hide();

        target.animate({
          height: newHeightOfTarget
        }, 150);

        target.children().delay(150).fadeIn(300);

        Drupal.attachBehaviors(target);
      });
    },
    error: function(data) {
      target.html('An error occured!');
    }
  });

My problem is, that for example if the view uses the 'Field Slideshow' module, the js/css files needed for it to work properly are not loaded. What could be a nice (= kittens unharmed) solution to this?

Hmm, I feel like this question deserves a bigger bounty :-p but none the less here's my attempt at answering this.

Drupal already loads any extra css/js now I can't really find much documentation on it and sadly the JS files aren't easily documented without actually reading through the code but is there.

You really should try to avoid making $.ajax request yourself and instead wrapping everything with Drupal.ajax also if you use the Ajax System you don't even need to write the ajax request your self.

By implementing a proper Drupal ajax request using ajax commands most of the css/js handling will be done for you automatically.

By looking at your above code it looks like you you're making the same request views would normally do it self. So you should probably let views handled the ajax request and overwrite the ajax commands thats going to be fired to be your command. You can do this by either implementing a hook_ajax_comamnd_alter but it kinda sucks with views because you loose all contextual information so I would recommend using hook_views_ajax_data_alter instead.

I know there's not much code in my answer, but it's hard to answer with code, being that the code currently there is not correct to being with.

For more information see Drupal.ajax in the misc/ajax.js file. For an example of implementing an ajax request with Drupal.ajax see the views ajax file. And if you want to see and example of views normal behavior being overwritten by changing the ajax commands see the views_load_more module where I do this behavior.

Also please feel free to comment on this answer, if anything here is unclear.

On and for more info on the Ajax Framework see Ajax Framework for example see the example module, even thought most of what you want to do is not cover in the examples module.


Is there a way to show a node's comments when displayed in teaser format on the taxonomy term page? Is there a way to show the first page of a node's comments when the node is displayed in teaser format, e.g. on the taxonomy term page? I am building a site with 'posts' (a node type) which have comments, but I want users to be able to read comments, and leave comments from the taxonomy term page.

Is there a way to do this programmatically?

Associate a custom node to each taxonomy term.

Create a content type of "taxonomy term page" with comments enabled.
Add a custom field of type "taxonomy term".
Create a View, with a display of type block. Add to it a contextual argument of type taxonomy, and specify from where in the URL path is the argument going to be found. This should filter out nodes based on the current taxonomy found in the URL path. For safety, add a content type filter (regular, non-contextual), and specify "taxonomy term page".
Change the render type from "fields" to "node", or something like that. Try to see if in the node display option, you can choose to render comments as well.
Using Context, add a condition for taxonomy/term/* paths.
In the same Context, add a reaction of type block. Browse and select your block. Add it to the desired region. Save.
...
Success!

I tried to suggest the "easiest" option, which was using Views. If however for some reason Views won't allow you to render a full node view - with comments enabled - then you will need to create your block programatically using hook node view. But you still get the idea. The purpose is to take advantage of the existing comment-to-node architecture to avoid writing custom code as much as possible.


How do I send email to a large number of Drupal users, based on rules? I have a scheduled rule (schedule, rules module) to send a HTML email (mime module), using a View to list the email addresses (View Rules).

I tested this based on a couple of users (all users within my site's database) and everything worked as expected. When I increased the number of emails (to around 1400), I found that around half the users received the email, over and over again.

I also noticed that when I manually run CRON, the page times out.

I can't see any errors logged, but these may have been cleared.

Could anyone explain why this is occurring? I'm confident that everything was working before the increase in user numbers.

If a CRON task times out / errors, does it repeat on every page hit until it is successful ?

The Mandrill module (combined with the Mandrill service) lets you send transactional emails (and, theoretically, bulk emails) very quickly. It has a built-in queue feature which adds outgoing emails to a cron queue.

Note that the Mandrill service requires you to build up a reasonable sender reputation before you can send many emails at the same time - there are hourly limits that increase automatically. And of course it can cost money.

The Queue Mail module is a general-purpose solution to queue outgoing emails, if you don't want to run Mandrill or other modules that have their own queueing.

Regarding cron: Drupal's built-in cron triggers all repeating tasks to run at once, which means it can be very slow for complex sites. Many cron tasks don't need to run that often, and many of them shouldn't run often (for example, the system cron clears caches, which can really slow down the site).

So you can use the Elysia Cron module to manage cron jobs more effectively: it allows you to separate tasks so that the ones that are fast and need to be frequent (such as Mandrill cron) run say every minute, while the ones that are slow (such as system cron) run every week.

The Ultimate Cron module is an alternative to Elysia Cron - I haven't used it recently so I'm not certain that it works well.


Fatal error: Call to undefined function node_type_get_names() Drupal 7.59 I upgraded my Drupal site to Drupal 7.59 and now the site is down.

Fatal error: Call to undefined function node_type_get_names() in D:\Development\xampp\htdocs\biobank\modules\comment\comment.module on line 119

List of installed modules:

admin_menu
autocomplete_deluxe
autologout
better_exposed_filters
bootstrap_fieldgroup
chosen
conditional_fields
ctools
date
devel
empty_front_page
entity
entityreference
entityreference_autocreate
exclude_node_title
field_collection
field_collection_table
field_collection_views
field_group
field_validation
jquery_update
mass_pwreset
module_filter
msnf
restrict_ip
securelogin
security_review
termcase
title
token
unique_field
vefl
views
views_bootstrap
views_data_export
webform

Can't comment but I don't see the Node module. Its part of the core and should be present(thats where the missing function is defined). Verify that the module is present and permissions are set right


CPU spikes enabling / disabling modules when site is under load We are in the process of migrating our website to Drupal 7 and we had a failed launch this past week. We performed load testing and were certain that our server was going to work just fine with our current load, unfortunately we did not perform load testing with logged-in users (we use a 3rd party gateway login system and it was almost impossible to accomplish a load test this way).
Long story short - logged in users overloaded our site and the server crashed.

So we've gone back to the drawing board, implemented APC and Memcache and we believe we have the problem fixed. The CPU no longer maxes out when under an expected load.

However, we now have a new issue that is a critical showstopper if we cannot find a fix for it.

While the server is under load from users, if an administrator attempts to enable or disable a module, ANY MODULE, (and sometimes even if we attempt to VIEW the modules page), the CPU will max out and the server will then eventually crash. The only option at that point is to restart the httpd service, which of course disrupts all user traffic.

When operating normally, CPU usage is at about 20 - 30%. When you attempt to enable or disable a module, the server IMMEDIATELY pegs the CPU at 100% and becomes nearly unresponsive from the browser and command line. Our normal page load times are 400ms, and they skyrocket to over a minute until the server crashes.

With no user load, the server operates as expected, though the action of enabling / disabling a module does spike the CPU for a short period of time. I have checked the sql slow query log and haven't found anything enlightening there. HTTPD is not spitting out any errors either.

Server has 2 CPU, 16GB memory and is dedicated to running this site alone; surely it isn't under powered.

What could possibly be causing this problem?

If you look at the source for module_enable() you can see what is going on.  In particular, several cache tables get cleared, as does the registry.  It also does filesystem scanning to rebuild module data.  All of these are expensive operations.

If you look at the source for system_modules() (this is the callback for the modules page), you will  see that system_rebuild_module_data() is called.  This is also an expensive operation.

My guess is that something on your server isn't optimized.  Even though you have gobs of CPU and RAM, Apache and MySQL may need tuning.  I have seen similar instances to yours, where MySQL hangs due to heavy loads and then incoming HTTP requests stack up.  Eventually, connections to the database will block, and slow things down more.  When this happens, the system will very often hit swap due to the number of httpd processes.  A live webserver hitting swap is a catastrophe; load/memory will swell exponentially.

In this case, you need do a few things.

First, run mysqltuner on your database, and make sure buffer sizes are OK, and that your max memory usage is sane.

Then, tune Apache to make sure you won't ever hit swap under normal conditions by limiting the number of concurrent servers.  Enabling keepalives, and setting up some aggressive HTTP cache rules can also help reduce the number of active httpd processes.  Using the CDN module can also help reduce Apache load by offloading most CSS, JS, and image requests to the CDN instead of your server.

It is also possible that your memcache doesn't have enough memory, and you are thrashing.  You may need to check these settings, and also check which tables you are offloading.

I would also avoid enabling/disabling modules outside of maintenance mode.  Schedule windows where you can do work.  Assuming you stage/test everything properly, and work from a checklist, you shouldn't have more than 5-10 min downtime to do this.


Access variables populated in one page function for a different page function? Always null I have a module that creates a simple page. However in the page I want to link to iframes that I will generate in the module code.

Currently I have two hook_menu items: one for the simple page (no arguments), one for the iframe pages (with arguments).

However when I show the iframe, I need to get some values from a global variable that is populated from the simple page function but when I reference it in my function for the pages with arguments the variables are always null. I assume this is because drupal re-loads the .module page but skips running the simple page function when it loads the page with arguments, thus it doesn't populate the variables when it loads the iframe.

How could I populate my iframe with the variables from my simple page? Is there an easier way than what I'm doing? Can I do it without global?

Does that make sense?

function my_custom_page() {} for:
    drupal/my-custom-page-module

function my_iframe($id) {} for:
    drupal/my-custom-page-iframe/0

Code for drupal/my-custom-page-iframe/0 needs to get variables that were generated in function my_custom_page() {} when it runs the my_iframe($id) for the page callback.

I have defined the variables outside functions as global and included global var_name in both functions but it still doesn't work.

Also, the iframe should not have any Drupal theme/sidebar content: for this I'm just echo'ing my code and then return: within my_iframe{$id}.

What I was thinking was instead of using two functions with page callback, was to just use GET request for my 'iframes' like ?iframe={$id}. Does that sound like a better direction to go?

First off, Drupal is bootstrapped every time a new page is requested. Even if both the pages  would be using the same menu callback, the global variables would be reset when passing from a page to the other one.

What you can do is using session variables, passing variables through the URL, or using a cache.
Passing variables through the URL would not use for complex variables, as there is a limit to the URL length accepted from browsers; using a cache would be a solution if the cached data should be available to more than one user, such as to user having the same rule; using session variables is the easier solution when the data to share are only for the currently logged-in users.

As for using the same callback, there is an example given in the hook_menu() documentation.

  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

The menu callback would be used for http://example.com/abc/def, http://example.com/abc/def/222, and http://example.com/abc/def/333/aaaa. In the first case, $ghi and $jkl would get their default value; in the second case, only $ikl would get its default value; in the last case, none of the variables would get their default values.

That is true also for the form builder, with the exception that the first two arguments would be $form, and &$form_state.


Where to put a personnalized copy of a layout from layout_discovery? I want to personnalised core/modules/layout_discovery/layouts/twocol/layout--twocol making a copy of it renamed with a suggested name in the display mode but I don't know where to put it in my subtheme of Bootstrap... I've tried different places, but none worked...

Any help will be appreciated.

Drupal 8.4.3.

I putted my layout in drupal\themes\mytheme\layouts\twocol\layout--twocol--node-end-of-a-suggested-name.html.twig and declare it in a mytheme.layouts.yml file at the root of my theme and it worked.


Is there a way to insert a view in a node form? I have created a content-type based form (contact form) for anonymous users.
One of the fields in the form must displays a view.
This view is a slideshow view that displays different persons (site employees).

I want them to select an employee to where their comments will be delivered.

Found it i can use Markup module to use php code in the field and use this code;

WHATEVER is the name of your view.


how do I organize the input fields in fieldset? I have a node form in Drupal 7, in order to simplify it for the user I want to break it up into sections using the vertical tabs feature.

Using hook_form_FORMID_alter() I can move the fields with difficulty.tha following is my code.:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {
    $form['cpmonth'] = array(
      '#type' => 'fieldset',
      '#title' => t('test'),
      '#weight' => 5,
      '#collapsible' => TRUE,
    );
$form['cpmonth']['field-14sq']=array();
$form['cpmonth']['field-510sq']=array();

  }

}

"field-14sq" and "field-510sq" are my input text fields. Do you have any idea?

If I understand correctly you want to move existing form elements into the fieldset you created.  Try this, I'm assuming the fields you want to move are $form['field-14sq'] and $form['field-510sq']

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {
    $form['cpmonth'] = array(
      '#type' => 'fieldset',
      '#title' => t('test'),
      '#weight' => 5,
      '#collapsible' => TRUE,
    );
    $form['cpmonth']['field-14sq'] = $form['field-14sq'];
    unset($form['field-14sq']);
    $form['cpmonth']['field-510sq'] = $form['field-510sq'];
    unset($form['field-510sq']);
  }
}

If you have custom submit and validation functions this shouldn't affect them, since fields in fieldsets still come back in the root level of $form_state['values'] .