drupal webservice error Access denied for user anonymous experts:

I am new to drupal webservice,when I have set up the backend drupal webservice,I am trying
to use firefox poster plugin to test the user/login function but I always get "Access denied for user anonymous" message ,after what I have check and searched the solution all around internet I can't find out why this error happen,could anyone who kindly take a look and help me?thank you so much in advance.

1 using firefox poster to post message and get response like below snapshot:

2 after checked the http message in fiddler,I still confused that every thing seems correct
but still error message for "Access denied for user anonymous"

3 here is my webservice configration:

This most likely has to do with permissions for anonymous user. Try updating permissions and it should solve your issue.


Unable to use rules to update field after the first update I currently have a field that shows the last updated date on a user edit page.

I'm using the current configuration for rules.

Event:
    After updating an existing user account
    After saving a new user account

Conditions
    Entity has field
      Parameter: Entity: [account], Field: field_last_updated

Actions
    Set a data value
      Paremter: Data: [account:field_last_updated], Value: now

It works great the first time but subsequent updates do not update the last_updated field with the current time. Is there something I'm doing wrong?

The issue appeared to be that the 'last updated time' field was updating only in 15 minute increments. Though I'm still not sure why it is in 15 minutes increments or how to turn that off.


Using Drush make to install a profile I use make files for a number of different flavours of sites that I build, then manually insert my own profile into the site/profiles/ directory.  Can drush make download and automatically insert the profile folder into the correct place?

Thanks

Kieran

Sure.  Take a look at the file drupalorg_testing.make.bootstrap in the drupalorg_testing project.  The relevant part is:

projects[drupalorg_testing][type] = "profile"
projects[drupalorg_testing][download][type] = "git"
projects[drupalorg_testing][download][revision] = "master"

Usually, when building a profile, you will download only Drupal core and the profile in the bootstrap makefile, and put all of your other modules in the makefile that is bundled in the profile.  If you are making a makefile that makes use of someone else's profile, then you may include your additional modules in your top-level (bootstrap) makefile.

If you ever want to move a module from one location to another, you'll want to use the registry rebuild tool.  It will fix up the system table to account for the module's new location.


What does this Omega theme warning / notice mean? I’m getting this Notice repeatedly on my Drupal Commerce site, in various places. Not sure though exactly what is triggering the notice. This Notice is:

Notice: Undefined property: stdClass::$dir in omega_css_alter() (line 276 of /home/lovetrib/public_html/sites/all/themes/omega/omega/template.php).

And the line #276 in the Omega template file is

$pattern = $GLOBALS['language']->dir == 'rtl' ? '/\.no-query(-rtl)?\.css$/' : '/\.no-query\.css$/';

I believe it’s looking for a no-query.css file….?

To remedy I put a file named omega.no-query.css in the css folder. Since Omega is a base theme there is also a mytheme.no-query.css file in my theme’s css folder.

Can someone explain precisely what that line is doing and how to fix?

The $pattern needs to be filled with one of the values to the right of the question mark. To find which value to use, Drupal checks the global variable $GLOBALS['language']->dir if it contains the value 'rtl'. If this is true, the first value is assigned, otherwise the second. Basically this is a short notation of if-else.

The problem is, that $GLOBALS['language']->dir does not exist, so php throws an error.

The lines part should read $GLOBALS['language']->directory
There seems to be a fix here, which is from 2014, so there is a good chance this fix was already integrated into production.

You might be able to fix this issue by upgrading the Omega-Template to the latest stable or maybe development version (after creating backups!)


How to add an "or" to Rules event? Is it possible to add an "or" relation to a rule's event? I'd like to do exactly the same things when two different events took place. With an "or", I don't have to clone the whole rule.

Just edit the rule and add another event to it. Reaction rules can have multiple associated events.


How to add classes to some images in a multi value image field? I have content type with a multi value image field. When adding images is it possible to add a class to some of these images? The mark up I'm trying to achieve is some thing like:

So when creating a new node I would like to add 'my-class' to come of the images. I've looked as Field Formatter modules but these seem to add the class on all items in the field.

You can create a tpl.php file for your image field.

Possible override templates are:

field.tpl.php
field--field-type.tpl.php
field--field-name.tpl.php
field--content-type.tpl.php
field--field-name--content-type.tpl.php

code for field--field-name.tpl.php file as below.

 <?php

/**
 * @file field--field-name.tpl.php
 * Default template implementation to display the value of a field.
 *
 * This file is not used and is here as a starting point for customization only.
 * @see theme_field()
 *
 * Available variables:
 * - $items: An array of field values. Use render() to output them.
 * - $label: The item label.
 * - $label_hidden: Whether the label display is set to 'hidden'.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. The default values can be one or more of the
 *   following:
 *   - field: The current template type, i.e., "theming hook".
 *   - field-name-[field_name]: The current field name. For example, if the
 *     field name is "field_description" it would result in
 *     "field-name-field-description".
 *   - field-type-[field_type]: The current field type. For example, if the
 *     field type is "text" it would result in "field-type-text".
 *   - field-label-[label_display]: The current label position. For example, if
 *     the label position is "above" it would result in "field-label-above".
 *
 * Other variables:
 * - $element['#object']: The entity to which the field is attached.
 * - $element['#view_mode']: View mode, e.g. 'full', 'teaser'...
 * - $element['#field_name']: The field name.
 * - $element['#field_type']: The field type.
 * - $element['#field_language']: The field language.
 * - $element['#field_translatable']: Whether the field is translatable or not.
 * - $element['#label_display']: Position of label display, inline, above, or
 *   hidden.
 * - $field_name_css: The css-compatible field name.
 * - $field_type_css: The css-compatible field type.
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess_field()
 * @see theme_field()
 *
 * @ingroup themeable
 */
?>

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
<?php $i = 0; ?>
<?php foreach ($items as $delta => $item): ?>
<?php $i++; ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?> custom-class-<?php print $i;?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

For more info check field.tpl.php

To override node.tpl.php check

You can also check this link https://api.drupal.org/api/drupal/includes%21theme.inc/function/template_preprocess/7


How to change calendar entry background based on taxonomy? Folks, I'm trying to figure out how to style my calendar. I was able to add color stripes based on my taxonomy, but the background of calendar entries is still that ugly yellow #ffc. What I'd like to do is to make the background the same color as the taxonomy color, only brighter/semi-transparent - for example, if the taxonomy color is #00ff00, I want to se the background of that calendar entry to #e0ffe0. I'm pretty new to Drupal and really can't figure out what's the right way to do it.

Look at the HTML source of your calendar display, and try to find:

Calendar entry stuff

The CSS class name might be something like "block block-calendar block-calendar-entry" but you just want the most specific one that works, and only shows on each calendar entry.

Use CSS transparent coloration of the individual entries:

/* Colors a calendar entry lighter */

div.block-calendar-entry {

background-color: rgba(255, 255, 255, 0.3)

}

The first three numbers give the RGB value, and the last one gives the opacity.

Since 255, 255, 255 (maximum red, green, and blue) would be white, an opacity of 0.3 (30%) will lighten any background color that bleeds through from the parent container.


How can I leave Subject as blank when fill nothing in the subject field of a comment? When we fill nothing in the subject field of comment, drupal will use the comment body as the value of subject. See the code in CommentForm::buildEntity

// Validate the comment's subject. If not specified, extract from comment
// body.
if (trim($comment->getSubject()) == '') {
  if ($comment->hasField('comment_body')) {
    // The body may be in any format, so:
    // 1) Filter it into HTML
    // 2) Strip out all HTML tags
    // 3) Convert entities back to plain-text.
    $comment_text = $comment->comment_body->processed;
    $comment->setSubject(Unicode::truncate(trim(Html::decodeEntities(strip_tags($comment_text))), 29, TRUE, TRUE));
  }
  // Edge cases where the comment body is populated only by HTML tags will
  // require a default subject.
  if ($comment->getSubject() == '') {
    $comment->setSubject($this->t('(No subject)'));
  }
}

I still need to show Subject if it's been filled, while leave the Subject as blank when the user fill nothing in. To programmatically change the default behavior, we may need to override the function after buildEntity take place, otherwise buildEntity will override it again to the comment body. Is it possible to do that?

You can use hook_ENTITY_TYPE_presave to do this, just call

 if (!$entity->getSubject()) {
   $entity->setSubject('');
 }

if it isn’t filled.

Hope it makes sense.


How to check a boolean value in twig templates? We have a field_boolean (boolean field) on an ECK Bundle on the article content type. While doing research we came across the question "How to test for a boolean field in a twig template?" but it does not solve my problem.

What is the appropriate way to check for the boolean value?

We have attempted but they don't work:

{% if entity.field_boolean == True %}
{% if '1' in entity.field_boolean[0] %}

These appear to work, but not sure it is correct approach.

