How can I change the way content titles are generate and displayed? I'm a total amateur working on the website for my community radio station via Drupal 7. (Here for reference) Each show on the station has their own content type called a Program Page, which displays, at the bottom of the page all the Program Playlists (a type of content) they have created by clicking a link on the Program Page and filling out the 'Create Program Playlist' form (http://www.cjsf.ca/node/add/station-playlist/685).

Currently these playlists are listed by an automatically-generated title that is just the date the episode aired (a field within the 'Create A Program Playlist' form), and we'd like to be able to assign custom titles to these playlists.

I can't for the life of me figure out how to do this. I've tried editing the content type for the Program Playlist but all I have there is an un-editable 'Title' field and I can't get much further than that.

Help!

If the title field is uneditable, that might have been done through another module or custom code (Automatic Entity Label?) that is setting the title text. I would edit the content type, and look down at the bottom and see if there are any content type settings that would be determining the title (not the "manage fields" page, but the main edit page for the content type). You might be able to re-enable editing.
https://www.sierraclub.org/admin/structure/types/manage/station_playlist (? not sure if this link is exactly right, a guess...)

A work around would be to add a custom field that is your custom title, and then edit your view(s) to use the custom title if it exists. (The short version of how to do that would be to make the regular title hidden, and then add the new field, and use the if empty setting to populate with the text from the title.)

But figuring out how the title field is made uneditable and fixing it from there would probably be best in the long run.


Is there any way to redirect page to front page, if it isn't translated? Is there any way to redirect page to homepage if its translated page not found.

Suppose my page url is /en/node/237, If I switch translation from English to German /ge/node/237, if it's translated page not found, URL should redirect to homepage of its native language like: /ge/home

Here is my code:

 use \Drupal\node\Entity\Node;

   $elements = [];
 $ids = \Drupal::entityQuery('node')
  ->condition('type', 'intro_2')
  ->condition('langcode', 'fr')
  ->condition('nid',1218)
  ->execute();

 $nodes = Node::loadMultiple($ids);
  $language = 'fr';

 foreach ($nodes as $node) {
 $translation = $node->getTranslation($language);
$elements[] = [
 'node' =>$translation->nid->value,
'title' => $translation->title->value,
'url' => $translation->url(),
];
  }
dpm($elements);

Above code working fine i have checked on /devel/php,but i am having only following issues:

1)How to get current page node type dynamically in database query

2)How to get current page language dynamically in database query

3)How to get current page node dynamically in database query

Can anyone modify the above code?

To get current node:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
  $node_type = $node->getType();
}

Current language:

$language = \Drupal::languageManager()->getCurrentLanguage();
$langcode = $language->getId();
$language_name = $language->getName();

Check if translation is not available and redirect:

use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

$translation = $node->getTranslation($langcode);
if (!$translation) {
  $url = Url::fromRoute('<front>', [], ['language' => $language]);
  $response = new RedirectResponse($url->toString());
  $response->send();
}

P.S.: I believe entity query you posted is a simplified version of smth more complex in your logic. Otherwise I see no reason to pass node id to entity query condition to get it back eventually. If you always have just one node use Node::load($id) instead of Node::loadMultiple($ids), and you don't need foreach in this case.


Do exposed filters work in Views 7.x-3.3? When I create a filter, check the expose filter box, click save, then open the filter up again the exposed filter checkbox is uncheked...

I noticed when clicking save the filter is called: "Content: Assessment (or Unknown) | Settings" instead of "Content: Assessment (exposed) | Settings"

Anybody know what's going on here? I've tried creating an entirely new view and the same thing happens.

The field I am exposing is a simple taxonomy list.

I created a short video showing the issue:
http://www2.intensiveintervention.org/views_issue/

I found a thread on a seemingly related issue: http://drupal.org/node/1343482 but this did not solve my problem.

Downgrading views to 7.x-3.1 did not have any effect.

Okay I figured out the problem.

There is, as of today, incompatibility between Views and Theme Developer. If I disable Theme Developer views acts normally.

FYI for everybody else having this problem!


How to include RSS feeds inside a node? I would like to create a node that displays 5 RSS feeds from 5 different external sites. I have the RSS URL of the external sites, and I would like to find a simple way to display the last elements of these feeds inside my node.

I have already looked at the Feeds module, but it creates a node for each element of the given RSS feeds.
How can I display the last elements from different RSS feeds?

I think the best way is to use Aggregator, you dont have to map into a new content type RSS Feeds like on Feeds module.

Follow this:

Active Aggregator core module.
Add a new chanel per each feed URL under /admin/config/services/aggregator, defining a name and time for importing by cron.
Create a view with a display of type "Aggreator", Here you can make a comun view, ordering by date, limiting by 1 result, and filtering by each channel.

I hope this help.


Change entity bundle on update? Is it safe to change the entity bundle (e.g. node type or commerce product type) when updating an entity with Migrate API?

Specific use case:

The site already contains plenty of commerce_product entities with $product->type === 'product', that were imported with something other than Migrate API.

I now want to re-import these entities with Migrate API, updating the existing entities.
Custom MigrateMap to sync by field or property, e.g. SKU

The product type should be changed to something else by the update, let's say $product->type === 'othertype'.

Some of the fields are the same in both bundles. Other fields only exist in one of the bundles. Data from obsolete fields should be discarded / deleted. This includes images from an image field.

So, I wonder if all of this will happen painlessly, or if I need to do something special to make it work.

I will try this anyway and see what happens, but I think it is useful to have this documented here on stackexchange.

That seems dangerous to me - a node's bundle is fundamental to its identity, and has repercussions well beyond the node's data itself. You're on Drupal 7, presumably? Simple way to test would be a script like:

$node = node_load(5);
$node->type = 'other_type';
node_save($node);

If it breaks there, it'll break with migration too. And if it works there, it should work with migration.


Is there a simple way to add user access on a page level? I'm still getting used to the way Drupal works, most of what I have read on adding User Level Security on a Drupal site seems to be either View based or by using a Module like Panels.  I am creating a site that is rather simple in structure, with some high level pages that differentiate out the content to different areas.  I am using Superfish to generate a drop down menu system at the high level, and underneath I have some content areas that will either contain only a few pages or one specific area that will have many.  I am also using shortened URLs to make site structure easier to manage, although in general it comes across as flat.  I may be wrong in thinking in terms of pages, and if I need to reconsider that for the site that's ok, I have only been using Drupal for the past 6 months but its a good fit as a CMS for the site I am working on.

The requirement is only for three types of Users - Admin, Group Leaders, and Members.  I'd like to give Group Leaders some access to pages for editing permissions, although mostly only at a second level or specific pages.  Members will have some editing rights but only on a few pages.  Group Leaders and Members will have access to content in one specific area, where I will have many pages, no one else should be able to get in.  Content pages on Member activities will be accessible by only those who have a login, those not logged in should ideally not see the links or not be able to access the pages.

With Drupal 7, and using the Bartik theme and some modules (Chaos Tools, Display Suite and Superfish for now) what is the best mechanism to be able to grant permissions to view and access content on only specific pages in the structure I have?  The site is still new, so if I have to make changes I'd like to do so now before it gets too complex.

Update:
Just to note in addition what happened.  I was looking for some sort of access that was simple to add in and allow me control on an individual node.  Content Access module gave me this in a way I can teach my Users to utilize.  Sorry if it seems a duplicate, I was looking for more of a description on what the modules did than I had seen before.

Well when you say page in drupal, it comes down to a lot of options. it might be a views page, a panels page, a page created directly with hook_menu().

So options:

If its a panels/views page, you already have permissions options there through UI in those cases.
Node and taxonomy term pages, have contrib modules that does this..Ankit's answer above lists out some.
If the page is a custom page defined bu hook_menu, you can employ '#access_callback' parameter to add a permissions function where you can return TRUE of FALSE based on check.

After restricting access to each page based on roles, these will be respected already when you add their links to the superfish menu.


how to get a list of all nodes that haven been created and are not in use on the system as the title says..
i need to get a all published nodes of type A that have been created and not used (at the moment) by other nodes.

in other words a list of all node of type A that are on the Database except for those that are NOT been referenced in an entity reference field.

the easy approach will be to load all nodes that uses node of type A, and that load all type A nodes and check for each if it's has a reference for it.
but then if i add another node that will use node of type A as an entity reference i'll have to go back check it as well.

is there an easy way to do it ?

You could set up a view showing title of content type A,  title of content type B (using relations), hide both and create a custom PHP field that just returns title of ct A if ct A does not have ct B referencing to it. Maybe


Getting arguments from URL How do I get arguments from the URL? in other words, what is the equivalent of the arg() function of Drupal 7 and previous versions?

As reported in the arg() is deprecated and will be removed change record, the Drupal 8 (procedural) equivalent of arg() is the following one.

$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

As the change record makes notice, not all the times that is the correct code to use. Depending from the context, you should use code similar to the following one.

Check if a path is for an administrative page

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  // Your code.
}

Add CSS or JavaScript conditionally, basing on the page being visited

function mymodule_page_attachments(array &$attachments) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $attachments ['#attached']['library'][] = 'my_module/my_library'; // you'll need to define in mymodule.libraries.yml
  }
}

Load the currently viewed node

$node = \Drupal::routeMatch()->getParameter('node');

Notice that in the first and last case, in Drupal 7 you should not use arg(), but respectively path_is_admin() and menu_get_object(). The typical beginner-Drupal-developer error is using arg() also in those cases.


Is there a hook function for a module's settings form being submitted? I am maintaining a cache of data in my module using $_SESSION, which gets rebuilt after an amount of time has passed.  This works fine, but I now need the cache (session object) to be cleared when the user submits a change to the module settings.

Is there a hook I can implement that will be called on form submission?  I have already implemented mymodule_form_validate, but this doesn't feel like the right place for it, I would prefer a hook that fires only when validation is successful.

I have tried checking for the rebuild flag in mymodule_form, but that doesn't seem to work:

function mymodule_form($form, &$form_state) {
    if($form_state['rebuild'] === true) unset($_SESSION['mymodule_cache']);
    //form elements and stuff...
}

Update

Trying to follow marcvangend's answer, but I'm struggling.  I've implemented hook_form_FORM_ID_alter:

function mymodule_form_mymodule_form_alter(&$form, &$form_state, $form_id) {
    echo $form_id.'<br>';  // mymodule_form
    $form['#submit'][] = 'mymodule_form_submit';
}

and this seems to work, in so much as the form id traces out as expected.  The trace in my submit function never seems to appear and the session object is unchanged, although the form values do submit:

function mymodule_form_submit($form, &$form_state) {
    echo 'form submit';
    $_SESSION['mymodule_cache'] = array();
}

You can implement hook_form_alter or hook_form_FORM_ID_alter and add a custom submit handler to the form in which you can clear the session data. It would look something like this:

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "some_form") {
    $form['#submit'][] = 'mymodule_some_form_submit';
  }
}

function mymodule_some_form_submit($form, &$form_state){
  // Do your fancy stuff here.
}
?>

This example implements hook_form_alter. If you only have one form to alter, I recommend using hook_form_FORM_ID_alter because it results in cleaner code.


Join variables in twig I want to join two variables in twig in the user.html.twig

{{ content.field_firstname }} {{ content.field_lastname }}

How can i output them on the same line and add a space between them using twig ?

Everytime i try, they show on two different lines ? and i don't want to use css just for this.

Is there any better way to do this ? Many thanks

{% set full_name = [content.field_firstname ~ ' ' ~ content.field_lastname] %}

Note: We use ~ in twig to concatenate two or more strings instead of "+"


How can I use these modules together? Is it possible to use Mimemail, Mail System, and SMTP Authentication Support modules together?
Currently I am using Mimemail to send HTML-formatted messages; however, because of the configuration of my server, these e-mails are often being recognized as spam.  To reduce the chance that they will be recognized as spam, I want to use the SMTP Authentication Support module.

Yes. We can use the Mimemail + SMTP Authentication Support. Plz check the link http://drupal.org/node/1200142 and check the part : Alternative Approach: Mail System + SMTP + Mime Mail


How to add padding/margin for sidebar-right in Adaptive Theme? I am trying to make something with Adaptive Theme, but I can't find how to set a padding or margin to Right Sidebar...

I am using only content -- right sidebar  layout, and if I wish to add some padding for Right Sidebar - it just disappears and falls down to bottom of page.....

Also, the problem started when I wanted to remove any Margin for a Content area, which was set to 10 px; but - when I removed margin for Content, it disappeared from Sidebar; and if I try to add margin/padding to Sidebar only, It just fall to bottom of page, probably resembling the tablet layout...

What Geoff said is basically true, but there is a way to change the margins and the paddings without messing up your basic page layout.

The way to do it is the following:

Take a look at the structure of the HTML in the sidebar region. There should be a div that has a class .region-sidebar-second or .region-sidebar-first. If you try to change the padding/margin of this div, your structure will be messed up.
You can, however, change the margin and padding of the div with the region-inner class by using a selector like ".region-sidebar-first .region-inner" or ".region-sidebar-second .region-inner".
You can even go deeper if you want to change the margin/padding of a specific block and not the whole region's by using something like ".region-sidebar-second #blockID" as your css selector.


Only show the complete form at the end of the quiz In the Quiz module, After each question that the user answers, it shows a page that have some information (such as: right or wrong, question, answers, etc.).

And in the last of quiz it shows a complete form too.

I want to change this, so that the form is shown just at the end and not after each question. Is there a template I should change or some other way I can change the normal module behaviour?

I don't know enough about the Quiz module to say for sure but have you checked out the theme functions available for Quiz?

There is a theme function called theme_quiz_take_summary().
It has a form that it adds if the quiz is set to display_feedback. Maybe it's a setting for the quiz somewhere?

// Get the feedback for all questions. These are included here to provide maximum flexibility for themers
if ($quiz->display_feedback) {
  $form = drupal_get_form('quiz_report_form', $questions);
  $output .= drupal_render($form);
}

If you want to have your own version of that theme function you should place the whole function in your theme and replace theme_quiz_take_summary() with NAMEOFYOURTHEME_quiz_take_summary().


How can I modify the login form using hook_form_alter()? I'm trying to alter the login form with the following code:

function git_form_alter(&$form, $form_state, $form_id) {
  $forms = array(
    'user_login_block' => 'user-login-form',
    'user_login' => 'user-login'
  );
  if (array_key_exists($form_id, $forms)) {
       //my altering code
    }
}

I got this from the openidselector module that introduces some JavaScript widgets and more or less is what I'm trying to do.
When I go to mysite/user/login it doesn't call the block where I have to alter the form.
It simply doesn't call hook_form_alter().

A different thing is with the register form, or any other form, that are calling the hook.

Can anyone tell me what can I do? How is it possible that openidselector uses the same method, but in that module the code works, while it doesn't work in my code?

When I go to mysite/user/login it doesn't call the block where I have to alter the form. It simply doesn't call hook_form_alter().

example.com/user/login doesn't show the user login block; it shows the login form. Your code should work, even if I would rather make the code simpler (if you are not using "user-login-form" in any way).

function git_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    // …
  }
}

As for the reason why the code doesn't work, I can think of the following reasons:

The hook name doesn't match the short name used for the module; for example, the short name of the module is "git_form" and you are using git_form_alter() for the implementation of hook_form_alter() when it should be git_form_form_alter().
You are editing a module that is enabled. In this case, when you add a new hook to the code, you also need to flush the cache used by Drupal as Drupal caches the list of hooks implemented by third-party modules.
The module is not enabled.


Using a backup file to transfer a site to new directory I am working on a project on a sub-domain of my site that when it is ready I want to move it to my client's site. I was wondering if I can do this by creating a back-up file using 'Backup and Migrate' and installing Drupal on their site and loading this back-up file to move all my work there. Is this possible or is there a better way?

All the best!

This will depend a little on which version of Backup and Migrate you are using.

Older versions only backed up the database, so you would also need to copy over the public and private files to the new site, along with the rest of the code.

Newer versions can backup files, but I don't have any direct experience with doing this.  It advertises that it can do either the public files, or the entire site.

Just keep in mind that Backup and Migrate will by default exclude the data from certain tables, mainly the cache files, logs, and the search index.  Rebuilding the search index can be a very expensive (and lengthly) process on a big site.  This is configurable, though.

There are other options, too, such as drush.


How can I hide the taxonomy term icon? By default, taxonomy terms on a node display with a tag icon:

What's the easiest way to get rid of that icon? Just use hide($content['fieldname']); in my node template and rewrite it the way I want? Or is there a config option somewhere that I've missed that would let me turn it off?