{% if entity.field_boolean[#items].value == '1' %}
{% if entity.field_boolean[#items].value %}

Time for another promotion of my blogpost from a while ago :)

https://www.md-systems.ch/en/blog/techblog/2017/02/20/twig-and-entity-field-api-or-how-to-take-control-of-nodehtmltwig

The relevant part:

Only display a field if a checkbox is checked, optionally with custom wrapping HTML.

{% if node.field_checkbox.value %}
   <div class="only added when there are values">
  {{ content.field_name }}
  </div>
{% endif %}

You don't need == '1' or same as or anything like that, because it directly evaluates as to a boolean value. I also wouldn't recommend to use type safe checks with content entities because they are not type safe. Values are stored in the database and anything coming out from there is a string but sometimes values might not be. The boolean field is actually the perfect example for that, it is a string one, aka a nice mix of 3 different data types.


Writing JS/PHP code in feature? Is it normal practice to write code (JS/PHP) in feature?

I was thinking that feature should contains ONLY settings, however I've read that some developers write code there and they believe it's fine.

the reason why I ask I found a video on drupalize where they write code in feature so I'm in doubt now.

Any pros and cons to that?

Yes there is no problem inserting code in a feature. I guess the con is that you do not need to introduce a new module.


How to bootstrap a custom script and retrieve the session object? I'm writing a custom script that requires a proper Drupal 8 user session to work. This is the current version:

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = __DIR__;
define('DRUPAL_DIR', $drupal_root);

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->handlePageCache($request);
$kernel->prepareLegacyRequest($request);

// get session handler and retrieve session details
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// inspect values
var_dump($request->getSession());
var_dump($session_id);
var_dump($logged_in); exit;

I'd expect $request->getSession() to return something, $session_id to be the Drupal's session id, and the $logged_in variable to be truthy. Instead I keep getting this output:

NULL string(0) "" bool(false)

Update 1: I executed this on a browser, which I have an active session with my Drupal. This script is placed in a subfolder of the Drupal installation, so it should not be a cookie path issue.

Update 2: Added var_dump($request->getSession()) to the script.

This is the code I came up with in the end. It works.

Feel free to suggest a more concise version :-)

<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$drupal_root = realpath(__DIR__ . '/../');
$autoloader = require_once $drupal_root . '/autoload.php';

// Make sure Drupal operates correct when handle request instead of internal server error and twig error
chdir($drupal_root);

$kernel = new DrupalKernel('prod', $autoloader);

// Note: The session_name is generated from the string "{domain}/{script basepath}".
// Need to override the script filename and script name before creating request.
$_SERVER['SCRIPT_FILENAME'] = $drupal_root . '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$request = Request::createFromGlobals();
// Note: may restore script_name and script_filename after this line.

// This handle process would chain up and initialize all services
// in container, include the session handler.
$kernel->handle($request);

// now we can use session normally
$session_handler = \Drupal::getContainer()->get('session_handler.storage');
$session_id = $session_handler->getId();
$logged_in = (bool) $session_handler->read($session_id);

// restore app
chdir(__DIR__);


Passing an argument to a node causes 404 On my page I have a block that reads a variable in the URL.  The page that it reads it on is a node.  When I pass an argument through the URL to the node, it causes a 404 error. ex:

www.example.com/experience //This is the node, it works
www.example.com/experience/asia //Asia is the argument, I get 404

I've tried configuring the URL Alias to "experience/*", but this obviously didn't work and only accepts '*' as the argument.  What do I need to configure to make this work?

I've heard of some modules that automatically add the aliases to the configuration table, but I would prefer a more straight-forward solution.

There are modules to accept subpath aliases.

If you're on Drupal 6 then look into the subpath_alias module.

Drupal 7 has subpathauto which does the same thing.

What they do is expand Drupal's path matching to work with subpaths, so no extra aliases are added. I've used it in the past when embedding views within nodes and it worked a treat.

So if you have node/4 aliased to path/test then it will recognise path/test/argument as node/4/argument


In Drupal 7, how do I create a custom rules event for any and all file entities? I'm having trouble creating a small module to add an Event scenario to Rules using the Rules API.  Basically, I'm creating a rule that should detect to see if certain fields of a file entity have certain values upon saving that file.  Then, if the conditions are met, the action is to change the URL path alias of /video/ to point to the newest video file in my system (file/[fid])

But I'm getting stuck even creating the new Event to even work.  My code below does succeed in making it appear in the Rules event list, and then when setting conditions, the Data Selector exposes the correct file fields.  But, when I set a very simple condition or even no condition, my action does not fire.

(A bigger aside: shouldn't the Rules module come pre-packaged with functionality for dealing with file entities?  There are plenty of events for nodes, users, and comments, but nothing for files.)

So, what is wrong with my code below?

/**
 * Implementation of hook_rules_event_info().
 */
function rules_extended_rules_event_info() {
  return array(
    'rules_extended_rules_event_file_insert' => array(
      'group' => t('Entity'),
      'label' => t('After saving a new entity'),
      'module' => 'rules_extended',
      'variables' => array (
        'file' => array ('type' => 'entity', 'label' => t('created entity')),
      ),
    ),
    'rules_extended_rules_event_file_update' => array(
      'group' => t('Entity'),
      'label' => t('After updating an existing entity'),
      'module' => 'rules_extended',
      'variables' => array (
        'file' => array ('type' => 'entity', 'label' => t('updated entity')),
      ),
    ),
  );
}

You can't just declare hook_rules_event_info(), it just tells rules about an event type, but you still need to invoke that event.

To invoke a declare event, use rules_invoke_event().

Example

/**
 * Implements hook_entity_insert().
 */
function rules_extended_entity_insert($entity, $type) {
  if ($type == 'file') {
    rules_invoke_event('rules_extended_rules_event_file_insert', $entity);
  }
}


Getting the error "No active batch." when running any batch I am getting this error when running any batch on the site:

  No active batch.

I thought this may have been a server issue, so I tried it locally, but I got the same error. I tried deleting all the records in the batch table, but I also got the same result.

The only thing I can think of is that perhaps the web server is down. Why would that effect batches that do not connect to their servers?

If you are using the Secure Pages module, you have apply the patches provided for that module.

As I am using the Secure Pages module, that fixed my problem.

  Steps to install Secure Pages 7.x-dev

  Set $conf['https'] = TRUE; in settings.php.
  Apply these two patches:

  #961508-21: Dual http/https session cookies interfere with drupal_valid_token()
  #471970-13: DrupalWebTestCase->getAbsoluteUrl should use internal browser's base URL


When posting OG content, how to choose only from Content Author's Groups? When a user is editing/creating a node, there is a field where the user can choose what groups to post the content to. I want this field to list only groups the user is actually a member of. Is there a setting for this? If there isn't, what is the best way to code this?

As far as I know the default is to provide all groups you have access to and so if you are some sort of admin then you will have this problem.


Add JS to all webform I have a Drupal 9 custom theme and would like to attach a JS file on the webform.
Adding JS file in themename.libraries.yml does not work.
webform:
  js:
    theme:
      js/webform.min.js: {}

What is the right way to attach a JS file to the other module(webform)?

Adding lines to themename.libraries.yml is not enough to add the JS, you just declared a library doing this.
Now if you want to use that library on all your theme pages, you need to add in themename.info.yml
libraries:
  - themename/webform

But if you just need to attach the library to your forms, you can use  the hook_form_alter, target your webform ids and write
$form['#attached']['library'][] = 'themename/webform';


Why is my update query OK for the database but the page shows the wrong value? I have 2 custom content entities created with Drupal Console (drupal generate:entity:content): 'person' and 'member'.
They are linked (1 member <-> n persons) by a field named 'member_id' in 'person'.
If a person is set with 'iscontact' = true, the other persons related to the same member should have 'iscontact' = false.

In the PersonForm.php, I have this code.

public function save(array $form, FormStateInterface $form_state) {
  $entity = $this->entity;

  if ($entity->get('iscontact')) {

    $member_id = $entity->get('member_id')->getString();
    $iId = $entity->get('id')->getString();
    $database = \Drupal::database();
    $query = $database->select('person', 'ap');
    $query->fields('ap', ['id', 'member_id'])
      ->condition('id', $iId, '<>')
      ->condition('member_id', $member_id, '=');
    $results = $query->execute();

    foreach ($results as $key=>$result) {
      $numberofrowsaffected = $database->update('person')
        ->fields(['iscontact' => 0,])
        ->condition('id', $result->id)
        ->execute();
    }
  }

  $status = parent::save($form, $form_state);

  switch ($status) {
    case SAVED_NEW:
      drupal_set_message($this->t('La personne « %label » a été ajoutée.', [
        '%label' => $entity->label(),
      ]));
      break;
    default:
      drupal_set_message($this->t('La personne « %label » a été modifiée.', [
        '%label' => $entity->label(),
      ]));
  }
  $form_state->setRedirect('entity.person.canonical', ['person' => $entity->id()]);
}

When I execute this, the table 'person' in the database is correctly updated, but in the page the previous person is still seen as having 'iscontact' = 1.
It's incorrect until I clear the cache.
What am I doing wrong?

I replaced

foreach ($results as $key=>$result) {
  $numberofrowsaffected = $database->update('person')
    ->fields(['iscontact' => 0,])
    ->condition('id', $result->id)
    ->execute();
}

by

  $storage = \Drupal::entityTypeManager()->getStorage('person');
  foreach ($results as $key=>$result) {
    $person = $storage->load($result->id);
    $person->iscontact = 0;
    $person->save();

And it works!


Drupal Commerce - add fields to product or product display? Ive used Ubercart before but im making my first site with Commerce. Im wondering if I should add fields (eg image and description) to my product or product displays?

Im making a site where most of my product displays will relate to one product only.

In some cases however you will have a choice of different weights to purchase. I dont yet know if Ill do this with multiple products and one product display, or if  another method would be simpler.

In the future I may want to make multipacks, so combine 10 products into a single purchase and then either give a discount on this pack, or a discount on the total price (which would allow users to substitute the chosen products so long as the total price is the same). Thanks

I add all fields that will never change depending on the variations to the product display. For the fields that will change based on variation, those fields go on the product itself.

Example:

A tee-shirt from "Rockstar Threads," a brand, and a tee-shirt from "Basic Clothes," another brand. Each shirt has two colors each, red and black.

The red Rockstar shirt is the same brand as the black Rockstar shirt.
The red Basic shirt is the same brand as the black Basic shirt.

So the "brand" field gets attached to the product display. The "color" field gets attached to the product. Now, when I create a new product, for each variation I can add a color, but I only choose a brand once since it's attached to the display. All in all, anything that will remain constant across all variations is attached to the display. Anything that will change, attach to the product.


Rendering an image field in page.html.twig with a custom image style I'm trying to set up a slideshow that's unique to each page. The code for this needs to be in page.html.twig. I've got the slideshow mostly working, but I can only call the full image URL, not a custom image style of a specific size. How can I modify this code to call a specific image size?

{% for key, item in node.field_slides %}
{% if node.field_slides[key].entity %}

    {% if node.field_slides[key].title %}

            {{ node.field_slides[key].title|striptags(",
,
,
,
,
,
,
,
,
,
")|raw }}

    {% endif %}

{% endif %}
{% endfor %}

The bit where I'm calling the URL is:

{{ file_url(node.field_slides[key].entity.uri.value) }}

I've tried doing {{ dump(node.field_slides[key]) }} to see if there was any data I could use, but every time I do that, I just get 500 error.

Any help would be greatly appreciated; I'm very new to Drupal, coming from WordPress. I think this is the last major hurdle before I can finish up this theme for my client.

Replace the image tag

<img class="swiper-image" src="{{ file_url(node.field_slides[key].entity.uri.value) }}" alt="{{ node.field_slides[key].alt  }}" />

with a render array for the image style:

{% set imagestyle = {
  '#theme':      'image_style',
  '#style_name': 'medium',
  '#uri':        node.field_slides[key].entity.uri.value,
  '#alt':        node.field_slides[key].alt,
  '#attributes': { class: 'swiper-image' },
} %}

{{ imagestyle }}

Edit:

There is a new filter in the module Twig Tweak. Now you can generate the image style url in twig directly from an uri or url:

{{ node.field_slides[key].entity.uri.value | image_style('thumbnail') }}


Display Multistep Progress I've created a multistep form to add new customer details when they sign up. So for example, step 1 is personal details. step 2 is contact details. Step 3 in social network details.

Only the fields in step 1 are mandatory so the user can skip steps 2 and 3 and finish registration.

How do I display a progress bar whilst the user is using the form?
I was wondering if I could display a 'Profile completion' percentage in a view to show the user they've only completed x% amount of their profile?

Something like this from LinkedIn:

Thanks,
Rumman

You can try using Profile Complete Percent module..

Project page says

  Profile Complete Percent (PCP) is an add-on to the core Profile module
  or the Profile2 module. It allows administrators to select profile
  fields as mandatory for a user to achieve a 100% profile completeness
  status.


Access the value of a disabled field in a twig template I'm using the Paragraphs module to create components, i then make a content type and add the Paragraph as a reference field.

The form of the Paragraph has a field (a list) where a content creator can select a color name for a background color for the div. Each Paragraph has 3 values (pacific_blue, smokey_white, white).

However, i'm trying to get the selected value without displaying it on the site.

As long as the field is not disabled i can get the value using this code and add the class to style the div with the right background color:

<div class="c14a {{ content.group_wrap.field_color_backgroud.0["#markup"] }}">
  <div{{ attributes.addClass(classes) }}>
      {{ content }}
  </div>
</div>

So how do i get the value of a field that is disabled in 'manage display'?

Thx...

Try to add it on you hook_preproccess_node to variables.

something like following snippet could help you.

on your THEMENAME.theme

function THEMENAME_preprocess_node(&$vars) {
    $node = $vars['node'];
    if(isset($vars['node']) && $vars['node']->getType()=='YOUR_CONTENT_TYPE_MACHINE_NAME') {
        $values = $node->field_color_backgroud->entity->getValue();
        $vars['myvar'] = $values[0];
    }

}

Then on your TWIG file {{ myvar }} will be available.


Drupal 7 on new Linode stack, POST/GETS 404ing but pages still loading? I'm trying to migrate a site to a new linode environment, and my website has made the journey with the exception(s) that:

I cannot login at /user/login, console shows 404s when submitting credentials and the page simply refreshes. Note: ?q=user DOES work.

When logged in (through ?q=user method), every page i request shows a 404, but then still loads the page. For example, when going to mysite.com/t-shirts, console shows 404 on that address, even though the page loads fine.

Trying to login via colorbox returns (in the modal): Request unsuccessful: error.

All the elements in my pages that use ajax fail, showing 404s in console.

Short URLs SEEM to work, i.e. /catalog returns the proper page (despite 404 in console). I can also get to admin pages with /admin paths, but cannot seem to change anything on those pages because submitting the changes always fails.

What am I missing in migrating this drupal install? Drupal install status whines about GD and cURL missing, but I don't believe this has anything to do with it..

base URL is set to the proper address in settings.php (http://dev.skinnyboyswagclub.com)

The reason for this is most likely that clean url's are disabled. Make sure that mod_rewrite is enabled in Apache.

Fetching pages still works, because the 404 triggers Drupal, which is then able to return the correct page. That does, as you found out, not work for form submits, because the submitted data is lost when doing the redirect.


What's difference between "attributes", "title_attributes", and "content_attributes"? Is there any difference between writing CSS classes directly to Html tags and using the Attribute class?

Is there any difference between attributes, title_attributes, and content_attributes? What is the usage of each of them?

I read Using attributes in templates, but it doesn't explain that clearly.

This depends on the template you use. If you use for example the node template

node.html.twig

  {{ title_prefix }}
  {% if not page %}

      {{ label }}

  {% endif %}
  {{ title_suffix }}

  {% if display_submitted %}

      {{ author_picture }}

        {% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
        {{ metadata }}

  {% endif %}

    {{ content }}

You have four attributes variables

attributes
title_attributes
author_attributes
content_attributes

The difference between them is that they have different targets in the html markup of the template. The main attributes variable in a node is for the
 tag, in a form for the <form> tag or in other templates often a simple wrapper
. If a template defines additional attributes variables they are for that specific part of the template, in a node for the title, author and content.

Always add attributes to the existing variable like explained in the linked documentation. Never replace it with your own attributes, because a lot of code depends on that the template is actually using the attributes variables.


Drupal 7.14 on IIS 7.5, MS SQL Server 10.5 I have been tasked with seeing if Drupal can be made to run on IIS (specifically, IIS 7.5 running on Windows Server 2008 R2) and MS SQL Server (2008 R2). I'm aware of Microsoft's WebPI Drupal package, but since we have an existing site which we wish to migrate to this new environment I'd prefer to add the pieces that are needed so that they can go into the source control environment with the others rather than use a black box package. I am doing the experimentation with Drupal 7.14, which is the latest release at this time.

I have got basic PHP scripts to run (Hello World, phpinfo, etc), and installed the sqlsrv driver 7.x-1.2 (recommended at the present time) into Drupal. The Drupal installation process gets as far as to the database settings screen without any complaints. However, if I select MS SQL Server as backend:

if I enter invalid database credentials I get an error back, as expected.
if I enter valid database credentials, after clicking proceed I get a HTTP 500.0 error from IIS saying about php-cgi.exe The FastCGI process exited unexpectedly.

I have enabled request tracing in IIS and found the error code GENERAL_READ_ENTITY_END Reached the end of the file. (0x80070026) in the resulting log file. Googling for the hexadecimal error code produced very little in terms of helpful information.

drupal.org reports 4772 sites reporting using the sqlsrv module, so the module obviously works. Any hints on how to get it to work, preferably other than "use the WebPI packages"?

By setting Instance MaxRequests to 1, keeping Standard Error Mode at ReturnStdErrIn500, disabling friendly errors in IIS and ditto MSIE (thanks for the link @DigitalFire which pointed me in the right direction for this), I was able to get at what I suspect is the actual command output, or at least as close to it as I can easily get in the web browser. What is shown in MSIE's "View Source" is a plain, almost-empty, boilerplate HTML document with an empty body. Before I turned off MSIE's friendly HTTP error messages (who came up with the idea of having that turned on as standard on Server, anyway?) it showed HTTP 500, so this is probably pretty close to the truth.

Using SQL Server's Profiler, I traced the database calls made and toward the end was the following, ignoring pure SELECT statements:

-- repeated a number of times
INSERT INTO system ([filename], [name], [type], [owner], [info]) VALUES (@P1, @P2, @P3, @P4, @P5)

UPDATE system SET [status]=@P1
WHERE  ([type] = @P2) AND ([name] = @P3) AND( ([status] <> @P4) OR ([status] IS NULL ) )

UPDATE system SET [bootstrap]=@P1
WHERE ( ([bootstrap] <> @P2) OR ([bootstrap] IS NULL ) )

INSERT INTO registry ([name], [type], [filename], [module], [weight]) VALUES (@P1, @P2, @P3, @P4, @P5)

The final INSERT occurs only once, with EventClass SQL:StmtRecompile. I'm not sure this helps much...

Try commenting out extension=php_gd.dll in your php.ini file and try again. I found this article in which the OP had a similar problem.


The order of field in basic page I added a field image to my basic page and I set it to be displayed first. The problem is that the image still display after the field body.

How can I change the order in which those fields are shown?

Structure -> Content Types -> Your Type -> Manage display-> Change the position of image field with plus icon -> Save


Drupal content update to Facebook page When I publish content – for instace an article – on a Drupal site, I'd like Drupal to push a status update with a link to the article to a Facebook company page.

I know there are a lot of Drupal modules that offer Facebook integration, but does any of them offer this particular functionality? Or is perhaps the best way to go to generate an RSS feed and use a third-part app like http://twitterfeed.com/ to push it to Facebook?

The site in question is a Drupal 6 site.

The Drupal for Facebook module gives you integration on a number of levels, including (with some extra work) automatic push to a Facebook page you have access to.

However, you might get better results by letting visitors to your website post references to their own timeline using something like ShareThis. This will use your audience as multipliers of your message, not just on Facebook but on other social media sites as well.


How to reset a form element to its ordinary default value? I do a form alter on a node form and make some callbacks which restrict value lists in a < select > element, which is a entity reference. When the triggering element is changed, I want to load the node forms default value just like it is in the beginning of the form process.
I remember there was an api function to do that. Someone nows it?

field_get_default_value - Helper function to get the default value for a field on an entity.
Usage:

<?php
  $field = field_info_field('YOURFIELDNAME');
  $instance = field_info_instance('node', 'YOURFIELDNAME', 'YOURNODETYPE');
  $defvalue = field_get_default_value('node', $node, $field, $instance, $node->language);
  print_r($defvalue); // Here structure, like $defvalue[0]['value']
?>


Load view with ajax and contextual/exposed filters I am trying to access content, that is provided via and can be filtered via a view. I want to load this content dynamically with Ajax. My problem now is, that I can access the view without problems using the following ajax-call:

$.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
        view_name: 'search',
        view_display_id: 'block_1',
        filterName: value
    },
        success: function(data,jqxhr) {
            $("#ajax-test").html(data)
            console.log(data[1])
        },
        error: function(error) {
            console.log(error)
        }
    });

This works fine, but it ignores the value of filterName (Which corresponds to the according input in the view form). Unfortunately using Better Exposed Filters and Links is not an option since I need to access many filters at once.

Also building an URL like so:

$.get(Drupal.settings.basePath + 'views/ajax/search/block_1/', "filterName[0]=filterValue" ,resultFunction);

did not work for me. Thanks ahead for any pointers!

If you call a display_id of block_1 the block does not have the exposed_form created to be evaluated by default in Views (views blocks cant have exposed forms out of the box) -- so your AJAX views calls knows nothing about any exposed form.

You need to either call a Views Page url where the exposed form is set on the page. Or, you need to use Views hooks to create/attach the exposed form to the View when your Ajax call is made.


Import Book content and structure from another drupal website I am looking to implement an 'Open Government Guide' on my website.

Here is a link to one of the books that I would like to copy

My question is - How do I copy both the Book Content and Book Structure from another Drupal site that I do not have admin access to? Ideally I would be able to do this for all 50 States.

If you haven't got admin access then you'll need to scrape the content. The module Example Web Scraper would be a good starting point.

I think this question on the ethics of web scraping may also be relevant.


Problem with token when unchecked "Enable signatures" and "Enable user pictures" How when i want unchecked "Enable signatures" and "Enable user pictures" show those errors:

 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [sito: login-url].
 The Body is using the following invalid tokens: [site: url-breve].

??

That error is showing up because you are using wrong names of the tokens.

[sito: login-url] should be [site:login-url].
[site: url-breve] should be [site:url].


Show a sale price and discount percentage in Commerce 2 I want to show the original/list price and sale price (actual price) in my store as well as the discount percentage: N% off!

In Drupal 7, there is the excellent Commerce Price Savings Formatter module-- just install the module, set the prices, and you're done.

What can I do in Drupal 8?  I have tried to use the built-in promotion feature in Commerce 2, but as far as I can tell the promotion UI can only be used to create coupons, not discounts that automatically apply to the relevant orders.  (based on a reading of the documentation and experimenting with the module).

Easiest way for me was to create my own FieldFormatter for the price and make it extend Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter.

Once you did that, flush the cache of your website, go to the manage display of your Product variation type, select "My Custom price calculated formatter" for Price field and in the parameters, check "Apply promotions to the calculated price". And voilà!

Here is an example code for the custom FieldFormatter:

<?php

namespace Drupal\my_custom_module\Plugin\Field\FieldFormatter;

use CommerceGuys\Intl\Formatter\CurrencyFormatterInterface;
use Drupal\commerce\Context;
use Drupal\commerce\PurchasableEntityInterface;
use Drupal\commerce_order\AdjustmentTypeManager;
use Drupal\commerce_order\PriceCalculatorInterface;
use Drupal\commerce_price\Plugin\Field\FieldFormatter\PriceDefaultFormatter;
use Drupal\commerce_store\CurrentStoreInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\commerce_order\Plugin\Field\FieldFormatter\PriceCalculatedFormatter; // This is the FieldFormatter we want to extend

/**
 * Plugin implementation of the 'my_custom_price_calculated_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "my_custom_price_calculated_formatter",
 *   label = @Translation("My Custom price calculated formatter"),
 *   field_types = {
 *     "commerce_price"
 *   }
 * )
 */
class MyCustomPriceCalculatedFormatter extends PriceCalculatedFormatter implements ContainerFactoryPluginInterface {

  /**
   * {@inheritdoc}
   * This is the function we want to extend
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    if (!$items->isEmpty()) {
      $context = new Context($this->currentUser, $this->currentStore->getStore(), NULL, [
        'field_name' => $items->getName(),
      ]);
      /** @var \Drupal\commerce\PurchasableEntityInterface $purchasable_entity */
      $purchasable_entity = $items->getEntity();
      $adjustment_types = array_filter($this->getSetting('adjustment_types'));
      $result = $this->priceCalculator->calculate($purchasable_entity, 1, $context, $adjustment_types);
      $calculated_price = $result->getCalculatedPrice();
      $number = $calculated_price->getNumber();
      $currency_code = $calculated_price->getCurrencyCode();
      $options = $this->getFormattingOptions();

      // Check if there is any adjustment for the price
      // If so, get the BasePrice (without adjustment) and format it
      if(!empty($result->getAdjustments())) {
        $adjustments = $result->getAdjustments();
        foreach($adjustments as $single_adjustement) {
          // Get the discount percentage off
          // NB: there could be many other discounts applied but this example catches percentage discounts only
          if($single_adjustement->getType() == "promotion" && $single_adjustement->getPercentage() !== NULL) {
            $discount = $this->t('@discount off', ['@discount' => $single_adjustement->getPercentage() * 100 . '%']);
          }
        }
        $base_price = $result->getBasePrice();
        $base_price_number = $base_price->getNumber();
        $base_price_currency_code = $base_price->getCurrencyCode();
        $base_price_formatted = $this->currencyFormatter->format($base_price_number, $base_price_currency_code, $options);
      }

      // This is our calculated price with the promotion
      $price_display = $this->currencyFormatter->format($number, $currency_code, $options);
      if(isset($base_price_formatted)) {
        // Set the base price (old-price), the percentage off and the calculated price within $price_display
        $price_display = '
' . $base_price_formatted . '

' . $discount . '

' . $price_display . '
';
      }

      $elements[0] = [
        '#markup' => $price_display,
        '#cache' => [
          'tags' => $purchasable_entity->getCacheTags(),
          'contexts' => Cache::mergeContexts($purchasable_entity->getCacheContexts(), [
            'languages:' . LanguageInterface::TYPE_INTERFACE,
            'country',
          ]),
        ],
      ];
    }

    return $elements;
  }

}


Caching strategy for a page that varies by IP I've created a custom cache context that determines if a request comes from in my campus network or from outside my campus network:

class NetworkContext extends RequestStackCacheContextBase implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Network');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    if (Util::requestFromCampus($this->requestStack->getCurrentRequest()->getClientIp())) {
      return 'oncampus';
    }
    else {
      return 'offcampus';
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

This custom cache context is registered in my module's services file and given the name "network".

I have a custom controller action that returns some data that varies based on if the user is on campus or off campus:

public function myCustomAction(Request $request) {
  $build = [];

  $build['my_data'] = [
    '#theme' => 'my_custom_theme_function',
    '#rawdata' => $this->fetchData(Util::requestIsFromCampus($request->getClientIp()));
  ];

  // Add some cache metadata that indicates this render array varies
  // based on the user's network. We can't effectively use cache tags
  // here since the data is retrieved from an external service and we
  // don't know when it's updated. Instead, expire the result after
  // one hour.
  $build['#cache'] = [
    'max-age' => 60 * 60,
    'contexts' => [
      'network',
    ],
  ];

  return $build;
}

Here's what I've found:

Internal Page Cache won't work here:
The Internal Page Cache module, to my knowledge, doesn't support cache contexts at all. It will store the entire page result for ALL anonymous traffic. If the request that warmed the cache for this page happened to be on campus, off campus users will also see that result, despite their cache context being different. This means I have to tell Internal Page Cache to not cache this page. One way is to add the "no_cache" option to the routing definition, which is what I've done.

Dynamic Page Cache DOES work, but not when I have the "no_cache" option set. I've found that dynamic page cache DOES support cache contexts entirely, so it will correctly vary the response by my custom cache tag! However, I can't keep Dynamic Page Cache working while also turning off Internal Page Cache, because the mechanism to disable one will disable both.

My questions:

Is there a way I can disable internal page cache for a page but NOT dynamic page cache?
Is using the dynamic page cache appropriate here, or am I using it incorrectly? I looked into auto placeholdering but that seems to be for things that are highly dynamic, but my cache context is not. It's either "yes" or "no".

One approach could be to use a middleware to set a query parameter:

  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    $ip = $request->getClientIp();
    if (Util::requestFromCampus($ip)) {
      $request->query->add(['oncampus' => '1']);
    }
    else {
      // remove the query parameter in case an off-campus user sets it incorrectly
      $request->query->remove('oncampus');
    }
    return $this->httpKernel->handle($request, $type, $catch);
  }

Set a priority higher than 200, so that it runs before the page cache. The page cache uses the url including the query string as cache key and so both versions can be delivered from cache, which is good for performance.

As example how to set this up see Drupal\ban\BanMiddleware.

If you use this approach you don't need the custom cache context anymore, you can use a context for the query argument in content that varies for off- and on-campus users.


Applying image style breaks image src I have added simple blogging functionality to my Drupal Site using a custom content type named Blog that I created.

One of the fields in Blog content type is a image field.

Inorder to display a list of teaser blog posts, I created a view with a page named Blog List.

This view displays a list of Blogs using the Teaser view mode.

This works fine until I try change the image style associated to the Teaser view mode for the Blog content type.

When the Image Style is set to None(Origional Image), all the images are visible for the teasers on my Blog List view page.

When I change the image style to anything else like "Medium 220x220" for example, the images for the Blog teasers do not display on my Blog List views page and it appears if their links are broken. I have also noticed that when I apply a Image style the Blogs teaser display image field, the image src is appended with something like "?itok=R1dYIZFH", when I temporarily remove this param, the image is displayed.

I am trying to do all of this through the UI.

Any help and suggestions would be greatly appreciated <3

The ?itok='xxxxxx' is normal.  This is to prevent possible DDoS attacks.

This problem can be broken down to a couple of things to check.

First, you need to check if the image is actually being created properly.  You can do this by looking in your public files directory under styles/[image style]/public/[path to original] (e.g. does public:/resources/foo.png exist in the directory sites/default/files/styles/medium/public/resources/.  You should see the new image there.

If not, then there is a problem generating the image. Check the status report to verify that a graphics tool exists.  Also check the logs for errors.

Common problems here are that the directory rights are not set correctly and the system can not create the file.

If the image file exists, you may be having a browser cache issue.  Most browsers will latch onto a 404 and not try to reload it.  You will need to force a full page reload (Shift F5 in most browsers) or clear cache / view from an incognito to see the image.  Only on your test browser.  Once it is created, others will not have this problem.

Another possiblity is that your site is using an upstream caching service, e.g. CloudFlare, Varnish, etc.  This service may be caching the initial 404 and not letting people see the image.

If there are still problems, please update with more information, including a URL.


How to add registration and login in a custom modules I am creating a multi step form and in a one step i want to add user registration and login forms in as tabs and i have custom module which is uses to load multi step form,my problem is how i add registration and login forms in my page i try with things but didi't work out

  function garland_user_bar() {
  global $user;
  $output = '';

  if (!$user->uid) {
    $output .= drupal_get_form('user_login_block');
  }
  else {
    $output .= t('
Hi !user, welcome back.
', array('!user' => theme('username', $user)));

    $output .= theme('item_list', array(
      l(t('Your account'), 'user/'.$user->uid, array('title' => t('Edit your account'))),
      l(t('Sign out'), 'logout')));
  }

  $output = '
'.$output.'
';
  return $output;
}

You to need render the form element.

Use the following to print the forms:

print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));


How can I programmatically get a list of orders purchased by a specific user? how can i get list of commerce order purchased by specific user programatically?

i want to create function for it so that other developers can use it in further development by simply calling that function.
i want to get name of orders purchased by user based on uid.

i have used drupal commerce module for it,i am not getting any table column in database where i can get relevant data.

to get ALL orders of a user - get user ID ($user_id)
then

$orders = \Drupal::entityTypeManager()
  ->getStorage('commerce_order')
  ->loadByProperties(['uid' => $user_id]);


The right way to validate fields Rather than creating a new field via the Field API, and as a quick workaround, I've added a simple text field to a content type that I'm now attempting to validate via hook_node_validate(). Unlike previous versions of Drupal, the value for this field is not simply available as $node->field_name or $form['field_name'], but instead as a nested array containing a variety of other information.

My question then is this: what is the 'correct' and therefore most future proof way to retrieve the value for this field?

Am I supposed to be using the likes of field_view_value() or field_view_field(), or is it acceptable to simply reference $node->field_name['und'][0]['value'] for example.

field_get_items() is the one you're looking for.

$items = field_get_items('node', $node, 'field_FIELD_NAME');
$first_value = $items[0]['value'];

It also takes care of language selection for you, so no need to worry about that one any more.


Can I make the second button in a form the default button? I have a form in a custom Drupal 6 module built with the Form API, it has 1 or more image_button elements in a list followed by the Save and Cancel buttons.

Everything is working fine when clicking the image and standard buttons, they call the submit functions they should, but if I hit the [ENTER] key within any of the text fields in the form the first button in the form is submitted, which unfortunately in this case is an image_button in the list rather than the Save button.

This is a standard problem with web forms, you generally have to hack in a hidden (by style and/or size) button early in the form definition to ensure the default submit path is called (in this case that's what the Save button will call) rather than the submit path for the buttons that are before the button you want to be the default.

Is there some Drupal 6 magic that enables setting a default button regardless of where it is in the form definition that I've failed to find in the docs, or should I create a phantom submit button that is styled to not be visible?

Thanks in advance for any answers.

The answer seams to be no, there is no built in Drupal method of getting around the problem of the first button in a form being the default when pressing [ENTER].

Here is what I had to do.

I created an extra submit button at the top of my form:

// A submit button that needs to be hidden, it'll be the default rather than one from the list.
$form['hidden-submit'] = array(
  '#type' => 'submit',
  '#value' => 'Save',
  '#attributes' => array('class' => 'hidden-default-submit'),
);

In the CSS included for the page I added the following belts and braces CSS to hide the extra submit button in as many web browsers as I could test:

.hidden-default-submit {
  position: absolute;
  left: -2000;
  top: -2000;
  width: 0;
  height: 0;
  border: 0;
  margin: 0;
  padding: 0;
}


How to show translated taxonomy terms in a view? I have used the Views module to create a view of taxonomy terms.

The taxonomy terms are translated in the Greek language also (apart from English), using the typical i18n modules.

But when I switch the language to Greek (while visiting the site), still the English taxonomy terms are appearing (and not the terms in Greek).

How can I solve this?

Instead of adding the term: name, add term: name (localized) to your view.


What permissions affect fields attached to taxonomies that don't affect fields attached to content types? On a D7 site, I created a Description field (using filtered text with ckeditor) and a Geolocation field using a Googlemap widget.

I attached them to a content type called Accommodation, and they behaved as I expected - ie, I got a rich text editor on Description, and a map on the Geolocation field, when logged in with any role that would allow me to edit a node of that content type.

I attached the same fields, with the same settings, to a Taxonomy, and found that I could only see the map and ckeditor if logged in as an administrator.

If I logged in with another role, the googlemap and rich text editor would not appear, although I was still able to create a taxonomy item, and they did appear on the same fields shown on a node create form  -  just not on the taxonomy item create form.

I have all taxonomy permissions turned on for authenticated users.

Leaving an answer in case it's useful to anyone else.

The permission that was affecting the display of taxonomy ckedit and geolocation fields was 'View the administration theme' - it looks like the Open Framework theme has a small issue when displaying taxonomy edit field forms.

I should have just changed to a default theme to test this.


how to add directory name after uri I want to append the name of a directory, say 'abc' to public:// uri of sites/default/files directory, such that it will point to the 'abc' directory inside sites/default/files.

Actually, whenever I try to do this file_move($file_object, 'public://abc', FILE_EXISTS_REPLACE) it moves the file inside sites/default/files and creates a file called 'abc'.

I want to move the file inside 'abc' directory, by appending 'abc' to public://, how do I do this?

I have searched for this and found that public://abc does the trick, but its not working for me.

Your function is telling drupal to move $file->filename to public://abc and hence renamed to abc. Drupal is doing what you are asking to do.

your $destination should be - 'public://abc/' . $file->filename

file_move($file, $destination, FILE_EXIST_REPLACE );

Below code should work (though not tested):

 $file = file_load($fid);
 $destination = 'public://abc/';
 if(file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
   file_move($file, $destination . $file->filename, FILE_EXIST_REPLACE);
 }


How to pass a nid to panel, and load a node with the given nid as context? The panel has a custom path, Like this: http://example.com/mypanel/something/theNID/something_else

So the arguments to the panel are:

something
theNID
something_else.

How can I load a node with some variable nid (theNID in this case), and have it available as a context in the panel, and then, make all of it's fields accessible directly in that panel?

If I create a view and load the node (with theNID) within the view, the view won't pass the loaded node as context to panels.

Settings -> Basic -> Path -> something/%node/something_else
Settings -> Arguments -> Change ->  Content: ID

Then at 'Variants -> Contexts' you should see the loaded 'Argument 1'.


I cannot delete a view I installed the module "himuesgallery" in a Drupal 7 site, and created two image galleries. To display them on one page, I created a view. When I try to remove the view, the system is showing me the message: "The view has been deleted." It seems to be ok, but it isn't. The view is still there and can't be deleted.

I also flushed the cache, but nothing changed. DO you have any idea?

It happened to me also.

After hours of trying, I removed the records in the database:

VIEWS_VIEW > remove the view (remember the 'vid' value of the view)
VIEWS_DISPLAY > remove all the displays with that vid


Missing Menu Links generating a Feature I am using Features that includes several basic site features such as the main menu and another custom navigation menu. Both are two level menus.  I have included the menus in the Feature, but when I select the menu links, only a few of the menu link items are included in the selection list.  The balance are missing.

What I have done:

I have searched for other issues on Drupal.org, but not found a similar one.
I have also examined the links and cannot find a difference between those that are included and those that are not.
I have flushed the menu cache.

Has anyone else seen anything like this or have any insights as to how I might fix this?

It could be this issue with features and menus, for which there is a patch: http://drupal.org/node/1283742

Something to be aware of: menu links don’t show up in the admin UI, or get added to the database, if their path does not link to an existing node.


Block value in a view row design template I have a block value which I need to access in a views row design template. I need to check the value of the block content in this template.

Does anyone know how?

You can use the following code.

$block = block_custom_block_get($block_id);
$content = $block['body'];

But be advised that it would generally contain html which would be difficult to parse.

If you are looking to store a value and then use it to check in the theme layer I would suggest creating an admin page for that and storing the value in the variables table, which you can later access by

variable_get('my_setting', 3);


Why does swiftmailer doesn't use my HTML template? In some form of my custom module, a condition triggers an email to be sent:

  public function save(array $form, FormStateInterface $form_state) {
    $entity = $this->entity;
    $status = parent::save($form, $form_state);
    $values=$form_state->getValues();
    if (($values['isurgent']['value']==1) && ($values['status']['value']==1)) {
      $iSeliste = \Drupal::currentUser()->id();
      $oSeliste = \Drupal::entityTypeManager()->getStorage('person')->load($iSeliste);
      $sSelite = $oSeliste->firstname->value . " " . $oSeliste->lastname->value;
      $sAction = ($values['action'][0]['value']==0)?"offre":"demande";
      $sDueDate = $values['duedate'][0]['value']->format("d/m/Y");
      _sendEmailForUrgentService($sSelite, $sAction, $sDueDate);
    }

in sel.module:

function _sendEmailForUrgentService($sSeliste, $sAction, $sDueDate) {
...some code...
  \Drupal::service('plugin.manager.mail')->mail('sel', 'emailforurgentservice', $sTo, 'fr',      $params);
  \Drupal::logger('sel')->info('Courriel pour service urgent : envoi effectué.');
}

my hook_mail:

function sel_mail($key, &$message, $params) {
  $sFrom = '[redacted]';
  $message['from'] = $sFrom;
  $message['headers'] = array(
    'Content-Type' => 'text/html',
    'bcc' => $params[3],
    'From' => $sFrom,
    'Sender' => $sFrom,
    'Return-Path' => $sFrom,
  );
  switch ($key) {
    case 'emailforurgentservice':
      $message['subject'] = '[Le Grenier à SÉL] Un service urgent requiert votre attention...';
      $sBody  = $params[0] . " a posté une " . $params[1] . " urgente qui est valide jusqu'au " . $params[2] . ".";
      $message['body'][] = check_markup(nl2br($sBody), 'full_html');
      break;
  }
}

The settings of mailsystem are these:

And in my theme templates folder (mysite/web/themes/contrib/mayo/templates/), there is my email template swiftmailer--sel--emailforurgentservice.html.twig:

                    Chers S&Eacute;Listes,

                    {{ body }}

                    Vous pouvez la consulter ici.";

                    Si vous ne la trouvez pas, c'est peut-être qu'elle a d&eacute;j&agrave; &eacute;t&eacute; satisfaite.";

                    --

                    Le Grenier à S&Eacute;L

The email is sent. Everything is OK (From, To, Bcc, Subject) except the body!
Instead what I defined in the template, I have only the content of $sBody as defined in function sel_mail().
Any idea what I am doing wrong?

My mistake!
I put my email template swiftmailer--sel--emailforurgentservice.html.twig in "mayo" theme which is the theme the users of the site will see.
Mailsystem was set to use "current" theme.
When I made my tests, I did it as 'user 1' and the theme when the email was triggered was "Seven" (Administration theme).
I changed the settings of Maisystem:

And it works as expected!


Problem with favicon and theme settings I'm having an insane problem enabling shortcut icon in my theme. When I dpm theme_get_setting('favicon') and theme_get_setting('toggle_favicon') - I get null strings, even though in the Shortcut icon settings section of admin/appearance/settings I have the favicon.ico as the value of the path to custom icon (obviously, the default shortcut icon checkbox is blank).

This lead me to inspecting other themes setting pages (eg. admin/appearance/settings/bartik) and I found out that all of them display a full set of options while my theme has only one checkbox. See the attachments below:

Bartik theme settings

My theme settings

Comparing the info files does not lead me to any findings.

The following is the info file of my theme:

name = SI 2012
description = SI Startup Theme
package = Core
version = VERSION
core = 7.x

features[] = main_menu

stylesheets[all][] = [...]
scripts[] = [...]

regions[offtop] = Off top
regions[header] = Header
regions[highlighted] = Highlighted
regions[help] = Help
regions[content] = Content
regions[sidebar_first] = Left sidebar
regions[sidebar_second] = Right sidebar
regions[footer] = Footer
regions[offbottom] = Off bottom

OK, problem solved. Removing the features[] line from the theme info kind of reset the settings page. I also read this post about theme settings and providing default values. Problem solved, although I don't quite know why the features[] stuff affected the whole form. Will probably learn with time.


Views filter criteria groups OR not working? I have a view with FILTER CRITERIA set. I have three groups, each joined by ANDs, with the criteria within each group ORed. The final group are two taxonomy terms, meaning I want my query to return nodes that have one term or
the other. No node will have both of the tags set.

However, when I see the SQL in the preview, the terms seem are connected by a AND.

WHERE (((node__field_event_categories.field_event_categories_target_id = '434')) AND ((node__field_event_categories2.field_event_categories_target_id = '212'))) AND ((taxonomy_index.status = '1') AND (((DATE_FORMAT((node__field_date_range.field_date_range_value + INTERVAL -14400 SECOND), '%Y-%m-%d\T%H:%i:%s') >= DATE_FORMAT(('2018-10-22T04:00:00' + INTERVAL -14400 SECOND), '%Y-%m-%d\T%H:%i:%s'))) OR ((DATE_FORMAT((node__field_date_range.field_date_range_end_value + INTERVAL -14400 SECOND), '%Y-%m-%d\T%H:%i:%s') >= DATE_FORMAT(('2018-10-22T04:00:00' + INTERVAL -14400 SECOND), '%Y-%m-%d\T%H:%i:%s')))))

This causes my query not to return any results.

I've tried removing each tid, one by one, and when one is missing I get results. So I'm thinking I should get both sets of results when they are set to OR.

To make sure I was reading the SQL correctly, I ran it through a pretty-printer:

To double check, I exported the views config, to see what the yaml said about the WHERE clause, and it all seems to be OR within the groups:

I even re-imported the configuration from this yaml, but I still get the same results.

How can I get my taxonomy criteria to function using OR?

Edit
In the course of troubleshooting, I tried to simplify the filter criteria. I removed everything, all groups and criteria. This is what I have now:

This is Drupal 8.6.2. We just updated, so I'm wondering if this is a new bug.

This answer on a related (perhaps duplicate?) issue provided settings that got the display working for me.

First, on each filter criteria, check "Reduce Duplicates".

EDIT Actually, the answer I linked says to uncheck the "DISTINCT" in the Advanced settings for the query. However, when I did that, I got duplicates. I unchecked it, and I got the right number of results. So that second step may not be necessary for you.


Tablesort with EntityQuery Inside a block plugin I'm creating a table (in Drupal8). Like so

            $header = [
                t('Name'),
                t('Number'),
                t('Rank'),
            ];
            $nids = \Drupal::entityQuery('node')
                ->extend('Drupal\Core\Database\Query\TableSortExtender')
                ->orderByHeader($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager(5)
                ->execute();
            foreach ($nids as $nid) {
                $node            = \Drupal\node\Entity\NODE::load($nid);
                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                    ],
                ];
                $rows[] = $row;
              }
            $render = [
                'table'           => [
                    '#prefix'        => '
Entries
',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];
            return $render;

Without the code below

 ->extend('Drupal\Core\Database\Query\TableSortExtender')
 ->orderByHeader($header)

the table renders just fine, but if I do include it I get the error

  Call to undefined method Drupal\Core\Entity\Query\Sql\Query::extend()

I'm guessing that it ->extend does not work on EntityQueries, but if that's the case how can I add table sorting to my table?

UPDATE: I've changed my $header array to include 'field' like so

            $header = [
                [
                    'data'  => t('Title'),
                    'field' => 'title'
                ],
                [
                    'data'  => t('Race'),
                    'field' => 'field_number'
                ],
                [
                    'data'  => t('Time'),
                    'field' => 'field_rank',
                ],
            ];

and tried adding

 ->tableSort($header)

to the query and removing extend and orderByHeader from the query but then I receive the following error

  Drupal\Core\Entity\Query\QueryException: '' not found in
  Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable()

UPDATE 2:
I tried changing the $header array to use a specifier and type property like so.

                    'data'      => t('Name'),
                    'type'      => 'field',
                    'specifier' => [
                        'field'    => 'title',
                        'column'   => 'value',
                    ],

But I end up with the same error and get an additional error

  Undefined index: specifier in
  Drupal\Core\Entity\Query\QueryBase->tableSort()

Following some of the information found in Berdirs answer and comments I was able to arrive at a solution.

I formatted my header like so:

            $header = [
                'title'      => [
                    'data'      => t('title'),
                    'field'     => 'title',
                    'specifier' => 'title',
                ],
                'number'       => [
                    'data'      => t('Number'),
                    'field'     => 'field_number',
                    'specifier' => 'field_number',
                ],
                'time'       => [
                    'data'      => t('Time'),
                    'field'     => 'field_rank',
                    'specifier' => 'field_rank',
                ],
            ],

I then performed the EntityQuery like so

            $nids = \Drupal::entityQuery('node')
                ->tableSort($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager($items_per_page)
                ->execute();

I formatted my rows like so

                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                ];

After that generating the table was easy

            $render = [
                'table'           => [
                    '#prefix'        => '
Entries
',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];

The important parts I was missing is the proper format for $header. And using ->tableSort($header) instead of                 ->extend('Drupal\Core\Database\Query\TableSortExtender')
                ->orderByHeader($header) in my entityQuery


Image field is not showing up in view/block I am currently using Drupal 7, and I am trying to get my images to be displayed in a view on the main page. So far I have created:

Created a content type containing a title, body and image field
Created two nodes that both contain an uploaded image
A view and a block that has

fields: title, nid, and image
filtered by: published and type (set to the content type I created)

When I look at my content type I can see the name, body and the image that I uploaded. When I go to the main page, I can see my view with the content, but it only shows the name and the body; it doesn't show the image.

Is there anything I can download and/or do to make this work? I just want the images to appear within the block (in my view).

check admin/user/permissions page. if you use imagecache check view imagecache permission and set it. and set view image field permission.


Translate configuration values in custom webform handler I created a Custom Webform Handler, which uses the email and name data from the form input to subscribe the user to a newsletter service through the vendors API.
Ich created a configuration form with this handler, where I can input the API key and the mailing list of the newsletter service.
This all works well up until the point where I want to translate the webform to a different language. I need to have a different configuration for the mailing list in German than in English.
I checked the code of the handlers that come with the webform module, but I can't figure out, how to define, which configuration field values should be translated. I need to have the newsletter_list form element to be translated.
Can anyone help?
This is my shortened code
<?php
/**
  * @file custom_webform_handler/src/Plugin/WebformHandler/NewsletterWebformHandler.php
  */
namespace Drupal\custom_webform_handler\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandlerBase;

// ...
/**
 * ´Newsletter Webform handler.
 *
 * @WebformHandler(
 *   id = "newsletter",
 *   label = @Translation("Newsletter Subscription"),
 *   category = @Translation("Subscription"),
 *   description = @Translation("Subscribe to Newsletter"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_IGNORED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class NewsletterWebformHandler extends WebformHandlerBase
{
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'newsletter_apikey' => '',
      'newsletter_list' => '',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['newsletter'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Newsletter settings'),
    ];
    $form['newsletter']['newsletter_apikey'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API key'),
      '#default_value' => $this->configuration['newsletter_apikey'],
      '#required' => TRUE,
    ];
    $form['newsletter']['newsletter_list'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Mailing List'),
      '#default_value' => $this->configuration['newsletter_list'],
      '#required' => TRUE,
    ];

    return $this->setSettingsParents($form);

  }
  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    // ...
  }

// ...
}

I read that I need to have a schema for doing this, so I tried adding one, but it didn't change anything
# file custom_webform_handler/config/schema/custom_webform_handler.schema.yml
webform.handler.newsletter:
  type: mapping
  label: 'Newsletter'
  mapping:
    newsletter_list:
      label: 'Mailing List'
      type: string

Edit
To make it more clear:
I created a Handler that has this configuration form

The connection settings are the ones that need to be translated
When I go to the translation page of my webform, I can translate the Email-Handler settings, but not my custom Newsletter Subscription handler settings

I did provide the wrong type. It should be label and not string
webform.handler.newsletter2go:
  type: mapping
  label: 'Newsletter2go'
  mapping:
    newsletter2go_formcode:
      label: Formcode
      type: label


How to show a teaser of the next node? At the bottom of each blog post I need to show a teaser for the next blog post. I know there is module to add links to next/prev blog. But I need to show more than a link. I need to show the title and summary. Could someone please suggest a way to achieve this?

I was able to achieve it by using the helper service defined in https://www.drupal.org/project/prev_next.


Feeds Import - Entity Reference mapping I have a "Buildings" content type. Within that content type I have a building_id field, which contains the building ID.

I have an "Employee" content type. Within that content type I have an entity reference to the Buildings content type.

I have a CSV file for employees but it does not have the building label or the node id, only the building_id.

So my issue is that when I run the employee feed import, I cannot add the building since I only have the building_id.

How would I map the building_id in my csv to match the building_id in the building content type so that it knows which building node it is referencing?

I hope that makes sense :)

Thanks!

In the past I used Views Data Export to build a spreadsheet in Views that contain the NID and the plain text field I needed to use as a reference.

Then in Excel, you can use VLOOKUP to join 2 excel files based on a common column (building_id) so  that way you can obtain the entity referenced nid you need for your import.


PHP code does not work I'm using Drupal 7.
I wrote the following code in a token field, but when I refresh the node page, it doesn't show anything.

if (arg(0) == 'node') {
  $nid = arg(1);
  $node = node_load($nid);
  $s = $node->field_name['und']['0']['value'];
  echo $s;
}

Can you advise me what I should do?

Try removing the quotes in ['0'] in the following line.

$s = $node->field_name['und']['0']['value'];


Dates to effect dynamic form behavior I want a form to display an error if someone is not 18 years old, or display the next form item if they are.

After exhausting a lot of time searching for a way to do it, I believe AJAX does not work directly on "date_select" fields. I was thinking there might be some kind of use for "#states" here.

In either case, the Conditional Fields module sounds like it could help you here... from the module page:

  Define dependencies between fields based on their states and values. Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

The alternative is harder because you'd need to write your own little module that implements hook_form_alter() that can do custom validation and insert a snippet of jQuery to hide/show elements according to the age being 18 or over.


How do I sort two different date content-types in a view? I have a view that filters two content-types (single event, and serial event) by date. The content-types have their own date-field (one with, one without date-repeat option).

The view shows all the "serial events" first, and afterwards the "single events".

How can I change this order?

Is it because I use two different date-fields?

The sort criteria are the following:

Format
Format: Unformatted list | Settings
Show: Fields | Settings
Fields
Content: single event
Content: serial event
Filter criteria
Content: Published (Yes)  AND Content: Category (exposed) | Settings AND Content: Type (in single event, serial event)  OR Date: Date (node) (Content: single event (field_serialevent)
OR Content: serial event (field_singleevent) >= now)

I am using Drupal 7.14, with the latest versions development snapshots of the Views, Calendar,  and Date API modules.

Are you sure you are only have one sort field? It sounds like you are also sorting on "Type". If you are sorting on type, make sure the "Date" is the first in the sort fields. The order of the sort fields, makes the top ones dominant.


How to allow editing a single node to a single user? I am building 500 nodes of same type with different info in them.
When I am finished, I want to give each user that will register 1 node that is already in the system, and only that user can edit or add data to that particular node.

Any suggestions about how to do so?

I would setup all those nodes as a particular content type and author. Then you could give those users a role once they register that allows them to edit their own nodes for said content type. Then you will of course need some custom code that runs at that time to find one of those nodes and change the author to the registered user so that they can edit it. Probably could the last part with Rules but you might need to use custom php to find a node and change the author.


How to check if drupal_get_messages() returns an empty array I am running drupal 6.22 with MySQL. I am trying to check if there is any error message set by using the following If statement, but with no luck.

if(count(drupal_get_messages('error',FALSE)) > 0){
...
}

When I try this condition, I get a parse error saying...

Parse error: syntax error, unexpected T_IF

What am I doing wrong here? And how do I check if there is any error message in the message queue?

What you get is a syntax error not a parse error, meaning that the code never executed, but PHP couldn't parse it. My hunch is that the problem is in the code before the if statement. One way of getting this error would be to do:

$var = 'foo' // Missing ;
if (TRUE) {
  $var = 'bar';
}

This would result in the error message you got.

A lot of things could be wrong, but when it is a syntax error, the gist of it, is that you made code PHP couldn't understand.


Is it possible to insert a value in field using Rules? How can I insert data in database using Rules?

I created entity type Job and added some fields. I want to insert values inside those fields when the flag button is clicked. I tried "set a data value" but I think it will work if I already have an existing field and value.

I also tried to use "add variable" in my Rules Action and set value on it. My question is how can I validate if it's working?

PS: I tried to look the data inside my database but I can't see it.

Before you will be able to create a Rules Action like "Set a data value" for your field, you have to make sure to add a Rules condition Entity has field (related to the field for which you want to set a value). And make sure to add that Entity has field condition BEFORE other Rules Conditions in which you might want to refer to this field (if you have any such conditions in your rule).

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

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

And to validate if your rule is working, just add a "Set a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after your executed your rule (and re-execute it). If that doesn't work (or help), use Rules debugging, as detailed in "How to debug a rule that doesn't want to fire?".


How to display the default user picture programatically? I'd like to print a user's image in a View's template file. If the user hasn't set an image yet, the default user picture (set to public://pictures/default.jpg at Configuration > People > Account settings) should be rendered.

I used the following code:

<?php $account = user_load($user->uid); ?>
<?php if (isset($account->picture->uri)) {
          $path = $account->picture->uri; }
      else {$path = "public://pictures/default.jpg"; } ?>
<?php $array = array('style_name' => 'picture',
                     'path' => $path,
                     'alt' => 'Picture'); ?>

<?php print theme('image_style', $array); ?>

That works perfectly, but I don't really like the isset approach, because it makes me think that it was redundant to specify the default image path in the configurations. Is there another method that uses the default path automatically?

It's a bit of a strangled route - Drupal itself uses some conditionals in template_preprocess_user_picture() to make that decision:

if (!empty($account->picture)) {
  // @TODO: Ideally this function would only be passed file objects, but
  // since there's a lot of legacy code that JOINs the {users} table to
  // {node} or {comments} and passes the results into this function if we
  // a numeric value in the picture field we'll assume it's a file id
  // and load it for them. Once we've got user_load_multiple() and
  // comment_load_multiple() functions the user module will be able to load
  // the picture files in mass during the object's load process.
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

If it suits your use case, you can just set the user_picture_style variable to your style name, and use theme_user_picture():

$build = array(
  '#theme' => 'user_picture',
  '#account' => $user,
);
$picture = drupal_render($build);

The caveat is that user_picture_style is a global var, so if you want to use something different for the style used elsewhere in the site, you're stuck with reproducing the same logic as the preprocess function above.


Display node's details instead of ID with relation module I have create Two node ‘Partners’ & ‘Project form’.

I used relation module & create directional relation between two nodes.

Partner’s node have following fields:

I have to select multiple partners in Project form, so I added relation widget into project form for create relation with partner’s node. Currently that field’s display partners node id as per below screenshot:

Instead of that I want to display partner’s details like (partner name-dept-country-city) & also allow to search using same string as per below screen-shot:

When you go to the reference fields there will be an option to display view as a reference option. You need to create a view and attach it there.


Views with relationship of taxonomy terms A node (Content 1) has two Tax-Terms (Category-Term 1, Category-Term2). The current relationship contains following entry: term from field_category and it's grouped via field_category.

How is it possible via a view to get this result?

Category-Term 1

Content 1

Category-Term 2

Content 1

But the current result is:

Category-Term 1, Category-Term2

Content 1, Content 1

Thanks for help. Best C

In your view FIELDS click on your Catagory field, since your category allows for multiple values, you should see the following option Multiple Field Settings, click on it to expand it:

All you gotta do is uncheck this.


How to display only some terms of a specific vocabulary in Views I have a taxonomy vocabulary (Drupal 7) called "Categories", with 6 terms: a, b, c, d, e, f

I can't see a way to create a view that will show just terms b, d, e (i.e. any sub-set of the full term list).

This seems like something that should be easy to do. Hopefully it is and I am just missing something, though an hour of searching has turned up nothing...

Any suggestions?

This can be achieve through View,

Create a view based on the Taxonomy (Strucutre->view->View settings)
Choose Page or Block View.
Select the desire fields in the field section
Add the taxonomy vocabulary ( categories) and Add term in Filter criteria, and select the Drop down, select the select the hirarchy.

Then it will show the term what you want to filter, select the b,d,e terms over there

And then, b,d and e terms only will be shown in View.


Twig theme variables I am working on creating a theme from scratch for Drupal 8 and I am 90% of the way there.  I do have a question on how to access variables in the

{{ dump() | raw }}

I have created a page.html.twig and the {{ page.BLOCKNAME }} is working great.  But when I try to place {{ title }}, or any variations, I get NULL or nothing at all.

I can see the title in the dump(), but it has ["string":protected]=> so I am not able to access. I was able to create a new block region and move the title there, but the title will not be in the same place from page to page.  I would also like to access the content type, node ID, and node url, with some other custom fields I created, but I can't seem to get to those either.

In summary, how do I use the dump() and actually get to the variables that are presented?

If you wanna see all variables available in your twig template file in Drupal 8 use {{ kint(_context) }}. Don't forget, you must enable kint in devel module settings.


Disable anonymous users on Open Atrium? first off I'm a beginner to Open Atrium, but am wondering if there is a simple way for all content on the site to require authenticated user permissions.

I'm building an open atrium 2 intranet and do not want anything but the login field accessible to anonymous users

I realize I can simply set the access permissions in every piece of content that is created, but this doesn't seem like a great solution.

If you go to http://yoursite.com/admin/people/permissions and find the "View published content" permission, uncheck it for anonymous users and that should do the trick.


How to make Drush rsync @dev @staging exclude some directories? I am using the following drush commands to synchronize development and test environments.

drush rsync @dev @staging
drush sql-sync @dev @staging

How to setup drush to exclude certain directories (such as sites/all/modules/devel ) from this synchronization process ?
I don't want devel module and some other modules to be included in staging environment and would like drush to automatically take care about this requirement.

It's not so simple like just don't send the directory.

Actually, you're synchronizing SQL and directories. If you want avoid some directories (specially modules) you should also avoid their tables and configuration sync.

The best way its, from my point of view, to sync them and after to dis and pm-uninstall them in the staging process.


Basic Drupal site architecture based on taxonomy I come from a custom web dev background but I'm working on some Drupal projects now. I am confused about the best method to set up basic site architecture. What I want is for taxonomy terms or variables to drive display of content throughout the different areas of the site. I gather I should be using taxonomies as these variables...If I am wrong please let me know

So say I have one taxonomy (BRANDS) with two terms:

BMW
AUDI

I also have three content types:

Article (can belong to multiple brands)
Video (can belong to multiple brands)
Model (only single brand)

I want to create 3 types of pages (I think what I should be doing is using views) BUT - I should only need to use ONE view per page type:

Index Page (which accepts taxonomy term and displays all videos articles and models associated with the term - this is not an individual node page) (url should be something like /BRAND eg: /BMW)

Model Page (which shows the model node - and also content [videos and articles] associated with the BRAND taxonomy term) (url should be like /BRAND/Modelnode eg: /BMW/3-Series)

Article Page (which shows an article node - and also videos and models associated with one or more BRAND taxonomy terms associated with that article)(url should look like either BRANDS/Articlenode - eg: BMW-AUDI/Articlenode or just /article/Articlenode if the taxonomy does not need to be coming from the url to feed into views or whatever generates the page content)

If i was doing a custom PHP driven website, this would be easy to do, but it's confusing as hell in Drupal. What is the standard and best practice way to go about creating each of these page types - and if it is created using views - only use one view per page type [ ie the view will accept url or internal taxonomy arguments to dynamically show content]?

You'll need to use Fields and some modules to do this but it looks like you already have the understanding on how to get started.

Fields are basically properties that can be used to extend Drupal entities. You can add Fields to your Content Types and your Taxonomy Vocabularies to include extra properties not available out of the box.

Any Fields that you want associated with your Node, add them to the Node Type. Any Fields you want associated with a Taxonomy Vocabulary, add them to the Taxonomy Vocabulary. And in the end, make sure everything is rendered correctly in your theme.

As soon as you associate a Node with a Taxonomy Term, Drupal already provides a way to display all Nodes associated with a specific Taxonomy Term. If you navigate to /taxonomy/term/TERM_ID you'll see what I mean.

If you want to modify that page, I would start looking into Views and Panels which are arguably the building blocks of any Drupal site. It is important to note though that Views and Panels are usually not used to create new content but rather to query and display, respectively, existing content.

For the URL structure you mentioned, look into the Path and PathAuto modules. They provide a way to generate URLs based on a pattern.

So, for your example, if you want a URL /BMW to show all Nodes tagged with the BMW Taxonomy Term, those two modules will get the job done for you.

So what's the best approach? It depends on your site's content. From your question:

Index Page: Classic use case for a view that takes an argument from a
URL. In this case, a Taxonomy Term. You can choose to filter on
specific Node Types, Taxonomy Terms, etc.
Model Page: Simple Node. Create a field on it's Node Type to
associate it with the appropriate Taxonomy Vocabulary. You can also use Views to pull      related content, which from your description is what you need here. There are also a lot of modules that can help with this.
Article Page: Same as above.

Good Luck!


Alter/insert into the links variable in a field_collection I am currently working with the Field Collection module, but I have stumbled into a small problem.

I am trying to alter the links variable (currently there is Edit & Delete links) on a field_collection, as I want to add a link to it. I believe I have tried everything, such as hook_entity_view_alter(), or a preprocess function, but nothing seems to work.

Is there a way to solve this, without hacking core?

In a custom module you can use hook_field_attach_view_alter(). In this example I'm using the distribution profile eRecruiter so there is a bundle called resume with several field collections and in an entity type profile2. Every time there is a field attached to a field collection this hook is fired recursively but the links are not contained there.

/**
* Implements hook_field_attach_view_alter()
*
* @param mixed $output
* @param mixed $context
*/
function helper_field_attach_view_alter(&$output, $context) {
  if ($output['#entity_type'] == 'profile2' && $output['#bundle'] == 'resume') {
    $f = 'do stuff here';
  }
}

So you understand how the links work here is some of the code used in field_collection.module.

The links are created in a render array. Don't worry about 'links__field_collection_view' too much because it doesn't do anything. When the #theme function is called more familiarly as theme('link__field_collection_view', $variables) it looks first for TEMPLATE_link__field_collection_view(&$variables) or link--field-collection-view.tpl.php however if it doesn't find it, it will use as it does in this case theme_links();

  $links = array(
    '#theme' => 'links__field_collection_view',
  );
  $links['#attributes']['class'][] = 'field-collection-view-links';
  foreach (array('edit', 'delete') as $op) {
    if ($settings[$op] && field_collection_item_access($op == 'edit' ? 'update' : $op, $field_collection)) {
      $links['#links'][$op] = array(
        'title' => $settings[$op],
        'href' => $field_collection->path() . '/' . $op,
        'query' => drupal_get_destination(),
      );
    }
  }

hook_admin_paths() is used to make the links rendered in the dialog window.

function field_collection_admin_paths() {
  if (variable_get('node_admin_theme')) {
    return array(
      'field-collection/*/*/edit' => TRUE,
      'field-collection/*/*/delete' => TRUE,
      'field-collection/*/add/*/*' => TRUE,
    );
  }
}

hook_menu() is set up for the link callback in this case the edit link

  $items[$path . '/%field_collection_item/edit'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('field_collection_item_form', $count),
    'access callback' => 'field_collection_item_access',
    'access arguments' => array('update', $count),
    'title' => 'Edit',
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'field_collection.pages.inc',
  );


How to create a module wide variable that refreshes every page load? What is the best way to create a variable that is accessed by the different views of my module (block, page etc), but that is destroyed at every new page request?

I've been using variable_set to store information that is used throughout my module, but this seems to persist across page requests.  Is there a hook I can implement to call variable_del for every outgoing page, or is there a better way of storing variables in my module that do not persist across page loads?

The variable_set() and variable_get() functions are made to set/get a persistent variable. So they should not be used to persist data within a single page request. The drupal_static() function is made for this task and is well documented. Off course, you could also go with a static variable without bothering about drupal_static(). But drupal_static() will make your code more maintainable and future proof.

/**
 * Set or get the shared foo variable.
 *
 * @param $new_value
 *  (optional) If set, the new value to assign to the foo variable.
 *
 * @return
 *  The value of the foo variable. If $new_value is set this would be
 *  the previous value.
 */
function MODULE_foo($new_value = NULL) {
  $value = drupal_static(__FUNCTION__, NULL);
  $previous_value = $value;
  if ($new_value !== NULL) {
    $value = $new_value;
  }
  return $previous_value;
}