I am almost sure it`s generated by your theme with css. So you can use firebug to find this line and delete background and padding of this element.


How to prevent people to ask for registration in Drupal 7? There is no login block in my website but everyday I see lot's of strange emails are sent they ask for registration. How do I can modify Drupal to reject every registration request?

Go to Configure > People > Account Settings (/admin/config/people/accounts) and set it so only Administrators can register accounts.


Where is htaccess located in Drupal 7? I'm looking for the .htaccess file that should be in the default installation of Drupal 7.

Normally it is supposed to be there. Does anyone know where it is located?

The file's called .htaccess and it's in the root of the Drupal installation. A lot of operating systems hide files that start with a ., so that might be way you can't find it.

If it's simply missing, just download a fresh copy of Drupal and copy the default .htaccess file from there.


Using drush to run a local script on a remote site I frequently use drush scr for little tasks throughout my day.  Sometimes these end up a proper commands in my environment, but more often they are just standalone things.

If I have @foo set up in my drush aliases with remote-host, and try to run a local script, I get

$ drush @foo scr ./foo.php
Unable to find any of the following:                                     [error]
/home/mpd/drush/commands/core/./foo.php, /home/mpd/./foo.php

Can this command run a local script on a remote site?

Nope, what you want to do is not supported.  When you run drush @foo scr, it causes Drush to run your scr command on the remote system.  The scr command on the remote system will then look for the script it wants to run on its own filesystem.  In order to make this work, you'll need to somehow get your script on the remote system, and then run it with your remote scr command.

Note that this is different than the drush php-eval command, which takes the php code to run on the commandline.  So, in theory, you could passing your php over on the commandline rather than in a file; however, in practice you may find this to be problematic due to the fact that bash is going to process your text, so you'll have to make sure that everything is properly escaped.  Moving the script to execute to the target machine will be more reliable for any nontrivial script.


Front-end on a different domain I'm using drupal8 in headless mode.
So I have a backend on Drupal8, and a frontend in JS.
I'd like to have content URLs in drupal8 to point to the frontend domain and not the backend (which doesn't have any templates to display the content).

backend.example.com/mycontent for Drupal8
www.example.com/mycontent for the frontend

How can I do to update all the links in UIs to have the frontend domain in place of the backend domain ? (views or admin/content or breadcrumb on edit form).

You can try using the Domain access module that does the work. Version 8.x works with not issues. Go ahead and use it with no fear.


How to remove href from last breadcrumb? I'm altering breadcrumbs using the theme_menu_breadcrumb_alter function and was wondering what can I do to make the last breadcrumb non-clickable (i.e. it should be just text, not a link).

I tried making the href value to an empty string but that just returns a link to the base URL.

How can I do this?

If anyone else is looking for this, here is one way to solve it:

In template.php add the following function

function theme_breadcrumb($variables){
    // get an array with all the breadcrumbs (and their html)
    $breadcrumb = $variables['breadcrumb'];

    // remove the html from the last one and put it into new variable
    $cur_page_brdcrmb = strip_tags(end($breadcrumb));

    //remove the last element from the original breadcrumb array
    array_pop($breadcrumb);

    // add our html free breadcrumb to the array
    $breadcrumb[] = $cur_page_brdcrmb;

    // build the output and return it
    $output = '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
}


How do you provide conditional checkout options depending on whats in the cart? Is it possible to provide different payment options depending on what is in the cart? Say someone wanted to purchase a service vs a physical product. For service related items, I want to be able to provide a payment option of Bitcoins and if its physical products, provide paypal. if they have a service and product in their cart it would only provide paypal as an option. Can this be done via rules and which rules would i need to edit?

I believe you have already set different product types to handle different kind of product.

So what you have to do is, by default disable payment methods and set them one by one in rules to make a payment option available if certain product type in in cart.

Add Event "Select available payment methods for an order"
Add Condition "Order contains products of particular product type"
Add Action "Enable payment method: (Your Payment Method)"

I have done something like this for COD(Cash on Delivery) for certain product type in certain postal codes.


Can I conditionally hide a route (e.g. action / local task) Consider an action button on a custom entity's canonical page:

mymodule.actions.yml:

entity.item.action:
  route_name: entity.item.action
  title: 'Do something'
  appears_on:
    - entity.item.canonical

mymodule.routing.yml:

entity.item.action:
  path: '/item/{item}/action'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ItemController::action'
    _title: 'Do something'
  requirements:
    _permission: 'edit items'

I would like to show or hide the action button depending on the value of some field of the entity.

How could I achieve this? Would it be wise to add custom access checking for this?

You can add a custom access method on your controller. According to this page you should have access to your item argument in the access method so you should be able to restrict access based on a value on that item. The action should be hidden if the user does not have access to the route, i.e. your custom access method denies access.


Assign taxonomy term to a view I would like to set a taxonomy for a view. I have Taxonomy called "CMS Templates" and under that I have "Drupal". I would like to set Drupal for a view which is displaying Drupal templates but I don't know how. I tried to put field taxonomy and all taxonomies but I don't have possibility to set it there.

You can easily output taxonomy term based information by going to admin/structure/views/add and under "Show" choose "Taxonomy terms".


hook_theme_suggestions_HOOK() doesn't work I am making a template in Drupal 8. At this moment, I made a theme in the /themes directory; there, I have my .theme file and a copy of the html.html.twig file from the core/themes/stable directory.

I have enabled Twig debugging mode and in the Chrome inspect tool I read the following.

<!-- FILE NAME SUGGESTIONS:
   * html--front.html.twig
   * html--.html.twig
   x html.html.twig
-->

I added the following hook to the theme file.

function testTheme_suggestions_html_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'html__testHTML';
}

After clearing the cache, there isn't any change to the file name suggestions.

Also I have activated kint() in html.html.twig file that is located in my theme root, but kint() also shows only these variables.

'theme_hook_suggestions' => array(2)
string(6) "html__"
string(11) "html__front"

Why doesn't the new suggestions appear?

Try it like this:

function yourthemename_theme_suggestions_html_alter(array &$suggestions, array $variables) {
  $suggestions[] = 'html__testHTML';
}

Replace "yourthemename" with your theme name.


Saving values of a multistep form into custom entity fields I'm building a module that implement a multistep form based on a custom entity.
The entity contains fields which are created by the install file.

I was able to create the steps and if I print the $form_state[storage] array in the last step I can see all the values entered all along the form.

But when I submit the last step the entity is empty.
This is what I have in the last_step_submit:

$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();
drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
$form_state['redirect'] = 'admin/organisations';

I know that I'm missing something but really I can't figure out what.
I'm quite new in module developing and I'd appreciate any help.

After struggling for a couple of days I finally was able to store the values in the entity.

The first mistake was that I forgot to pass my entity ('organisation') as an argument in the primary hook_form:

  // Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;

The second was that I had to build and save my entity each step with the code I attached in this question.

$organisation = entity_ui_form_submit_build_entity('organisation',$organisation, $form, $form_state);
$organisation->save();

Now I have my custom entity with custom fields and a multistep conditional adding form!

This is the code if someone else need the same functionality.
Primary form and submission functions:

function organisation_form($form, &$form_state, $organisation) {
  if ($form_state['rebuild']) {
      $form_state['input'] = array();
  }
  if (empty($form_state['storage'])) {
// No step has been set so start with the first.
   $form_state['storage'] = array(
      'step' => 'organisation_first_form',
   );
  }
// Return the current form
  $function = $form_state['storage']['step'];
  $form = $function($form, $form_state, $organisation);
  return $form;
}

function organisation_form_submit($form, &$form_state) {
 $values = $form_state['values'];
 if (isset($values['back']) && $values['op'] == $values['back']) {
   // Moving back in form.
   $step = $form_state['storage']['step'];
   // Call current step submit handler if it exists to unset step form data.
   if (function_exists($step . '_submit')) {
     $function = $step . '_submit';
     $function($form, $form_state);
   }
// Remove the last saved step so we use it next.
$last_step = array_pop($form_state['storage']['steps']);
$form_state['storage']['step'] = $last_step;
  }
  else {
   // Record step.
   $step = $form_state['storage']['step'];
   $form_state['storage']['steps'][] = $step;
   // Call step submit handler if it exists.
   if (function_exists($step . '_submit')) {
      $function = $step . '_submit';
      $function($form, $form_state);
   }
  }
return;
}

This is one of the steps and its submission function.

function organisation_second_form($form, $form_state, $organisation) {
  $form['#parents'] = array();
  // These variables are needed to build field forms.
  $entity_type = 'organisation'; // Substitute with any entity type.
  $bundle_name = 'organisation'; // Substitute with the entity's bundle.
  $entity = $organisation;
  $langcode = LANGUAGE_NONE; // Substitute as appropriate.

  $field_name = 'hub_position_activities';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $field_name = 'hub_market';
  $items = field_get_items($entity_type, $entity, $field_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $field_form = field_default_form($entity_type, $entity, $field, $instance, $langcode, $items, $form, $form_state);
  $form += $field_form;

  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('Back'),
    '#limit_validation_errors' => array(),
    '#submit' => array('organisation_second_form_submit'),
    '#weight' => 499,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Next'),
    '#weight' => 500,
  );
  return $form;
}

function organisation_second_form_submit($form, &$form_state) {
  $values = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  if (isset($values['back']) && $values['op'] == $values['back']) {
    $input = $form_state['input'];
    // The user clicked the back button, save values that were input
    if (isset($input['hub_position_activities'])) {
      $form_state['storage']['hub_position_activities'] = $input['hub_position_activities'];
    }
    if (isset($input['hub_market'])) {
      $form_state['storage']['hub_market'] = $input['hub_market'];
    }
    $form_state['storage']['step'] = 'organisation_first_form';
  }
  else {
    $form_state['storage']['hub_position_activities'] = $values['hub_position_activities'];
    $form_state['storage']['hub_market'] = $values['hub_market'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    $form_state['storage']['step'] = 'organisation_third_form';
  }
}

And the last submission function.

function organisation_last_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  if (isset($values['back']) && $values['op'] == $values['back']) {
    $form_state['storage']['step'] = 'organisation_second_form';
    $form_state['rebuild'] = TRUE;
  }
  else {
    $form_state['storage']['hub_equipment_measurement'] = $values['hub_equipment_measurement'];
    $form_state['storage']['hub_equipment_software'] = $values['hub_equipment_software'];
    $organisation = entity_ui_form_submit_build_entity($form, $form_state);
    $organisation->save();
    drupal_set_message(t('The organisation: @name has been saved.', array('@name' => $organisation->name)));
    $form_state['redirect'] = 'admin/organisations';
  }
}

Perhaps there were easier way to achieve this goal but, so far, is the only one that worked for me. If anyone has better solutions I'm eager to know them.

Thanks to Alex Weber for his great tutorial on how to get the form for existent fields http://www.alexweber.com.br/en/articles/how-manually-add-entity-field-forms-custom-drupal-form and to Bryan Jones for his Multi-step form tutorial http://bryanjones.us/article/custom-multi-step-forms-drupal-7


Printing fields in theme: Undefined index: safe_value I want to print my fields in tpl.php files as cleanly as possible. To do this, I have used the following code in my template.php file:

function print_field($field_name, $format = 'safe_value') {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

$field= field_get_items('node', $node, $field_name);

if ($format == 'url') {
    print file_create_url($field[0]['uri']);
} else {
print $field[0]["$format"];
}
}

Now, I can print my fields in my tpl.php file in a clean manner, without any unnecessary mark-up or labels:

<?php print_field('field_section') ?> -- Prints the field with safe formating

<?php print_field('field_title', 'value') ?>  -- Prints the field in Raw

<?php print_field('field_intro_image', 'url') ?> -- Prints the image url of a field

It all works fine, but I get this error message:

Notice: Undefined index: safe_value in print_field() (line 19 of template.php).

How I can resolve this?

Also, is it possible to just enter value or url in my tpl.php file without wrapping them in quote marks?

The problem is with your function, not the template.

Ideally you should check if the index exists, e.g.

print array_key_exists($format, $field[0]) ? $field[0]["$format"] : '';

or:

print !empty($field[0]["$format"]) ? $field[0]["$format"] : '';

or:

print @$field[0]["$format"] ? $field[0]["$format"] : '';

Alternatively you can ignore the notices in PHP config (php.ini) or in Drupal admin.

Or you can just prefix the field with @ to silence/suppress any errors (usually not recommended), e.g.

print @$field[0]["$format"];


Node teaser with a different size than other nodes I have created a content type, and for some reason the teaser text has a different size than the size used by all the other nodes.

This is what happens for "Stenhousemuir For Sunday Success."

Could anyone enlighten me on why this happens?

That particular bit of text is wrapped in a <span> that includes inline styles that change the font size of that text.

If your content is entered via a WYSIWYG editor, you may want to adjust the settings for that WYSIWYG so that it strips out inline styles like this.


Using Acquia for a production site and running Wordpress concurrently I've been building a website for my library in Drupal 6 using the Acquia Installer package on my local machine, a Win7 PC. I'm also going to need to run 2-3 Wordpress blogs alongside Drupal on the same machine, both on my local machine and when everything is migrated to our Server 2008/IIS 7 machine.

Do I need to ditch Acquia Installer now while still developing in order to run WP alongside Drupal? I've thought about installing WAMP alongside Acquia just to run WP on my local machine. But that seems like it would kill my local machine, running two separate installs of Apache, MYSQL, PHP, etc. And Acquia + WAMP probably isn't the smartest way to set up an efficient production environment on my server.

Acquia Installer is just an *AMP package. It installs standard versions of Apache, MySQL, and PHP, so you can configure Apache for multiple vhosts just as you would on any other machine.

Here's a guide to setting up vhosts on drupal.org http://drupal.org/node/111238

If you are deploying to IIS, I'd suggest at least testing your site locally before you push to live. These links may be of help:

http://learn.iis.net/page.aspx/505/install-drupal-on-iis/
http://www.microsoft.com/web/downloads/platform.aspx

The second is a Microsoft IIS installer with native Drupal support. MS are supporting Drupal as part of their Windows 8 push, so there are more resources around for IIS as a platform than previously.


Set data value in rules not written when using a condition I like to create a rule that will overwrite my body field after saving new content. This is content from the same node that has been created(field_update) and some content from referenced users form a user reference field(field_userrefer).

I have a CUSTOM TEXT field called "field_update".
This is is were content is written.

My actionrule is :

set data value "node-body-value" to
[node:field-update]
this works.

I have to create conditions to get the required fields I want to show in the data selection.
This also works very nice because is can see all fields in my data selection auto complete box.

The problem is that when I add these conditions my body field isn't being populated by my custom values.

Any help appreciated.

When i have a set of rules without conditions.

I have fixed. Seems like conditions is quite the puzzle. I fetched entity by ID with actions to fix it.

conditions:
Entity has field: parameter:node, Field:field_userref

actions:
Fetch entity by id(id01) :. type: user, id:node:field-userref:uid
Fetch entity by id(id02) :. type: profile, id:entity-id01:profile-main:pid
wich made all profile2 fields available.


Failure getting nodes from terms via the rest api I have added a REST web service in Drupal and all content is tagged with taxonomy. I'm now trying to acquire all related nodes to the terms.

First I'm calling taxonomy_vocabulary/getTree along with the vid and I'll get all the terms for a specific vocabulary, that works just fine. The problem comes when I've gotten all the term-id's I need to go through. When I create a request it fails to find the nodes that should be connected to the term. I'll get a 404 response on each request.

This is how I call the selectNodes.
I'm creating a POST request and pass along with the tid, the endpoint is called http://myhostname/api/taxonomy_term/selectNodes

Have someone else experienced this? Do I need to pass more arguments with the POST call?

EDIT: After a quick look in wireshark it also returns the error string: "String value: No nodes were found with tid 15". Does this mean that there aren't any relation between the terms and the nodes by default?

The taxonomy_term resource is only for returning taxonomy terms. It won't return any nodes.

There are tons of options but here are two that you can do quickly:

Install the Views Datasource module and create a taxonomy view. Have it output as json.
Create a custom resource that handles this. Check out these instructions on creating a custom resource.


How can the admin of a group edit all members default profiles? Is that possible? (Drupal 6 installation) I need to do this in a Drupal 6 installation, with the Organic Groups module:

The user that has administrator rights within a group can edit all members default profiles.

I just want the admin of an OG to be able to change each user´s email address, but the line above reflects the generic use case.

Any thoughts on how to complete that task?

Thanks!!!

Rosamunda

User Profile Access does not have elaborate access control in the fashion of nodes, so the answer is a custom module that takes over the profile edit page's menu access callback.

Use hook_menu_alter() on user/%user/edit and set 'access callback' to custom_user_edit_access. In that function, run the original access logic to preserve normal behavior, but then add another layer that checks to see if the current user is an administrator in the group and if the active user profile's user is in the group.

For D6, you can either check the user data structure directly, or use the API functions og_is_group_member() and og_is_group_admin().

If you want to special-case the email field to a specific permission once the user has access to the form, that's a case for hook_form_alter() and changing the email field's #access element to use a new permission or an access callback with logic of it's own.


Why are my custom email messages sent without styling? I have a Commerce Kickstart website working, everything works fine. Recently I wanted to create another notification email once I give an order certain status. Well I created the rule, also created the message (actually I cloned the Commerce Order: order confirmation message)

All the emails sent from my commerce kickstart are with the right styling, they show good, but only the custom message I created does not have any styling, it is sent in html but does not have styling.

I do not understand why my custom message is sent without styles, I copied the styles and html that is in the Commerce Order: order confirmation message, but all the other messages have styles, I could not figure out what's going on.

I FINALLY found the solution to this problem, commerce kickstart is theming the emails using the mail.css provided for the mime mail module, this file is located in the Omega Kickstart theme that was the one Im using, for some reason my custom messages were not styled using that file, so I did some of research and found this post where they explain how to theme mime mail emails, and they reffer to an issue about using different admin theme than your default theme so they suggest add the mail.css file to all your themes folders...

Well so what I did was to make a subtheme of the commerce kickstart admin theme and the omeka kickstart theme, then I placed the mail.css file in the css/ folder of both, now my custom messages sent with message notify from rules are sent with the correct styling!!

Thank you!


BCC For drupal mail function I am using Drupal 7 and focused to work with email option. I am using the Forward module. How can I add the BCC field in the drupal_mail() function.

my default function having,

drupal_mail('forward', 'forward_page', trim($to), language_default(), $params, $params['from']);

Everything you need is in the email message headers array.

$params['headers'] = array(
    'Bcc' => 'bcc_email@example.com',
    'Cc' => 'cc_email@example.com',
);

Here is an example implementation of drupal_mail() with bcc headers included.

$params = array(
    'body' => $body,
    'subject' => $subject,
    'headers' => array(
        'Bcc' => $header_bcc,
        'Cc' => $header_cc
    )
);

$email = drupal_mail('ModuleName', 'message_key', $to, LANGUAGE_NONE, $params, $from, true);

Using hook_mail() you need to add (thank you @clive):

/**
 * Implements hook_mail().
 */
function ModuleName_mail($key, &$message, $params) {
    switch ($key) {
        case 'message_key':
            $message['headers'] += $params['headers'];
    }
}


How to alter response headers from module hook I am puzzled how to alter the response headers from specific hook (hook_file_download)?

/**
 * Implements hook_file_download().
 */
function example_file_download($uri) {
  $scheme = FileSystem::uriScheme($uri);
  if ($scheme === 'public') {
// Set custom headers here.
  }

}

Basically I want under certain conditions to set additional headers and in D7 this would happen with drupal_add_http_header() but in D8 as far as I can see this can happen only by implementing custom subscriber and using getSubscribedEvents and then KernelEvents. However this does not solve my case as I want to add custom headers only for specific file types.

If I use custom subscriber then this would be possible by:

/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = ['exampleFunc'];

return $events;
}

And then:

/**
*
*/
public function exampleFunc(FilterResponseEvent $event) {

$response->headers->set('Header', 'Value');
}

in D7 this would happen with drupal_add_http_header()

In other hooks that might have been true, but hook_file_download works the same in Drupal 8 as it did in Drupal 7, without using drupal_add_http_header.

This is the documentation for both versions’ return value from that hook:

  If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers. If the file is not controlled by the current module, the return value should be NULL.

Emphasis mine.

You can't get access to the response object in hook_file_download, because it doesn't exist yet. It's not created until after the hook is invoked in FileDownloadController::download(). The headers you return are added to the response, so returning a suitable key-value array from the hook is the way to achieve what you want.


How do I get the field label? I added some fields to the "Article" content type. I want to output them in a page--front.tpl.php. How do I get the field label value?

When I use the following code in page--front.tpl.php, it doesn't show the name of the field label. Why? What code should I use to print the field label?

$node = node_load(1);
print_r($node);

The output is similar to the following:

    [field_sq] => Array(
      [zh-hans] => Array(
        [0] => Array(
          [value] => 250
        )
      )
    )

In node-article.tpl.php  add this code at the beginning

// loop through node properties
foreach ($node as $k => $v) {
  // ensure this property is a field
  if (substr($k,0,6) == 'field_') {
    // use the CCK function to get the field data for this field
    $fieldData = content_fields($k, $node->type);

    // add the label to the array
    $fieldLabels[$k] = $fieldData['widget']['label'];
  }
}

Than you can print labels like this:

<?php if ($node->field_YourField[0]['view']){ ?>

    <?php print $fieldLabels['field_YourField']; ?> // prints label (add div/span wrapper if you need it)

    <?php print $node->field_YourField[0]['view'] ?> // prints field value (add div/span wrpaer if you need it)

<?php } ?>

This is tested in Drupal 6.
Hope it helps.


flexslider cant adjust height I have installed Flexslider on my site (just locally on PC at the moment), it adjusts the width of the slide fine when I reduce the size of the screen width using the browser, but the height of the slide always stays the same and the image appears crushed when the browser is at minimum width. Can anyone help please? I have tried going through all the youtube videos etc.. but cant see what I'm doing wrong. I am using the Omega 3 theme if thats relevant.

I run into this when using Omega 4.  What I do is set my base img tag to have an auto height:

img {
  height: auto;
}


Disable theme debug.. just in one field Is it possible to disable theme debug in one field? I don't want to disable theme debug, but when I set up background file from field, theme debug comments block this style functionality.

No, this is not possible.

You would need to hack core in order to do it (twig_render_template), which might be ok for your local development.

The code in interest is this part:

if ($twig_service->isDebug()) {
  $output['debug_prefix'] .= "\n\n<!-- THEME DEBUG -->";
  ...
}

You could add a condition, like this:

 if ($twig_service->isDebug() && $template_file != 'awesome-template-file') {

I'm not sure what $template_file looks like, but I'm sure you could use it to make a condition to make the template file in question be skipped debug. This actually requires that the field uses it's own template file though.


Creating a View of nodes with field for workbench moderation state without showing every revision? I am trying to create a table view of nodes with fields for node title and moderation state. (There are other fields but I'm omitting them for simplicity).

Currently, it's displaying a new table row for every single revision of the node. I only want to see one row per node, whatever the current state is. Grouping is not sufficient, since there are fields that are not the same across revisions.

Immediately after asking this question, I realized there is a filter criterion that can be added for this.

Workbench Moderation: Current can be set to filter based on whether a revision is the current one, and all previous ones can be excluded.

This will also exclude nodes that haven't been created or edited since the enabling of Workbench Moderation for their node type but will include newly created or edited ones.


Add external CSS file with custom backend setting I'm trying to add a external CSS file. The client wants to be able to change the url from the backend. Creating a backend settings form is not an issue, but I can't seem to get the file loaded in the frontend.

My code:

function MYTHEME_library_info_build() {
  $libraries = [];
  $libraries['mylibrary'] = [
    'version' => '1.0',
    'css' => [
      'base' => [
        'https://www.mywebsite.com/css/styles.css' => [],
      ],
    ],
  ];

  return $libraries;
}

The fixed url will be replaced with a variable containing the value entered in the backend.

hook_library_info_build() would be the right hook to add dynamic library definitions (definitions that depend on any run-time information) but it needs to be implemented by a module, as its documentation page says.

  Modules may implement this hook to add dynamic library definitions. Static libraries, which do not depend on any runtime information, should be declared in a modulename.libraries.yml file instead.

hook_library_info_alter() can be implemented by either a module or a theme.

  Allows modules and themes to change libraries' definitions; mostly used to update a library to a newer version, while ensuring backward compatibility. In general, such manipulations should only be done to extend the library's functionality in a backward-compatible way, to avoid breaking other modules and themes that may be using the library.

If there are default values you can use (for example, using a local CSS file that is then replaced from hook_library_info_alter() basing on run-time information), you can put those default values in the .libraries.yml file, and use hook_library_info_alter() to alter them.


Unset required attribute with multiple submit buttons and multistep form I have a multistep form created with msnf for an content type.
I set multiple submit buttons that each one has its own submit callback, and also i want every single button with its validation callback :

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id){
        case "my_form_id" :
          $form['actions']['submit_2'] = array(
                '#type' => 'submit',
                '#name' => 'button_name',
                '#value' => t('Name'),
                '#weight' => 6,
                '#submit' => array('node_form_submit'),
                '#validate' => 'MYMODULE_validate_2'

            );
            // Add submit callback (works fine!)
            array_unshift($form['actions']['submit_2']['#submit'], 'MYMODULE_form_submit_2');
            // rest of code ...
  }
}

inside the validation callback i put this test code :

function MYMODULE_validate_2($form, &$form_state){
  dpr('test');
  exit;
}

Here i have two problems :

1) this validation callback didn't triggered i don't know why ? (the system must show me a dump 'test' and then exit but nothing happen!)

2) I want to disable all the required fields only when i click on this submit_2 button.

I found sth in this post, but like i said the validation callback is not handled so i can't test the code inside that post.

Thanks in advance.

EDIT
 I was blind :p I must put the callback function inside an array() like this

'#validate' => array('MYMODULE_validate_2')

sometime i made stupid error :)

Now my problem is only the second one :

I want to disable all the required fields only when i click on this submit_2 button.

You can set the #limit_validation_errors property on your submit button to an empty array to bypass validation on all required elements.


How to use a div class to wrap some selected fields of a grid views view I have came through this:

Views group different number of divs of a view by wrapping them
Views - Add a wrapper DIV around a Group

but can't understand how to use a div class to wrap some selected fields of a grid views view. In my case, i want to wrap three fields of a view into a div class as the image shows below:

It's really simple by using the Field overwrites.

First, set the (author) User: Picture and (author) User: Name fields to "Exclude from display".

Then open the settings for Content: Post date field, and open "Rewrite results" fieldset.

Check "Rewrite output of this field". This will reveal another fieldset "Replacement Patterns" which should show you the tokens for all the fields above the current field. All you need to do is put a <div> wrapper in the textbox and copy the tokens you want in between the div tags.


Multiple file upload controls on same form via FAPI not possible? My research seems to be indicating that only a single file control widget is possible per form when creating said form with the Forms API.

Is this true? Still?

I'm operating in D6, I don't want to use CCK because I want to keep my custom content type within a single DB table, but I do want to be able to upload multiple files - in separate form controls which lie in separate fieldsets from one another (logical context of what the file is for).

If one uses the CCK based upload options (such as those outlined here: How to upload multiple files at once?) as soon as multiple uploads are enabled, the content type's DB table gets fragmented by having the CCK upload control's data moved to its own DB table. I don't want that.

Is the only alternative to write some AJAX/AHAH logic handling this in the background, with the FAPI's file handling basically useless here?

I will recommend you to use:

print_r($_FILES);

This placed inside the form function submit will let you know if the files are been upload it into the temp directory and what are their names. Also check the file upload field name as sometimes when you copy and paste code you might be re-using the same name and this is creating the overwriting.

Last, but not least in your custom module try adding a single upload file field and test it if it work, then add a second and try it and so on.


How to create a multisite from an existing Drupal site I have an existing drupal 7 site that we want to convert into a multi site.  I want the new database to have the same content structure as the existing site.  What would be the steps I have to take?

with Acquia dev desktop , you can click on "More" at the bottom and create a multisite from an existing site.  Other wise I also found this https://www.drupal.org/project/multisite_wizard


Attach WYSIWYG to Drupal Form With a custom Drupal form, how can you attach WYSIWYG functionality to a textarea with the WYSIWYG module?

The wysiwyg module is tied to the input format system.

Use '#type' => 'text_format' when defining your text area.


I cannot figure out how to add the search form to a child element in the menu! I am trying to get something like this http://www.theverge.com/ on my website where you click the search icon and a search bar drops down, but I cannot figure out how to make it work.  I assumed I could do it with menu_build_tree() but have failed quite a bit, so I moved onto THEME_preprocess_menu_link() and have not figured out how to add a child element to a menu item that already exists to print my search form into.

I am pretty new to programming and even newer to Drupal, any suggestions would help me greatly!

The search button on that site looks like it is a menu item however you will find that it is a separate entity, nothing to do with the menu at all.

Usually that kind of thing is achieved using Javascript and AJAX.  Javascript to make the form appear, and AJAX to submit it.

Have a look at the Popup module, it might be what you are after.


How to define Meta tags on Views? Is there any module or some configuration that I can define the meta tags for the views page display in drupal 7 using Views 3.0?

The Metatag module has views integration from the box since 7.x-1.0-beta2.

Install the metatags_views submodule and you'll get metatag options in the views UI for any views page display (Paul Querol's comment below).


How to hide/remove a specific menu heading tittle I have created a menu using Superfish containing the following items: "Menu 1," "Menu 2," "Menu 3," and "Contact."

When I click on each menu, the heading title is displayed. I want to hide the contact menu title. i was trying to hide it from the block but each menu doesn't have a block title.

How can I hide only the "Contact" menu heading title?

You should:

select the Structure->Blocks menu;
from the blocks list, click on "configure" next to your menu block;
specify <none> as block title.


Organic Groups for grouping users? I have a project where I want to group users. So for example, say we have a role of 'King' and a role of 'Subject'. I will have a view where a King can see a listing of all of their subjects. When a new user registers, they will sign up under the name of a King, so they will self-organize as to who they are a subject of.

Is Organic Groups an appropriate module for this functionality? I've watched a few tutorials, and it seems to be about sharing (or actually hiding and providing special access to) content. Here I'm not really so concerned about content, but rather grouping users.

If not Organic Groups, is there a good module for grouping users? This is for Drupal 7.

As far as I know, organic groups would work great for this. You can easily just hide links to the group frontpages.


Can Date API/Calendar and CCK send an argument to Views with data from a field? I have a data/calendar content type using the Date API and Calendar Modules. Each event I add to the calendar uses Advanced Node Reference and returns a list of 5 other events of the same type.

What I want is a list of the next five events following the event node's advertised event date (not the date it was published). If a new event node is added, and it falls within the next five events parameter, then when the page is generated, it is listed, bumping the furthest future event from the list. If a event node is removed, then a new (previously out of range) event node is added to the list. It is a simple sort, and very reasonable requirement using the "advertised" date and not the "published" date. The field data would be the advertised date.

The Node Reference module allows a view to be used to make the selection to populate the node reference. This I have also done. The problem is the list of possible dates/events to be linked are produced by a filter with relative date value from today's date ('>= now'), rather than from the node's content value for event date.

TDW might use an argument to pass the current date value of the date/event being edited to Views. If this exists, where is it? What is it? Some kind of [keyword] to pass in the allowed argument field of the Advanced Node Reference of this Date Content Type?

If this was a PHP template I was hand coding, the value of the current form's 'event date' field would be available from the query used to populate the form. In Drupal I don't know where this is. I'm still a newbie at Devel Module and its variables page was no help.

It sounds like you need to do a relationship to the parent node, and then use a Filter by node published date using that relationship.


menu_get_active_trail returns page not found I want to add a meta description to a custom module 'mymodule', but this doesn't load as expected.
The problem is in the active trail, when menu_get_active_trail is called inside array 1 the router_path = node/% and the title is page not found.
How can the active trail be fixed?
This works on other sites.

function mymodule_html_head_alter(&$head_elements) {
// menu_get_object with load function at position 2

if ($myentity = menu_get_object('myentity', 2)) {
  dpm(menu_get_active_trail());

  $head_elements['meta_description'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'description',
      'content' => $myentity->name,
      ),
    );
  }
}

First, you have to make sure that the active menu is actually set. In Drupal 6, we did this like this: http://echodittolabs.org/blog/2010/04/drupal-fails-set-active-menu-trail-causing-context-fail.

Next, clear the cache, and then refresh the page. Yes, dpm() has a lag or something. If you see the right data, great.

My data was actually being cached as page not found, when actually it had set the correct data. Don't know why.

So, your debug info may show "Page not found" when, what is being rendered would be correct. The way you see if this is the case is by clearing the cache and refreshing.

This is for Drupal 6, but the principles likely hold for Drupal 7. Unfortunately, I doubt anybody rewrote the crufty old menu system. Too much AJAX and glitz.


title of view posted link is not showing I have created a view with display format Unformatted List of titles (linked) and it works fine as it shows the list of linked title but the problem is now when I click the link to view the article it shows full post without title.

So am I doing something wrong? How to show the title there?

It looks to me that the problem is with the node display itself and not the view.

When you click the title you're led to the node page.

Check your content type display settings in Structure->Content Type->(your content)->Manage Display


Programmatically printing from field_collection array Is there any simple way to print a certain number of elements from a field collection?

Say I have an array of 8 elements and want to just print 4 at the top of a page; then, print the other 4 at the bottom.
Right now I'm attempting it in the node.tpl I am theming.

print render($content['field_my_elements_of_whatever']);

You can use Entity View Modes to solve the first part.

Install/enable the module, then configure some new view modes for field collections.

Then, goto the Field Collections config, and do the Manage Display for your collections.  Configure the new view mode(s).

Now, goto the Manage Display for your nodes.  Click the settings gear for the field collection field, and choose your view mode.

That should set you up for your second part, which is rendering out a field twice.  There are several ways to do this, like this and this.  You would just need to make sure your duplicated field uses your other view mode.


How do I customize the location of a webform for a node type? I'm customizing a node type and need to add a webform using the webform module. How do I add the webform in a custom location without having a machine name for the webform?

In the code below for example, I want to populate body content followed by the webform:

<div id="content">
    <?php print render($content['body']); ?>
    <?php print render($content['WEBFORM?!?']); ?>
</div>

And, yes, I know about displays and how you can change the location of a webform there - my node is too customized.

You were almost there. Use the following code.

<?php print render($content['webform']); ?>

Bear in mind that if you are rendering the webform before the line containing print render($content);, you would need to hide the output of $content['webform'] first, and then render it manually. In this case the code would be similar to the following one.

<?php
// This would go at the beginning of the .tpl.php file, for better readability.
// Hide the webform from rendering, because we will do it manually.
hide($content['webform']);
?>

<?php print render($content); ?>

<?php print render($content['webform']); ?>

Generally speaking, I think it is a good practice to always hide elements you want to render separately, just in case at some point you move them before the render($content) line.


Changing value of a field before rendering in Drupal 7 I am trying to change the value of a field. I need to add a dynamic class on-the-fly, based on some complext context, and I need to warp the text value with the span-class-stuff. But I haven't been able to alter the value, even if I am able to read it. I use MYTEMPLATE_preprocess_page(&$variables, $hook), MYTEMPLATE_preprocess_field..., even some hooks in my modules, but to no avail. I am unable to change it. What would be the best and effective approach?

I suppose you're not actually trying to change the value of a field – but instead change one of its attributes? It would probably be useful to see how you're trying to rewrite the classes inside those theme functions so far. Basically that should already be the right location to do this.

I recently just had a very similar problem, wanting to rewrite classes of a node. I know it's not exactly what you're asking – but the approach should be very similar. Inside your preprocess funtion first you should extract the already existing classes for later use:

$variables['classes_array'][] = drupal_html_class('node-' . $node->type);

Then you could add classes to the classes_array according to your conditions:

if ($variables['promote']) {
    $variables['classes_array'][] = 'node-promoted';
}

Find full example code and further details on this page or also over here.


Don't load jQuery, even when modules have it as a dependancy How can I stop jQuery being loaded in Drupal 8, even when modules which use jQuery are on the page?
I have an existing style guide which I'm pulling into a Drupal 8 site. I already have all the JavaScript including jQuery as part of the style guide and I want to keep this separate from Drupal.
For anonymous users everything works fine. However admin users have access to the admin toolbar. This loads in Drupal's own version of jQuery which conflicts with the style guide's and causes the admin toolbar to break.
I tried adding this to my theme's libraries file:
core/jquery: false
core/jquery.once: false
core/jqueryui: false

Inspecting the page it did appear to block some jQuery references but not all of them:

However when I remove my entries from my theme's libraries file I can see that in fact all of the same jQuery files are being loaded, so I don't actually think it achieves anything.

I know that normally one would not load in jQuery themselves and just use Drupal's version, but the style guide requires the latest version and is also consumed by other applications so I cant change it very much.

You should be able to alter the JavaScript files include on the page with an implementation of hook_js_alter().


Including JS after the JS specified in theme info file The goal is to include js files for custom block from custom module after the JS specified in the themes.info file. From the moduleName.module

function moduleName_block_view($delta = ''){
  $block = array();
  switch($delta){
    case 'contact_form':{
                $block['subject'] = '';
                $block['content'] = array(
                    '#markup' => build_contact($delta),
                    '#attached' => array(
                        'js' => array(
                            'http://somepath/0.0.2/contact-0.0.2.min.js' => array(
                                'type' => 'file',
                                'weight' => 1000,
                            ),
                            drupal_get_path('module', 'moduleName').'/js/contact-config.js' => array(
                                'type' => 'file',
                                'weight' => 5,
                            ),
                        ),
                    ),
                );
...
return $block;
}

The weights work for the two JS files within the custom block as specified here. Problem is that, i am unable to make these js files be imported after the js files specified in theme.info file. How to make these file import after the theme js? Thank you for help

You can specify the #scope attribute to control where the JS gets added. For example, you could place it in the footer, which (more likely than not) would come after your theme's JS:

'#attached' => array(
  'js' => array(
    'http://somepath/0.0.2/contact-0.0.2.min.js' => array(
    'type' => 'file',
      'weight' => 1000,
      'scope' => 'footer',
    ),
    drupal_get_path('module', 'moduleName').'/js/contact-config.js' => array(
      'type' => 'file',
      'weight' => 5,
      'scope' => 'footer',
    ),
  ),
),

Alternatively, you could implement hook_js_alter() to change the 'final' ordering of the JS files added through #attached, drupal_add_js(), .info files, etc.


What does `OWNER` value mean in Rules export? When exporting a rule from Rules module you get some serialized representation of that rule.
I understand everything but the 'OWNER' property in the export string - it has 'rules' value, but what does it mean specifically?

If I want store this rule in code within my module, do I need to change this value to 'module_name'? What are the implications here?

OWNER means what module provided this rule. The reason for this is so we have a good way for contrib modules like drupal_commerce to have a section in their administrative area to only show an interface for their rules and not ALL rules.


Features reset without drush In Drupal 7, my commons wiki gives an error when editing.

  EntityMetadataWrapperException: Unknown data property
  field_target_nodes. in EntityStructureWrapper->getPropertyInfo() (line
  339 of
  /home/content/44/11622944/html/sites/all/modules/entity/includes/entity.wrapper.inc).

According to Drupal, the problem is that when commons is installed, it doesn't reset features because it might cause the user to loose work. So the solution is to reset features.

So I go /admin/structure/features/commons_wikis here and reset all I can, but I'm still having issues. My  FIELD INSTANCES and MESSAGE TYPE are "stuck" in overridden. I've tried clearing the cache too.

I can't install or use drush because I'm on a hosted solution and SSH isn't an option.

How can I reset FIELD INSTANCES and MESSAGE TYPE without drush?

You can revert features in an update hook

e.g, in MYMODULE.install:

/**
  * Revert the 'field' component in my_feature_module
  */
function MYMODULE_update_7001(&$sandbox){

  features_revert(array('my_feature_module' => array('field')));

}

http://drupalcontrib.org/api/drupal/contributions!features!features.module/function/features_revert/7

Note, if you have manual access to the code, you can check in the wrapper if the field isset first prior to use, preventing that EntityMetadataWrapperException:

e.g:

// Check if field is set prior to use, avoid EntityMetadataWrapperException
if (isset($wrapper->field_target_nodes)) {
  drupal_set_message('<pre>'. $wrapper->field_target_nodes->value(). '</pre>');
}


CKeditor not showing. 403 on ckeditor.config.js and ckeditor.styles.js I have a site with ckeditor 7.x-1.16 installed (not the WYSIWYG module). I have a local dev (XAMPP windows) staging (Linux) and production (Linux).

On the local dev copy and the production copy ckeditor isn't showing on the edit body tag.

In firebug net tab ckeditor.config.js and ckeditor.styles.js are showing as 403 - forbidden.

I have tried replacing my local copy of the ckeditor module and the ckeditor library with the ones from the staging server where ckeditor is working. This does not fix my dev copy.

I have tried upgrading to ckeditor 7.x-1.17. I have tried a new install of 7.x-1.16. I have tried deleting the ckeditor library and downloading a fresh version. I have tried moving the library files to the alternative location within ckeditor. I have tried to increase the permissions in windows of the ckeditor module (I believe windows doesn't have chmod). I have also tried chmod 755 on the module files on the production site. None of these has helped.

ADDITION: I have have made a new local version of the Staging server version (where the problem doesn't occur). The problem is on the fresh local copy, despite it having the same files and db as the staging version.

I worked this out. I found an .htaccess 'deny from all' file in the sites/all/modules directory. It must have accidentally got copied in there from the sites/all/files/private directory. I removed the file and ckeditor shows fine.


How do I have a dropdown select list for an entity reference? For Drupal 8, the entity reference field displayed in form is a textfield with auto-complete feature for you to select the entity, is it possible to have it be dropdown select list instead? I have tried using views as the reference method to check the possible solution, but without luck, someone can help me with this?

Yes, you can. Drupal 8 does it out of the box as D7. The only difference is you can now choose the widget for any field in the Manage form display tab of a entity type.

E.g. Try changing the widget of the entity reference field - Tags - for article content type from /admin/structure/types/manage/article/form-display


How to fire multiple Rules Actions in a single rule? I have a real estate website using the drealty module. In the real estate RETS feed, there is a numeric field called "Area". That numeric value refers to a specific area... for example, "22" might be "Miami Beach", and "32" might be "Miami Beach" and "South Beach".

When new real estate listings are created (via a command line in drush), I need for the corresponding "verbose" name of the area(s) to be selected from a specific taxonomy. For example, if the RETS feed returns "22" for the area value, then "Miami Beach" should be checked in that taxonomy field on the listings entities. Likewise, if the RETS feed returns "48", then both "Miami Beach" and "South Beach" should be checked.

I created a Rules Component for each area numerical value. The Miami Beach Rules Component is below:

 { "rules_set_area_miami_miami_beach" : {
 "LABEL" : "Set Area - Miami - Miami Beach",
 "PLUGIN" : "rule",
 "OWNER" : "rules",
 "REQUIRES" : [ "rules" ],
 "USES VARIABLES" : { "drealtylisting" : { "label" : "drealtylisting", "type" : "drealty_listing" } },
 "IF" : [
   { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area" } },
   { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area_taxonomy_" } },
   { "data_is" : {
       "data" : [ "drealtylisting:field-area" ],
       "op" : "IN",
       "value" : { "value" : [ "22", "32" ] }
     }
   }
 ],
 "DO" : [
   { "data_set" : {
       "data" : [ "drealtylisting:field-area-taxonomy-" ],
       "value" : { "value" : { "35" : "35" } }
     }
   }
  ]
 }
}

The same type of Rules Component exists for South Beach:

  { "rules_set_area_miami_south_beach" : {
  "LABEL" : "Set Area - Miami - South Beach",
  "PLUGIN" : "rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules" ],
  "USES VARIABLES" : { "drealtylisting" : { "label" : "drealtylisting", "type" : "drealty_listing" } },
  "IF" : [
    { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area" } },
    { "entity_has_field" : { "entity" : [ "drealtylisting" ], "field" : "field_area_taxonomy_" } },
    { "data_is" : {
        "data" : [ "drealtylisting:field-area" ],
        "op" : "IN",
        "value" : { "value" : [ "32" ] }
      }
    }
  ],
  "DO" : [
    { "data_set" : {
        "data" : [ "drealtylisting:field-area-taxonomy-" ],
        "value" : { "value" : { "23" : "23" } }
      }
    }
  ]
 }
}

I then created a Rule with Event "After saving a new drealty listing" and Actions: "rule: Set Area - Miami - Miami Beach" and "rule: Set Area - Miami - South Beach".

    { "rules_set_area_on_drealty_listing_cloned_" : {
    "LABEL" : "Set Area on Drealty Listing (cloned)",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "drealty" ],
    "ON" : { "drealty_listing_insert" : [] },
    "DO" : [
      { "component_rules_set_area_miami_miami_beach" : { "drealtylisting" : [ "drealty-listing" ] } },
      { "component_rules_set_area_miami_south_beach" : { "drealtylisting" : [ "drealty-listing" ] } }
    ]
  }
}

When I run a RETS import and the website creates the new listings, I expected it to evaluate each of those Rule actions in succession and check the taxonomy boxes when necessary, but instead it appears that only the South Beach Rule Action is taking effect, and thus only South Beach is checked in that field. Is this because it is listed last in the Rule action list? Is there a better way for me to set this up so that I can get the desired end result?

I see "data set" which I'm 99% sure means your field is either set to one value.. Or in taxonomy, it could mean  that setting data overwrites previous values. So your rules might simply overwriting each other.

I can't remember much about taxonomy but change your field to infinite values if not already and use the rules action, " Add an item to list" if possible.

On a separate note, you should avail of the action "fetch entity by property" and only have maybe one rule for everything. So you'd add an integer field to your taxonomy terms and use the rules action to fetch it using the integer provided. Let me know if you want to try it.


How do I define this simple views relationship? I have a person table that has a primary key id. This is a base table.
I have an address table that has a foreign key person_id. This is NOT a base table (has no primary key)
The address table contains a person's address, but not every person has an address.

When describing these two tables to views, how do I set it up so that when the person table is used as a base table, I can optionally add a relationship to address to join in the information?

I know I can add an implicit join on the address definition like so:

$data['address']['table']['join'] = array(
  'person' => array(
    'field' => 'person_id',
    'left_field' => 'id',
  ),
);

This allows me to add any address fields automatically in the Views UI. Views would by default use a LEFT JOIN to bring in the address data. I can change this to an INNER JOIN in the above definition, but I want to allow the user to chose, which is exactly what using a relationship handler does (has the "require this relationship checkbox", which controls INNER vs LEFT).

However, in my analysis of how these handlers work, I don't think I can define the handler in a way that this will work. It seems the relationship handler should be added to the foreign key on the base table. My base table is person, which does not have the foreign key.

For instance, I tried this:

$data['address']['person_id']['relationship'] = array(
  'base' => 'person',
  'base field' => 'id',
  'handler' => 'views_handler_relationship',
  'label' => t('Address'),
  'help' => t("Has basic information on a person's address.")
);

But this doesn't work, since address is not used as a base table in my View.

How can I do this?

P.S. part of my confusion/trouble stem from my inability to define a table neither as a base table nor an implicit join table, which is what I want to do for address.

UPDATE 1: For a real-world example, look at the table accesslog and how it relates to users. When working with a view w/ users base table, you cannot explicitly add the accesslog relationship, but you can add all the accesslog fields since statistics.views.inc creates the implicit relationship. My schema is similar, but I want to use explicit relationships instead.

The very first point is that, the table itself should be defined in order for Views to access it. It's not necessary to define all the fields in the table; just define what you want to access.

You can however, define additional fields that are not in the table. The default convention in the $data array is the table name => column_name but you still can add non-existing keys to the array without Views looking for that field in the query.

Try this:

<?php

$data['person']['addresses'] = array(
  'title' => 'Addresses',
  'help' => 'Load persons address information',
  'relationship' => array(
     'title' => t('Person\'s address'),
     'base' => 'address', // base table
     'base field' => 'person_id',
     'relationship field' => 'id',
     'handler' => 'views_handler_relationship',
     'label' => t('Address information'),
     'help' => t('Address information'),
  ),
);

You will now see a new relationship, Address, to join the table, along with a checkbox to make it an INNER instead of a default LEFT join.

Similarly, you can add additional fields, arguments and filters without having a real field with the array's key in the table.


Unable to print menu links using menu_navigation_links I'm using a custom template and attempting to customize the output of specific menu items. However when I attempt to output each link in the menu specified it outputs nothing. menu-it is the machine name of the menu.

<?php $menu = menu_navigation_links('menu-it', 1);
    foreach($menu as $item){
        print $item;
    }
?>

The normal way to print that menu would be:

<?php print theme('links', array('links' => $menu), 'attributes' => array('class'=> array('links', 'site-menu')) ));?>

or similar.

If you want to do something different for individual items then in template.php you could implement:

function THEME_preprocess_menu_link(&$variables) {
    // if certain menu item, do something different
}


I am getting a PDO error which seems related to the Media module After Drupal 8.8 upgrade media module is not working.
In admin media links are not working e.g /admin/content/media
Error :
The website encountered an unexpected error. Please try again later.

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'media' doesn't exist: SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM {media} base_table GROUP BY base_table.vid, base_table.mid) subquery; Array ( ) in Drupal\media\MediaListBuilder->getEntityIds() (line 158 of core/modules/media/src/MediaListBuilder.php).

it seems you have not done the update completely. one part of Drupal updating is Database updating.

there are some solutions to update it.

solution go to YOUR_WEBSITE_ADDRESS/update.php  the go through the steps.
solution if you have drush, run drush updb


Drupal Menu Page Callback Function went wrong with arguments I am new to Drupal, and I was trying a small example from Book "Pro Drupal 7 Development", this is an example of basic menu system, here is code:

function menufun_menu() {
$items['menufun'] = array(
    'title' => 'Greeting',
    'page callback' => 'menufun_hello',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}

function menufun_hello($first_name = '', $last_name = '') {
return t('Hello, @first_name @last_name'，
    array('@first_name' => $first_name, '@last_name' => $last_name));
}

But I got HTTP 500 Error all the time:

  The website encountered an error while retrieving 'http://example.com/SampleDrupalSite/'. It may be down for maintenance or configured incorrectly.
  Here are some suggestions:
  Reload this webpage later.
  HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

When I tried function menufun_hello() without page callback arguments, it was all okay. Here is code without parameters:

    function menufun_hello() {
    return t('Hello!');
    }

May I ask what was wrong with this? (Plus, I've googled before I post it here).

Really embarrassed to say I made one tiny small mistake in this line of code:

return t('Hello, @first_name @last_name'，
array('@first_name' => $first_name, '@last_name' => $last_name));

I was typing the first comma while switched to Chinese Simplified PinYin, correct code should be:

return t('Hello, @first_name @last_name',
array('@first_name' => $first_name, '@last_name' => $last_name));

After I changed it, everything is okay now. Thank you all for paying attention to my silly question.


Iterate through user custom fields in twig I'm trying to iterate through a user reference field using twig. I'm able to get the username, but not any of the custom fields that I made for users such as "First Name" and "Last Name".

{% for item in items %}
  {{ kint(item.content['#options']) }}
  {{ item.content['#title'] }}
{% endfor %}

I'm trying to get the email address as well, but I can't figure out how to get these values.

I thought it would be something like:

{{ item.content['#options'].entity.mail }}

When I do that, the entire site crashes and I get errors. Am I doing something wrong?

You should never try to display field values by going that deep into structured field properties data within your Twig templates.

Consider using according field displays, or hook_preprocess_HOOK() to preprocess your template variables, e.g. by providing a simple array of preprocessed item data the template can iterate over (an abstract example to put into your mytheme.theme file; where you have to replace mytheme with the name of your theme and themehook with the template's theme registry hook - usually the template name with underscores instead of dashes):

/**
 * Implements hook_preprocess_HOOK().
 */
function mytheme_preprocess_themehook(&$variables) {
  // This will be the new list variable to attach to the
  // template.
  $users_list = [];

  // Get the entity object from existing theme variables.
  // This example assumes you have a node entity in
  // your variables array already.
  $entity = $variables['#node'];

  // Load all referenced users from a field named
  // 'field_users_entityreference'.
  $users = $entity->get('field_users_entityreference')->referencedEntities();

  // Iterate through all users found.
  if (!empty($users)) {
    foreach($users as $user) {
      $item = [
        // Add whichever properties you'd like
        // to show within your template.
        'email' => $user->getEmail(),
      ];
      $users_list[] = $item;
    }
  }

  // Attach the new variable to the template.
  $variables['users_list'] = $users_list;
}

In your Twig template you can now access the users list by accessing the new users_list variable:

{% if users_list %}
  {% for item in users_list %}
    {{ item.email }}
  {% endfor %}
{% endif %}

EDIT:

According to the template name you provided, you are trying to alter how the entity reference field itself is displayed. Generally you have the following choices:

(1) Using field display: Add an according display to the user entity and change the field display to rendered Entity using this display. You can do so by

Go to "Admin / Structure / Display modes / View modes".
Find the User entity (should be somewhere at the bottom) and add a new user view mode.
Then go to "Admin / Configuration / People / Account settings / Manage display".
Choose the newly created view mode and add all fields you want to show.
Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
At the field in question change the Format to rendered entity and choose your newly created display mode by clicking the cogwheel at the very right of the row.

This approach usually fits your needs if you don't want to digg too deep into programming. Unfortunately you'd like to show the email address. This field is usually not available in user displays (privacy reasons; re-consider if you really want to show it). If you like to add that field to a regular user view, you'd have to additionally implement hook_ENTITY_TYPE_view().

(2) Alter the additional template variables within a preprocessing hook:

Within "Admin / Structure", head to the entity using the reference field and find the "Manage display" tab.
At the field in question change the Format to Entity ID.
Implement a preprocessing hook as described above.
Fetch the item IDs from the existing variables and load the user entities.
Attach your information to the variables and use it within your template:

$users = \Drupal\user\Entity\User::loadMultiple($variables['items']);


Add content screens from the front end I am building a web application (for trusted users), so the logged in user will have the ability to add content. However currently, when the user wants to add a record, they move from the frontend theme to the Admin UI, (the "Content > Add Content > Article" page).

This looks unprofessional, and I don't really want non-technical users let loose on the Admin UI.

How can I create "frontend" pages to let the user Add New Nodes or Edit Nodes?

(Essentially, I want to mimic the Add Article and Edit Article screens, but on the frontend of the site).

I'm not afraid of a bit of custom coding if necessary, but need to be pointed in the right direction!

Go to /admin/appearance, uncheck the box name 'Use the administration theme when editing or creating content', and save.


Is the X-csrf-token only available for authenticated users? I am working on a rest api end point. I am noticing that some end points work without X-csrf-token header. Digging into the core revealed the following
  // This check only applies if
    // 1. the user was successfully authenticated and
    // 2. the request comes with a session cookie.
    if ($account->isAuthenticated()
      && $this->sessionConfiguration->hasSession($request)
    ) {
      if (!$request->headers->has('X-CSRF-Token')) {
        return AccessResult::forbidden()->setReason('X-CSRF-Token request header is missing')->setCacheMaxAge(0);
      }

This means that the X-csrf-token header is only checked for authenticated users. Are anonymous users not required to have this header? This really seems counter-intuitive to  me as I feel that authenticated users already have a session cookie and its the anonymous users that need some kind of validation.
How do we add token validation for anonmyous users?

Drupal still doesn't use CSRF tokens for anonymous users. The CSRF token is also checked only when a session is available for the currently logged-in user, and only when the request method declared from the route is not one of the following: GET, HEAD, OPTIONS, TRACE.
There are some issues opened for Drupal core, which (at the moment I write this answer) still have to be fixed for Drupal 9.1.x, such as Allow form tokens to be used on anonymous forms in some cases, CSRF check always fails for users without a session, and X-CSRF-Token request header is missing when using Bearer authentication (which needs the steps to reproduce it).
The only way to add CSRF tokens for anonymous users is creating a new service that duplicates almost all the code in CsrfRequestHeaderAccessCheck, possibly using a route requirement that is different from _csrf_request_header_token used from Drupal core, and add that route requirement to the routes of your module that needs to be accessible also from anonymous users. Such service should also create a session, if it has not been already created.
Keep in mind that CSRF tokens are requested for those routes that alter data (for example, a route that deletes data from the database). If the route is simply showing data, the CSRF token is not requested.


Node PHP function causing CRON not to run properly Below is my code. I have two fields.

By default, "$staticPath" equals the path of the "field_static_ad" field, and "$flashPath" equals the path of the "field_flash_ad" field.

However, when there is nothing uploaded to "field_flash_ad", I want "$flashPath" to equal the path of "field_static_ad" instead.

This code WORKS for me know, but something is going wrong when I run CRON! I don't get an error, but I can't index my site.

<?php
if ($node = menu_get_object()) {  $nid = $node->nid; }

$staticPath = file_create_url($node->field_static_ad['und'][0]['uri']);

$flashPath = field_get_items('node', $node, 'field_flash_ad');

if ($flashPath) { $flashPath = file_create_url($node->field_flash_ad['und'][0]['uri']); }

else { $flashPath = file_create_url($node->field_static_ad['und'][0]['uri']); }
?>

Is there something wrong with my php?

Try debug_cron module to debug the cron issue.Also I am not sure if the mentioned code is even executing on cron run.
This module provides debugging of

 fail due to programming or runtime errors
 time out (PHP, server, database)
 are very slow

  Cron Debug will also allow you to test run specific cron functions
  while not running others. This can be nice for developing cron
  functions where you don't want to run a full cron.php with all
  maintenance, alerts and other tasks every time you test your own
  function.

Also why not you putting the complete code inside the first if conditions like'

if ($node = menu_get_object()) {
  $nid = $node->nid;
  $staticPath = file_create_url($node->field_static_ad['und'][0]['uri']);
  $flashPath = field_get_items('node', $node, 'field_flash_ad');
  if ($flashPath) {
    $flashPath = file_create_url($node->field_flash_ad['und'][0]['uri']);
  } else {
      $flashPath = file_create_url($node->field_static_ad['und'][0]['uri']);
   }
}


Use safe_key in webform emails I want to be able to send the safe_key through the internal email.
The website was doing this before, and for some reason is not any longer.

I've tried %value[safe_key] and %safekey.
I read some information here, but no one seemed to have an answer that worked.
Is there another token that works? I saw %email[key] but was not sure that it would map right.

I had a similar problem, the solution I found was here: https://drupal.org/node/1340010

If you are using webform v3.x, then you will need to apply patch #19.

If you are using webform v4.x, patch #22 (I have not tried this one).

For me, to apply the patch (on a Linux system), I did the following (adjust the first line to match where your webform module is):

cd /etc/drupal7/all/modules/webform
wget https://drupal.org/files/webform-1340010-19.patch
patch < webform-safe_key.patch

Then I had access to a new token called "%safe_key" that did exactly what I wanted (e.g. "%safe_key[field]" gave me the value of the safe_key in the email, rather than the display value.


How to determine what image style an image field of a node has? In D7, is there a way to get an image style assigned to an image field? if I have created an image style, say, my_image_style by overriding a default image style (thumbnail, medium or large at /admin/config/media/image-styles) and then assigned it to a field_image of a node at /admin/structure/types/manage/article/display, how can I programmatically determine what style does field_image have?

You can use the field_info_instance() function to get that information:

$entity_type = 'node';
$field_name = 'field_image';
$bundle = 'article'; // Or whatever content type you need.
$view_mode = 'default'; // Or whatever view mode you want to get settings for, e.g. teaser.

$info = field_info_instance($entity_type, $field_name, $bundle);

$settings = $info['display'][$view_mode]['settings'];

$image_style = $settings['image_style'];


Custom formatting of tokens for date fields In D8.1, I have created a field called field_date and added it to a content type.

I try to use pathauto to try to configure a URL pattern for the content type like type/year/title. But the token browser does not expose expandable date options for date_field. If I enter it manually, I get "The Path pattern is using the following invalid tokens: [node:field_datetime:custom:Y]."

How can I format the output of a token for a date field, the same way I can for a node property like date created?

I've searched the issue queues for contrib token, core datetime and core token system, but I find nothing about this.

The Token module added direct support for datetime and daterange fields in December 2016. See https://www.drupal.org/project/token/issues/2786181.

You should be able to use something like [node:field_datetime:date:custom:Y]