How to change the title of breadcrumb? I have a route that renders a node. Unfortunately in the breadcrumb the route title is rendered rather than the node title. When I preprocess in hook_preprocess_breadcrumb() inside my module only the preceding links are available inside $variable (not the current route title).

However, if I go to do hook_preprocess_breadcrumb() in my theme, the route title is inside $variables. So I could change it there but I want the functionality to be encapsulated inside my module, not split between module and theme.

I tried to create my own custom breadcrumb builder but I don't want to build it from scratch as there is some complex functionality built by other developers. I want to get the current breadcrumbs and then just replace the last one (the current page title) with my own.

I tried hook_system_breadcrumb_alter() as well but again the current page title is not showing up in variables inside my module.

<?php

class DefaultProductListBreadcrumbService implements BreadcrumbBuilderInterface {

  /**
   * Whether this breadcrumb builder should be used to build the breadcrumb.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   *
   * @return bool
   *   TRUE if this builder should be used or FALSE to let other builders
   *   decide.
   */
  public function applies(RouteMatchInterface $route_match) {
    // TODO: Implement applies() method.
    return true;
  }

  /**
   * Builds the breadcrumb.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   *
   * @return \Drupal\Core\Breadcrumb\Breadcrumb
   *   A breadcrumb.
   */
  public function build(RouteMatchInterface $route_match) {
    // TODO: Implement build() method.

    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

    return $breadcrumb;
  }

}

For reference, I'm using bootstrap as the base theme with multiple sub themes (it's a multisite). I can't find anywhere that's adding the page title in the theme. I'm also using easy_breadcrumb module but I checked there and the page title is also not shown there.

You could use a title callback, like for example this one from the core node controller:

\Drupal\node\Controller\NodeViewController::title

  public function title(EntityInterface $node) {
    return $this->entityManager->getTranslationFromContext($node)->label();
  }

Your title callback would have other route parameters, so that you can find the correct node, see also https://drupal.stackexchange.com/a/248687/47547.

When using the default option in the Bootstrap theme to display the page title you might need to add cache metadata to the breadcrumb, see Breadcrumbs are cached, which depends on how you determine the node to display.


CKeditor is not working with jquery > 1.8 I'm trying to get superfish accordion working on my pages. I have to have my jquery_update set to 1.9 or greater to get that function working.

But when I do I lose ckeditor on the comment fields for things like forums and such. I'm not sure what to do to resolve this problem.

Currently running Drupal 7.53

CKEditor for Drupal module 7.x-1.17

Superfish menu module 7.x-2.0

Okay, this may have been the cause.

I use AdaptiveTheme for my base theme on everything really. Right now the default theme makes use of a FooTheme created with a Corolla base. I had menu setting in the theme turned on and I think it was interfering with the Superfish menu.

If you are using Superfish then turn off all mobile menu options in AdaptiveTheme.


How can I execute jQuery within a *Basic page* content type node? I would like to run some jquery within a Basic page content type node and the only place that I can place this code is within the Body section when within the Edit Basic page.
After placing the following at the bottom of the Body section like the below:
jQuery(window).unload( function () { alert("Bye now!"); } );

It errors off so that it appears that it does not have jQuery included within this content type.
I tried putting a link to Jquery before calling jQuery but the link to it also errors off.
How can I execute jQuery within a Basic page content type node?

I am not sure, but You can try to change filter to Full HTML, or the second method, create template file for that content type like node--NAMEOFNODETYPE.tpl.php and clear cache and put your javascript code inside it.

example:

<div>
     // Here YOUR JAVASCRIPT CODE
     <?php print render($content['body']); ?>
</div>

Or another method, in template_preprocces_page you can check: for all nodes by one type - just check:

$node = menu_get_object();
if($node->type == "your type") {
  drupal_add_js('YOUR CODE', 'inline');
}

for only one node by nid:

$node = menu_get_object();
if($node->nid == YOUR NID) {
  drupal_add_js('YOUR CODE', 'inline');
}


Attaching Entities to other Entities I have two custom entities in a D7 site. One is 'additional' data on an entity, and I want to attach that data to the main entity every time it is loaded.

Within Entity/Entity API, how can I do that correctly? attachLoad sounded correct but seems to be Field related, all my data are not fields (yet).

I've seen modules use attach load as well, which is what you need to get it on the actual entity.

It also depends on your data structure if the base entity has a reference to the additional data entity, you could simply use the entity wrapper along with entity properties. You wouldn't actually have the data on the entity, but have it accessible via the wrapper. The advantage is that you only run extra queries (loading the entity) as required.

In code you would then do

 $entity = load_entity_function($foo);
 $enity_wrapper = entity_metadata_wrapper('entity_type', $entity);
 $additional = $enity_wrapper->addition->value();
 $additional_id = $enity_wrapper->addition->id->value();

In order to have the wrapper do this, you tell it about the additional entity in a hook:

/**
 * Implements hook_entity_property_info().
 */
function module_entity_property_info() {
  $info = array();

  $properties = array();
  $properties['additional'] = array(
    'label' => t('Label'),
    'type' => 'entity_type',
    'description' => t('description.'),
    'getter callback' => 'function_get_entity_id',
    'setter callback' => 'function_set_entity_id',
    'clear' => array('id_of_additional'),
    'schema field' => 'schema_of_additional',
  );

  $info['base_entity']['properties'] = $properties;

  return $info;
}

You need a function that will get or set the id from the entity. Depending on your naming convention entity modules come with some that you can use.


How do I pass a URL to a route? I need to send the URL of a Drupal 8 route to a template. I read some documentation on Drupal API, but when I implement this in my module, nothing happens.

My route in my routing file looks like the following.

movies.addMovie:
    path: /movies/add/{system}/{id}
    defaults:
        _controller: 'Drupal\movies\Controller\InsertController:addMovie'
        _title: 'Add Movie'
        system: ''
        id: ''
    requirements:
        _permission: 'create movies_movie'

This is the code I am using to get the URL from the route.

use Drupal\Core\Url;
Url::fromRoute('movies.addMovie')

When I put the URL in a variable, the code stops when calling Url::fromRoute(). Can someone tell me what I'm doing wrong?

should be:
InsertController::addMovie

Needs a double-colon.
Yours is single.


How do I use CCK fields with the form API? Does anyone know how to use OpenLayers CCK fields with the form API?
I want to get a coordinate and some other data from users in my custom form.

I believe in this case you want to create a new content type with the appropriate cck fields to collect the location data. This will be much, much easier than trying to recreate the same experience with the forms api, custom tables and some custom module to integrate CCK fields.


How to avoid Exif data rotating images automatically during approval selection? I've been doing some digging, but so far with no results. I'm currently looking for a way of forcing or letting the admin to dictate the orientation of an image. I came across an issue where some user uploaded content looked correct upon initial upload, but when the admin began the approval process, the files hidden orientation data changed it from a vertical to a horizontal orientation. Now mind you I know that I could simply re-save that file, pull down the submitted post data and re-upload with the correct image, but I'm trying to be as efficient as possible in the event someone outside myself is administrating the content one day.

Has anyone come across a module that could help force orientation away from EXIF content or other data?

Thanks in advance!

Once you've set up ImageMagick you can start using it in a file hook to process your images on upload.

Some good hooks to look at would be:

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_file_presave/7

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_file_insert/7

Watch for an image being uploaded, read exif data with imagemagick, adjust accordingly.


Add a link to the Module list page In a Module list page (admin/modules) , We could see help, permission or configure links in Operations column. and also Module Filter customize it as a dropdown for each module listed.

Now I need to create a new link in that operations for every module installed. How should I do it?

I think I should go with hook_page_alter() but don't know how to start with since the $page array of admin/modules page is too long.

The system_modules() form is the one that provides that module list.

You can form alter that in a custom module like so:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_system_modules_alter(&$form, &$form_state, $form_id) {
  // Loop through the array of module packages.
  foreach (element_children($form['modules']) as $package) {
    // Loop through the array of module rows for each package.
    foreach (element_children($form['modules'][$package]) as $module_filename) {
      // Add an extra operation link for each module row.
      $form['modules'][$package][$module_filename]['links']['new_operation_link'] = array(
        '#type' => 'link',
        '#title' => t('Link text'),
        '#href' => 'link/url',
        '#options' => array(
          'attributes' => array(
            'class' => array('module-link', 'module-link-configure'),
            'title' => t('Link hover text'),
          ),
        ),
      );
    }
  }
}

Note that you need to change MODULE_NAME to the name of your module and you have the change the link key, text, url, etc. to meet your requirements.

[EDIT]
I have now tested it and it works.
Here is a working example with the placeholder values changed to make a link to google.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_system_modules_alter(&$form, &$form_state, $form_id) {
  // Loop through the array of module packages.
  foreach (element_children($form['modules']) as $package) {
    // Loop through the array of module rows for each package.
    foreach (element_children($form['modules'][$package]) as $module_filename) {
      // Add an extra operation link for each module row.
      $form['modules'][$package][$module_filename]['links']['google'] = array(
        '#type' => 'link',
        '#title' => t('Google'),
        '#href' => 'http://google.com',
        '#options' => array(
          'attributes' => array(
            'class' => array('module-link', 'module-link-google'),
            'title' => t('Go to google'),
          ),
        ),
      );
    }
  }
}

You can also use relative internal links instead of the external google link above.


add #ajax property to email field in node add form usion hook_form_alter I've tried to add the property "#ajax" to email field but It dosen't work,
I've tried all this :

$form["field_user_email"]['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );

$form["field_user_email"]['und']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );
$form["field_user_email"]['und'][0]['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'usercheck',
      'effect' => 'fade',
  );

If the field is provided by the Email Field module it'll probably be:

$form["field_user_email"]['und'][0]['email']['#ajax'] = array(...

If it's just a standard text field it will be:

$form["field_user_email"]['und'][0]['value']['#ajax'] = array(...


How to Create a Image Field Template I've made a image field template called

"field--field-image.tpl.php"

This has override the image field.
But how do I get the image to display

<img src="<?php print render($item); ?>" alt="..." class="img-rounded">

Many thanks for your help

Quick and dirty, if all you are wanting to accomplish is to add class="img-rounded" to the <img> tag, you could do this right before you render $item:

<?php $item['#item']['attributes']['class']='img-rounded'; ?>

(Quick and dirty because this assumes no one else somewhere along the line has added or will be adding a class to your image.)


How to check if an entity is referenced before deleting? Is there a module or a way to use Rules to make sure that a parent node isn't referenced by a child node before deleting the parent?

In my case the children require a parent to be created. However if the parent gets deleted, the children all get screwed up.

(Entity)Reference Field Synchronization module should be able to help:

Having 2 Entity reference fields pointing back at eachothers entities, they can be set to be updated so that if an entity A with field 1 references to an entity B with field 2, entity B automatically points to entity A.
This is very helpful when you need to be able to reference from any entity, and not just be able to perform back reference queries (as provided by Entity reference).

Just add an synchronized reference field to a parent, and on delete test if it has values or not.
Also, see this feature request in Entity reference issue queue.


How do I add attributes to a single menu's links? I want to add some BEM classes to a single menu's links. I cannot find a way to do this in Drupal's GUI so I assume this must be done programmatically.

How would you go about this exactly? I've no idea what file any function would even go on...

You might try the Menu Attributes module.  This looks like it will do what you want.


Is there any way to add the social medial buttons in a field? I have made the field using field collection which is collection of 7 fields and the 8th field I would like to add as strip of social media buttons (like easy social module).

So when the entire content is displayed, below each set of field collections the social media button appears.

I searched and found that all social modules can be attached to content type which adds at the top of content or bottom. But is there a way where it can be added in-between the text or using CKeditor, the above issue can be solved?

You can use the Link icon module.

  The Link icon module is a simple link field formatter to create icon
  classes based on a predefined set of link titles.

Or the Social field module

  The Social field module provides a field that allows you to collect
  links to social network profiles like facebook, twitter, googleplus,
  linkedin, etc. Links are shown as icons. Social field links are
  validated according to the patterns inserted in the module
  configuration.


How can I add the sku code in [commerce-order:commerce-email-order-items] While the shortcode [commerce-order:commerce-email-order-items] is used to send several commerce emails, it does not includes SKU code. How can I add sku code or edit the output of [commerce-order:commerce-email-order-items]

Some tokens are generated by code others by views. This token is generated by code

So edit commerce_email.module and around line 420 you will see commerce_email_order_items function here you can add the sku.

Take in mind that this is not an ideal solution See hook_tokens_alter


How does the internal entity cache work? The internal entity cache is interfering with display modes on my site.  I have a view that is displaying a node with a custom display mode, 'slideshow'.  When I look at the view from a page that displays the entity in a different display mode along side the slideshow block, the node is rendered as that mode and not slideshow, but the other nodes in the block display using 'slideshow'.

hacking core, and rewriting node.module:

node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE)

to

node_load_multiple($nids = array(), $conditions = array(), $reset = TRUE)

resolves the issue.  Under performance, caching is on for anonymous users.  This is occurring while logged in.  I've tried entitycache in the past, but it is not installed.  Drush cc all does nothing.  I'm open to any ideas that may help.

Here is the offending part of a backtrace that I managed to pull up:

It looks like somewhere in theme.inc the wrong template is being chosen:

10 (Array, 4 elements) file (String, 52 characters )
/home/mysite/git/mysite/includes/them...
/home/mysite/git/mysite/includes/theme.inc line (Integer) 1185
function (String, 21 characters ) theme_render_template | (Callback)
theme_render_template();
args (Array, 2 elements)
0 (String, 70 characters ) sites/all/themes/mysite/templates/ds/ds-...
  sites/all/themes/mysite/templates/ds/ds-1col--node-post.tpl.php
1 (Array, 86 elements)

It only affects the node being rendered currently, which isn't a post and shouldn't be using that template when it shows up in the slideshow block.  I've grepped around for theme_hook_suggestions but haven't found any.

---EDIT---
I've tracked it down to this code in views:

 function pre_render($values) {
    $nids = array();
    foreach ($values as $row) {
      $nids[] = $row->{$this->field_alias};
    }
    $this->nodes = node_load_multiple($nids);
  }

  function render($row) {
    if (isset($this->nodes[$row->{$this->field_alias}])) {
      $node = $this->nodes[$row->{$this->field_alias}];
      $node->view = $this->view;
      $build = node_view($node, $this->options['view_mode']);

      return drupal_render($build);
    }

For what ever reason, node_load_multiple is returning the current node being viewed with the type set to 'post', instead of the correct content type.  Why would there be malformed nodes in the site's internal cache?

node_load_multiple() is using entity_load() and should not interfere with the rendering of your node because it only handles the loading from database, not rendering.

The node controller is the DefaultEntityController which implements a static cache, which (as of code) does not respect conditions used by loading. This might interfere. Are you using special conditions here? how does the $conditions array look like?

Are you using views to render that specific page? then it could be problem with contextual arguments and caching see: How to get Views caching working with contextual filters?


In image_link setting, How can I change "content" to the specific node The example in API show that 'image_link' => 'content', How can I change "content" to the specific node. This is my code in basic page:

$node = node_load($nid);
$image = field_get_items('node', $node, 'field_pg_image');
$output = field_view_value('node', $node, 'field_pg_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
  'image_style' => 'thumbnail',
  'image_link' => 'xxxxxxxxx',
),
));
print render($output);

I would like to change 'image_link' => 'xxxxxxxxx' to "node/30?ptype=20"; How to do this

keep

'image_link' => 'content',

and after your code, before print:

$output['#path']['path'] = "node/30?ptype=20";


Installation profile - Can I create nodes via yml files? What's the best practice for it? I've created an installation profile for Drupal 8, which creates content types, taxonomies, blocks and stuff I need for new projects via yml files. Now I also want to create some default nodes.

I could use hook_install() or the module "default content" to create some nodes, but I'd like to know, if there is a better way for it.

Since we can create content types, taxonomies, blocks, etc. with yml files, I was wondering if it is possible to also create nodes with it.

So my questions are:

Is there a way to create nodes via yml files?
What would be the best practice for it?

That's exactly what the Default content module was built for:

  Default content gives your module and install profile a way to ship default content as well as configuration.

I'm not sure it supports YAML, but definitely JSON and others, so it's basically the same thing.

The docs can be found here.


What is a good flexible way to send auto system emails to users? I would like to know a good user friendly, easy to setup and flexible way to send automated emails to users. This will be in response to an event triggered by a user. I guess it does not matter what it is for. Just need a good way to send system emails, which is widely used.

I think the most easy and user friendly way for you is to use Rules module.

EXAMPLE:
Create new rule

Add action

Follow next steps to set your mail.


Is there a way to allow an authenticated user to add to another users post? I have a content type that uses a field collection field and I would like for one user to create the initial node, then have other users able to add field collection entries after it has been submitted. Do you have any suggestion?

You can use the Content Access module to give the users permission to content level.


How to let a user change their own username? I can't seem to figure out how to let users change their own username. I'm running Aegir with about 10 Open Atrium sites. With permissions I've checked "change own username" for the master Aegir site, as well as the Open Atrium sites. For giggles, I enabled every role to "change own username"..

But when I try to change my username in OpenAtrium and click save, it confirms "changes have been saved", but the username doesn't actually change.  This has ballooned into a huge issue for us.  I'm hoping there is some obvious dumb thing I need to do.  Thoughts?

Changing a username inside a hosted site is completely up to the OpenAtrium Drupal installation.
Aegir does not usually interact with this.

I just verified that it works OK on a clean Aegir 3 install with a standard Drupal site.

So @Bisonbleu's comment seems correct:

  That's done in permissions. In Drupal 7, go to admin/people/permissions and look under User: Change own username.


How to prolong time of displaying of images in carousel slideshow I use Bootstrap 3-based Drupal 8 theme (Jethro). In the header, I have carousel of sliding images. They change every 5 seconds. I'd like to prolong this time to e.g. 30 seconds, so that every image is displayed for 30 seconds, not 5. So far I found only how to change speed of the change, animation, which is not the task. Any idea how to do it?

What I tried

In bootstrap.css and bootstrap.min.css:

.carousel-inner .item {
  ...
  transition: 30s ease-in-out left; # Increase time here
  } # Together with below it makes sliding slower, nothing more

and in bootstrap.js and bootstrap.min.js:

this.interval = 50000 // It does nothing
interval: 5000 * 10 // In Carousel.DEFAULTS; it makes sliding slower

Comparing with w3schools example (specifically line <div id="myCarousel"...) - inserting data-interval="30000" there (the line then looks like
) does the trick.

In the Jethro theme (and probably in any similar case), this backbone is in the file templates/page.html.twig (in version 2.0 line 85). So that inserting data-interval="30000" there does the trick. The line then looks like
. Might be this is not the most elegant way, but it works well.


How to import title, description and image from website I would like to have a "Facebook style link commment" feature in Drupal 7. When you enter a URL it will pull the page title, first 100 characters of the main website text and an image.
There is a module called "Facebook Style Micropublisher" but it's Drupal 6 only.
Any other ideas on how this could get accomplished?

The manual way to do it is to create a custom module that uses drupal_http_request to download the remote URL, then parse through the resulting data to pull out any images, a summary, and the contents of the title tag.

This is a lot harder than it sounds because manually parsing HTML is actually pretty tricky. If you must take this approach, try using simplexml or a library that tries to simplify things for you.

A better approach might be just porting the Drupal 6 module yourself - it's probably less work and you could contribute your code back and possibly get patches from other contributors.


How can I disable account settings? I am using Drupal 6 with the OpenAtrium distribution, and I'd like to completely remove the account settings menu. In other words, I don't want users (or, even better, certain users) from access account settings. I know that it can be done by hiding the menu via CSS, but I am looking for some kind of module that can make it easier.

EDIT:

Ok what I did was creating and activating a new module called disablepermissions:

function disablepermissions_menu_alter(&$items){
     $items['user']['access callback'] = FALSE;
     $items['user/%user/edit']['access callback'] = FALSE;
     $items['user/%user']['access callback'] = FALSE;
}

This actually works as intended but if I try to set some kind of permissions I only get a blank page with a 500 Internal Server Error, why? The following code does not work...

function disablepermissions_perm() {
    return array('visualizza utenti');
}

function disablepermissions_menu_alter(&$items){
     if (access_user('visualizza utenti') {
     $items['user']['access callback'] = TRUE;
     $items['user/%user/edit']['access callback'] = TRUE;
     $items['user/%user']['access callback'] = TRUE;
     }
     else {
     $items['user']['access callback'] = FALSE;
     $items['user/%user/edit']['access callback'] = FALSE;
     $items['user/%user']['access callback'] = FALSE;
     }
}

You could use hook_menu_alter(). Something like this should work:

function yourmodule_menu_alter(&$items){
  $items['user/%user_category/edit']['access callback'] = 'yourmodule_user_custom_access_function';
}

function yourmodule_user_custom_access_function($u){
  return user_access('administer users');
}

This way, only users with "administer users" permissions will be able to edit user informations.


Adding icons to field labels How do I add icons next to field names, like adding a phone icon in front of the mobile phone field?

i tried the patches shown in https://www.drupal.org/node/2050257, but they do not seem to work.

I have seen this on some websites, so I guess it should be possible.

You can change the label using the template_preprocess_field hook.

For instance, if your field was named "phone" and the content type was "business", you could add this to your template.php:

template_preprocess_field (&$variables) {
  $content_type = $variables['element']['#bundle'];
  $field_name = $variables['element']['#field_name'];

  if ($content_type == 'business' && $field_name == 'phone') {
    $variables['label'] = '<img src="http://www.carloancentre.ca/wp-content/uploads/2014/03/Contact-Methods-Phone-icon.png" height="16" width="16"/>' . $variables['label'];
  }
}


Create control panel for drupal 7 site When i use drupal 6, i install control panel module and change panels  and authenticated users can goes to control_panel page and manage contents,pages and site.
but this module is not available for drupal 7.

my question is  how do you create a management page for your site in drupal 7 ?

Do you use another module or  add some php code to page and create this page manually?

Another possibility: You could create a taxonomy (vocabulary) for your administrative features and use that with Taxonomy Menu. Add an image field to your terms with icon.  Or, just use Views to create your custom menu -- you'll be able to use your taxonomy term images there.


Rule with if statement prevents users from saving their user account I have set up a rule that is causing some odd behaviour.

The event of the rule is: "After updating an existing account"

However the rule is preventing the user to save the data of his particular useraccount.

Allthough drupal says "The changes have been saved." non of the filled in data of the useraccount is saved.eg password etc

It looks like the second condition (If: NOT Data value is empty) is causing the bug.
However i dont know what the alternative should be.

Thanks

Here my rule:

{
  "rules_if_oginvite_redirect_to_oghome_after_userpagesave_and_remo" : {
    "LABEL" : "If registered by mail redirect to oghome or mypage",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Redirect" ],
    "REQUIRES" : [ "rules", "rules_conditional", "php" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2", "4" : "4" } },
          "operation" : "OR"
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "user_remove_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "4" : "4" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is_empty" : { "data" : [ "site:current-user:og-membership--1" ] } },
            "DO" : [
              { "php_eval" : { "code" : "global $user;\r\n$uid = $user-\u003Euid;\r\n$result = db_query ( \u0022SELECT * FROM {og_membership}\r\nWHERE etid = :uid\r\nand entity_type = \u0027user\u0027\r\norder by gid DESC\u0022, array (\u0027:uid\u0027 =\u003E $uid ) );\r\n\r\n\/\/ get the results\r\nforeach ( $result as $row ) {\r\n\/\/ Do stuff with $record, which is an object\r\n$gid = $row-\u003Egid;\r\nbreak; \/\/get the latest one by breaking here\r\n}\r\n$_SESSION[\u0027ses_user_group_gid\u0027] = $gid;" } },
              { "redirect" : { "url" : "\u003C?php print \u0022node\/\u0022.$_SESSION[\u0027ses_user_group_gid\u0027];  ?\u003E" } }
            ]
          },
          { "ELSE" : [ { "redirect" : { "url" : "mypage" } } ] }
        ]
      }
    ]
  }
}

As an observation I would advise against using PHP directly in a rule if it can be avoided. Much better to put your logic into a custom action and call it.

But looking at the code you supply, you should note that the user account referred to in the rule and the global current one need not be the same (an administrator may edit someone's profile, for example). You should be using the account passed in to the rule throughout, not site:current-user. Also the user update condition, IIRC, may be called when a user object is saved in other circumstances than a profile edit, so the redirect won't be appropriate.

So in order to be sure the user is editing their own profile, you should add a condition to the rule which compares the account's uid to that of the current user to make sure they are the same.


basic difference between Date, Date(ISO format), Date(Unix timestamp) to create a field I have created a field as field type Date(Unix timestamp).

When i edit a content with some input value in the above created field it shows an error like below:-

PDOException: SQLSTATE[01000]: Warning: 1265 Data truncated for column 'field_reprisal_date_value' at row 1: INSERT INTO {field_data_field_reprisal_date} (entity_type, entity_id, revision_id, bundle, delta, language, field_reprisal_date_value) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 258985 [:db_insert_placeholder_2] => 245170 [:db_insert_placeholder_3] => embedded_video [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 2015-03-02 ) in field_sql_storage_field_storage_write() (line 494 of /www/d7yourtango/modules/field/modules/field_sql_storage/field_sql_storage.module).

But after deleting above field again i create another field as field type Date and i process same, it work.

So my question is why it happening so for 1st case?

And what are basic difference between field types of Date, Date(ISO format), Date(Unix timestamp) to create a field.

Below explains three field types in details

Date

Called a 'datetime' field type in techno database speak. This format type is recomended for most installs because it takes advantage of the database's date handling functions without any conversion, which means faster queries.
Stores the date in the database's native date format (YYYY-MM-DD HH:MM:SS).
The data is in a human-readable form.
You can use it for incomplete dates, i.e. only a year or only a year and a month, and pad the other values with zeros, so it does not appear to be any more precise than it really is.

Date (ISO Format)

Stores the date in an ISO format (YYYY-MM-DDTHH:MM:SS).
The data is in a human-readable form.
List You can use it for incomplete dates, i.e.
only a year or only a year and a month, and pad the other values with
zeros, so it does not appear to be any more precise than it really
is.
It is a format that is internationally-recognized, and it is used
as-is on many web sites and in many applications.

Date (Unix Timestamp)

Stores the date as an integer.
Takes up less room in the database because it's smaller.
Often easier to use for date calculations because you can increase or decrease it just by adding or subtracting seconds.
It is the format used by php date functions.
It must be filled with a complete date -- year, month, day, hour, minute, second, so you sometimes have to arbitrarily set some of these values even if they are not applicable.

Taken Reference from Here


Call to a member function label() on a non-object in entity module I created an entity type using Entity API and made it exportable. The export link works properly but on Import I have this error:

  Fatal error: Call to a member function label() on a non-object in [...]\sites\all\modules\entity\entity.module on line 903

I couldn't find any reason.
Here's my hook_entity_info():

$return = array(
  'event' => array(
    'label' => t('Event'),
    'entity class' => 'EventClass',
    'controller class' => 'EventController',
    'base table' => 'calendar_events',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'eid',
    ),
    'load hook' => 'events_load',
    'view modes' => array(
      'full' => array(
        'label' => t('Default'),
        'custom settings' => FALSE,
      ),
    ),
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'module' => 'events',
    'access callback' => 'event_access',
    'exportable' => TRUE,
    'admin ui' => array(
      'path' => 'admin/structure/events',
      'file' => 'events.admin.inc',
      'controller class' => 'EventsUIController',
    ),
  ),
);

Tell me if you need more information.

[EDIT]
I figured that the error has been occurred in entity_class_label($entity) in sites/all/modules/entity/entity.module:903. I printed the content of $entity and it seems it is NULL!
Why is it NULL?

It looks like this is a bug in the Entity API module.

An issue with exactly the same error message was reported here to do with the Profile2 module (which uses Entity API pretty heavily).

The upshot of that post is that the problem is an Entity API bug, details of which you can see at: Load reference field when building contents.

As you can see from the above there are patches available to fix the problem. The most recent patch that passed testing was on the 16th November 2011.

When you look at the Entity API module's latest stable release you can see it's date sas the 10th November 2011. This means that the patch probably hasn't made it into the stable version yet, so won't have been fixed in your version of the module.

There are two things you can do:

Upgrade to the dev version of the Entity API module (of course the usual amount of caution should be taken and you probably won't want to do this for a live site).
Apply the patch to the entity.controller.inc file that seems to have solved the problem for other users.


How to get the revisions list of a node and delete them all? Revisions and how to delete them all. For Drupal 7, there’re plenty of modules that do that or even limit the revisions that are kept or even delete everything that is older then x-days, but not for Drupal 8.

It seems there is nothing out there. Searching through the database is something I like not to do.

Any ideas?

Yes, as you says there is a list of modules that can do this in Drupal 7 like:

Node Revision Delete

  The Node Revision Delete module lets you to track and prune old
  revisions of content types. Define the max amount of revisions to keep
  per content type. Run on Drush, cron run or on a different period
  (daily, weekly, etc).

Node Revision Restrict

  The Node Revision Restrict module allows you to restrict revisions of
  node for each content type. This module has an admin interface to
  specify node revision threshold for each content type available. The
  possible setting include node type with corresponding revision limit,
  provided on the Node Revision Restrict configuration form. Note that
  this module does not and cannot delete the current revisions of a
  node.

Node Revision Cleanup

  Node Revision Cleanup is designed for really big databases. And site
  administrators who are comfortable with Drush. The concept behind this
  module is to be able to run multiple invocations at the same time, via
  Drush to maximize the number of node revision deletions per second.

Revision Deletion

  This modules enables the ability to mass delete aging node revisions.
  Possible settings include node type, the age of node revision before
  being deleted, along with a Cron frequency setting. The revisions may
  be deleted after review on an administer page as well. This module
  will NEVER delete the current revision of a node, nor will it allow
  you to do so.

And for Drupal 8, well at this moment there is not module for do that, but you can use:

To get the revision list of a node:

$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);

See Nodes now have a storage controller; node_revision_list() removed.

To delete a revision revision you can use the node_revision_delete() function, but at the end see the function code:

function node_revision_delete($revision_id) {
  \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
}

So, is better if you just use:

\Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);


Abstract submission with COD I would like to be able to let people submit abstracts with the Conference Organising Distribution. Is there a way already implemented? I did not see this.

The idea would be that people can enter information about themselves, the abstract and upload the tex file and select the session/track that they want to present in.

AND that we can approve the abstracts and add them to the schedule.

Is there an easy way for this? Seems like a pretty (academic) conference requirement.

Thanks!

this question was cross-posted on drupal.org and it got an answer there.
it basically explains that session submission is meant for this.


How to allow integer and decimal fields with default values to be saved as empty. If I set a default value on a decimal or integer field, the user cannot delete the default value and save the node.

They can set the value to another value including zero, and that is saved correctly.

But if the contents of the field is deleted, on save, the field is automatically populated with the default value again.

This doesn't seem right.  I guess I could intercept the empty field and set it to zero, but surely that's not necessary?  Am I missing something?

This is a bug in D7. Checkout https://www.drupal.org/node/1253820. I checked it works while editing content but not while creating. This has been fixed in D8. For D7, you can write custom code to handle this.


jCarusel + colorbox, show one thumbnail and open different image I have a jcarousel view, a colorbox, and content type that have two fields: thumbnail and full_image. This is because I don't want to be depend on Drupal scaling/cropping . I would like to show thumbnail in jcarousel and after click - open full_image.

In Views there is "Colorbox trigger" field, so I first loaded two hidden fields of both images, and then "Colorbox trigger". I set thumbnail as trigger field, and token of full_image as popup content but it doesn't work (after click, resized thumbnail appears). I feel that I'm just missing something obvious but I'm not sure what. Or maybe is this more complicated?

Ok, I figured this out and I'm putting answer here for future generations. I realized that my invisible Thumbnail field had set colorbox as formatter. It was blocking Colorbox trigger from working. Silly trap, I hope someone will be able to avoid this mistake because of this.


Converting the login / register / password reset tabs into three different pages? I want to separate the user account menu tabs structure into an individual page layout.

For short I want to remove the tabs, I know that the pages are different.

Snapshot attached.

What I have done so far is trying to use the theme suggestions but couldn't get any closer.

I get to know that it's being rendered from:

  themes/bootstrap/templates/block/block--local-tasks-block.html.twig

You could create different twig templates for that three pages and remove the local tasks from the display. Depending on your theme, it may also be sufficient to just disable the "tabs" block on these three pages. Then you'd create a custom menu (and block) with these three links in it and display it where you need it.


Using tokens under exposed views filter I have created a view with an exposed filter. In my display I have an Using tokens section that I do not want to display:

Using the theme developer this is the closest I can get to it:

So it seems to part of views bulk operations. How can I get rid of this text?

I needed to overide a function in my template.php in my theme:

function blogbuzz_views_bulk_operations_fields_action_form($form) {
  $output = '';
  $access = user_access('Use PHP input for field settings (dangerous - grant with care)');
  if ($access && $form['#settings']['php_code']) {
    $output .= t('
Using the Code widget

Will override the value specified in the Field widget.

Should include &lt;?php ?&gt; delimiters.

If in doubt, refer to devel.module \'Dev load\' tab on a content page to figure out the expected format.

', array('@link_devel' => 'http://www.drupal.org/project/devel')
    );
  }
}


How to get a node content programmatically? I am writing a module, in which I am required to display contents from multiple nodes. Using the configs I save, I will get the node id's in hook_block_view. Using that is there a way to get the contents of the particular node, so that I can manipulate on that?

Assuming by 'contents' you mean the HTML for the node in a particular view mode, you're looking for node_view():

  Generates an array for rendering the given node.

e.g.

$node = node_load(1);
$view = node_view($node, 'full');
$rendered = drupal_render($view);


how to display a media description in a twig template? i want to display the media description available in the file field of a media ( media of type video, audio, image, etc...), it is an option to activate:

Enable Description field
The description field allows users to enter a description about the uploaded file.

i already print other fields that i want in the media twig template, but i can not find the value of that "description" field attribute, because it's not a field, but some sort of attribute of the file field.

I got the media description in the preprocess
function template_preprocess_media(array &$variables) {

  $bundle = $media->Bundle();

  if($bundle == 'file') {
    $field_media_file = $variables['content']["field_media_file"];

    if($field_media_file[0]["#description"]){
      $desc = $field_media_file[0]["#description"];
    } else{
      $desc = $variables['name'];
    }
    $variables['description'] = $desc;
  }
}


CKEditor Font Size and Family buttons does not appear I tried to install CKEditor Font Size and Family on my fresh Drupal 8 install, but both buttons does not seem to show up.

Plugin is placed in /libraries
CKEditor and CKEditor Font modules are both activated
Both buttons S and F appear when I edit my content format (Full HTML)
Both buttons were added to the Full HTML CKEditor toolbar
My content use Full HTML format, and I am administrator
But these buttons does not appear when I edit my content

This problem is still here after a few days of development, so I'm already sure it's not cache-related.

Did I miss something in my configuration?
Thanks

For me, I put the center, left, and right align buttons in my "TOOLBAR CONFIGURATION".  But You also need to add the class attribute to the filter to "Allowed HTML tags" at the bottom of the page.

<p id class> <br> <u> <s> <em> <strong> <cite> <blockquote cite> <code> <ul class type> <ol class start type> <li class> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <drupal-entity data-entity-type data-entity-uuid data-entity-embed-display data-entity-embed-display-settings data-align data-caption data-embed-button> <img src alt data-entity-type data-entity-uuid data-align data-caption> <a class href hreflang !href id rel target title> <table> <iframe src frameborder width height scrolling allowfullscreen> <caption> <tbody> <thead> <tfoot> <th> <td> <tr>


Debugging a custom module with XDebug and PHPUnit How can I debug a custom module in Drupal 7 using Xdebug and PHPUnit? That is, I would like to debug and perhaps write some unit tests to eliminate some basic potential problems.

This is a code I inherited that is misbehaving. I am relatively new to Drupal but have some PHP skills.

Any advice is appreciated.

xdebug must be added in the PHP env. Acquia Dev Desktop, DrupalVM, Vlad and other VMs come with it out of the box. As for setting the connection up, IDEs like PHPStorm, Atom and VSCode have walkthroughs on how to do that.

For PHPUnit in Drupal 7, it is doable, but not easy. There are a few articles out there that can show you how, but they may be dated. There are two paths, using SimpleTest, and using PHPUnit on it's own.

See:

https://www.lullabot.com/articles/write-unit-tests-for-your-drupal-7-code-part-1
https://www.drupal.org/node/811254
https://tlattimore.com/blog/using-phpunit-with-drupal-7/
https://www.previousnext.com.au/blog/drupal-8-now-phpunit-tests-drupal-7
http://patshaughnessy.net/2008/12/12/writing-your-first-phpunit-test-in-drupal
https://devblog.more-onion.com/content/writing-unit-tests-drupal-7
DrupalUnitTestCase

To be honest, I got going with the articles from 2008 and 2012 respectively. It requires a bootstrap file (that requires and bootstraps Drupal) that you can require in your unit test classes - this allows you to use PHPUnit bare metal.

However, you should really evaluate the tests you are doing. If they truly are unit tests and you're familiar and comfortable with PHPUnit, go for it. But if you can achieve it via SimpleTest, that may be an easier road in Drupal 7. DrupalUnitTestCase is meant for that.


Cannot login to my website I've logged out my drupal 7.22 website and have no login/admin block. It's hosted locally.

I've tried the following URL queries, with no desirable results. The page remains the same and I cannot locate any block I can use to log in-

localhost/drupal/user/logout (Prints Access Denied on Title bar)
localhost/drupal/user/login (Prints User Account on Title bar)
localhost/drupal/?q=user (Prints User Account on Title bar)
localhost/drupal/?q=user/login (Prints User Account on Title bar)

Any help?

Seems like you do not have .htaccess file in you website directory. Place it over there any check :)


Seperate Drupal instance as files server for other Drupal instances My task is to create files gallery which is files library for other Drupal instances.

Other instances can upload files to library and browse them.
File metadata are stored in library (A) and client, but physical file is stored only in A.
So instance A acts like some kind of CDN.

Could someone share with me his thoughts about this problem?
Which modules to use? (besides CDN which I am testing now)

I can accept only free solutions.

You could use feeds module to periodically import file URIs from XML on your file server to you individual drupal instances. You might then be able to hook that up with the media module and use the files on all your different sites.

Edit:
If you're just looking for a cdn for your images you could probably just use Amazon S3. Looks like there's a few modules already built to work with it


How to provide back link to page? I have created grid view page. When I go click on one specific grid its display content of that grid. Now I want to put one 'back' link in side the page of content, that back link displays main view page.

Though they seem rather simple, "back" links on pages are rather tricky.  For the sake of this post, lets assume that you have a shopping site with a search page, and item detail pages.

One complication arises from the fact that users can arrive on the item detail page from multiple paths, including from Google and other pages that aren't in your site.  The back link really only makes sense when they have come from the search results page.

Another complication comes from how Drupal handles page caching.  You could potentially render a back link on a page, but unless you take some URL parameter into account (to have a different $cid), users may see the wrong cached page.  However, if you do tack on a back= to the URL parameter, you now severely lower the probability that a user will actually get a page from the cache.

I have mostly settled on Javascript based solutions.  There are two main options.  All are real variants on each other.  On the detail page, you jQuery in a link that goes back to the search results.

One way is to jQuery some logic on the search results page that sets a cookie with the exposed filer values, URL, or something similar.  Then on the detail page, you use this to go back.  However, this does not work cross-window / cross-tab, and there are security implications with building links this way.

The second way (and the way I have been using lately) just jQueries in a link on the item detail page that calls window.history.back().  This also isn't ideal, but it tends to be the least bad solution.


Multistep form submission fails I'm trying to add multistep form functionality to a node creation form via a form alter. My (abbreviated) code follows:

function mymodule_form_FORM_ID_alter($form, &$form_state)
{
        if (!isset($form_state['storage']['step']))
        {
            $form['actions']['submit']['#submit'][] = 'my_form_submit';
        } elseif (isset($form_state['storage']['step']) && $form_state['storage']['step'] == 'step-two')
        {
            $form['foo'] = array(
                '#type' => 'textfield',
                '#title' => 'Add foo',
            );
            $form['actions']['#type'] = 'actions';
            $form['actions']['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Register',
                '#submit' => 'step_two_form_submit',
            );
        }
}

function my_form_submit($form, &$form_state)
{
    if (!isset($form_state['storage']['step']))
    {
        $form_state['storage']['step'] = 'step-two';
        $form_state['rebuild'] = TRUE;
    }
    //so far so good
}

function step_two_form_submit($form, &$form_state)
{
    //This code never runs
    drupal_goto('/');
    dd('step two ran');
    //etc
}

The second step of the form loads as I would expect along with a submit function. The submit callback, however, is never called. Am I making a mistake by nuking the entire $form array? (The $form_state array, which is what I really need to hold onto, remains intact.) I feel like I'm very close but am missing something substantial.

This is actually easier than it looks! :)

Use the one submit callback and in it use a switch or if statement to execute different actions depdending on what step you're on.

function my_form_submit($form, &$form_state) {
  if (!isset($form_state['storage']['step'])) {
    $form_state['storage']['step'] = 'step-two';
    $form_state['rebuild'] = TRUE;
  }
  else if ($form_state['storage']['step'] === 'step-two') {
    // do something awesome for step-two
  }
}

UPDATED

The following is working code I have running in Drupal 6:

  // multistep form
  if (!isset($form_state['storage']['page']) || $form_state['storage']['page'] < 4) {
    $form_state['rebuild'] = TRUE;
    $page = $form_state['storage']['page'];
    $form_state['storage'][$page]['values'] = $form_state['values'];
    $form_state['storage']['page']++;
  }
  // process submit
  else {
    // grab submitted values for each step from storage array
  }

It runs in the only submit handler of a multistep form.

I realize this is Drupal 6 but its close enough, can you try this?


How to preserve a “target” attribute on links in overlays? How can I preserve target attribute functionality in Drupal 7 overlays? They appear to always be overwritten with target="_parent".

I have added a link to the help text of a field. I would like to open the link in a new browser tab/window so that the user’s input in the form is not lost when following the link. However, the target attribute appears to be overwritten and the link opens in the same overlay.

Here’s the relevant portion of the help text:

 I agree to the site’s Terms of Use.

In general, all links can be excluded from being processed by the Overlay module. Just add a CSS class named overlay-exclude to the class attribute of the link.

That has also solved my target attribute issue:

 I agree to the site’s Terms of Use.


Cloning site and $config_directories On my local Drupal 8 multisite environment in sites/default/settings.php I have:

$config_directories['staging'] = 'sites/default/config/staging';
$config_directories = array();

Because the default direction for the configuration files sites/default/files is .gitignored.

Is above correct, or do I have to delete $config_directories = array(); and put only the first line? How do I have to setup $config_directories properly so I can version my Configuration with Git?

Is $config_directories the same in both settings.php for the local site and production environment. In other words; is settings.php the same for the local site and production environment, except the database information?

Acquia Dev Desktop also gives:

$config_directories['sync'] = 'sites/griffioenrotterdam-dev.dd/files/config_CBOBWbcJU487p7Gc5z5e4GPzL6pSuEKQytsN6heKUULhL8ziYY7DUJoAbHI-dUxnFEfpzk0W7Q/sync'

What about that?

My steps to set this all up where:

I set up a local Drupal 8 multisite environment using Acquia Dev
Desktop. All worked fine.
I have a Git workflow setup
Now I try to make instances of my local site (clone) for Dev and Prod environments
With git I pull the Drupal 8 code to my production server
I adjust settings.php in sites/default/settings.php
I dumped my local Database using drush
I import the Database in Database connected to staging (Dev) environment

But when I visit http://staging.griffioenrotterdam.nl/ it doesn’t look good.

--- Update ---

$config_directories['staging'] = 'sites/default/config/staging';

Is from an old Drupal 8 version.

Now you have to use:

$config_directories = array(
    CONFIG_SYNC_DIRECTORY => './../config/sync',
);

But when I go in admin to Reports > Status report > it says:

  The ./../config/sync folder does not exist. You may need to set the
  correct directory at the file system settings page or change the
  current directory's permissions so that it is writable.

I don't know what you try to do with the config directories.

This doesn't make sense at all, setting a value and deleting it:

$config_directories['staging'] = 'sites/default/config/staging';
$config_directories = array();

The config directory staging does not exists anymore, it must be from an old drupal 8 version. You only need sync. This can be any directory. The hash is only for security reasons and is not needed outside the public files directory.

And I don't see anything in your workflow that would need a special configuration of the config directory, because you transfer the config in the database.


Problem with storing values in multiple textboxes I'm having problem while storing values in multiple text-boxes, its stores value only in 1st text-box, here i'm using following JSON format of drupal 7 services.

"field_raoster_travel_time":{"und":[{"value":"8"},{"value":"81"}]}

( Note : I have set "Number of values" : "Unlimited" for text-box )

When a field is set to Unlimited values, Drupal Services does not yet properly support them. There is an open issue here, and a patch in progress that I've used multiple times to get around this limitation. Grab the latest development version of Drupal Services 7.x-3.x and apply the patch mentioned above, and that should fix it.


Custom "admin/people" view preventing user creation I've created a new view for admin/people; as part of the view set up, I've included "Path: /admin/people."

However, this causes a "page not found" error when I go to "admin/people/create"; I'm guessing I'm not supposed to use the path setting here.

How else would I override the default user view?

Set your path to admin/people/list, not admin/people

Set the menu item for the page to "Default Menu Tab"

Set Default tab options to "Parent menu item already exists"

Worked for me, and didn't interfere with other items under the admin/people pages. It even added the "add user" link that normally appears on the regular admin/people pages.


Other modules functions Is it possible to have a function call within one module which calls a function of a different module even if that function has not been defined as  a hook?

Yes. You can call all function is write in file .module. If function don't write in file .module. You need use function module_load_include and you can call it.


Minimum comment length? I have yet to find a snippet or a solution to enforce a minimum comment length.

Most validation modules deal with fields.

Add a custom validator to form using hook_form_alter in your custom module.

function custom_mod_form_alter(&$form, &$form_state, $form_id){
  switch($form_id){
    case 'comment_form':
      $form['#validate'] = array_merge( $form['#validate'], array('custom_validator'));
    break;
  }
}

Define the logic to restrict the length of comment length

function custom_validator($form, $form_state){
    if(strlen($form_state['values']['comment']) < 50)
       form_set_error('comment', t('No No....'));
}


Can I conditionally call a library based on HTML element? I would like to use DataTables.js for tables created by content editors in the main body field of a content type. I already have the library installed in my libraries.yml.

I had an idea that I could avoid calling the library globally, but instead have it only be called on a page that has an HTML <table> element rendered.

That idea came from drupal.org documentation here, which offers up this code example for the hook_element_info_alter() function:

function fluffy_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'fluffiness/fancy_table';
  }
}

However when I checked into the theme.api, I saw this code is intended for people making modules and indeed the documentation section I saw it in was for modules.

Can I use this same or similar bit of code in my theme_name.theme file to apply to all nodes? Is there something else I should do instead?

Thanks for any advice you can offer.

hook_element_info_alter won't suit in this situation because you are trying to do something based on the value of a body field, which is just 'text' as far as Drupal is concerned. Element in the Drupal world is different. But here is an approach to your problem.

You can implement hook_preprocess_node and check if the body field value contains <table - and if there is a hit, then attach the library:

use Drupal\Component\Utility\Unicode;

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $match = Unicode::strpos($node->field_body->value, '<table');

  if ($node->field_body->value && $match !== FALSE) {
    // next line is just an example
    $variables['#attached']['library'][] = 'mytheme/libraryname';
    $variables['#attached']['library'][] = 'mytheme/datatables';
  }
}

This will only attach the library to a node being rendered IF the node body field has a value, and within it, there is a match for an opening table tag.

The use statement should go at the top of your mytheme.theme file.

strpos has a caveat:

  Note that a return value of 0 is not the same as FALSE.

So if you plan on using this a little more elsewhere, take note.


Creating a directory for a vocabulary term? Background:

I've opened a new vocabulary named "bc" (an acronym for "Blog categories).

The problem:

Anytime I go to the webpage of each term of this vocabulary, the url is sitename.com/term. INSTEAD OF sitename.com/bc/term

This is because when I first built the site, I disabled the option (somehow, it was a long time ago) to create folders for vocabularies.

What I need is to add a folder only to that vocabulary, i.e a way to make terms of this vocabulary to appear under sitename.com/bc/term.

How can this be achieved?

Note: I've already tried to give a pattern, like bc, [bc], [bc]/. None of these helped.

I would bet that you have the module Pathauto enabled. It allows you to create path aliases for mach of your site stuff like nodes and taxonomies. Go to Configuration > Search and metadata > URL aliases > Patterns. That's where you enter the alias patterns for content, taxonomies, etc.   Set the default alias to [term:vocabulary]/[term:name]

It should be mentioned for any case that the default Drupal path for taxonomy terms is taxonomy/term/[term:id]


7.x-2.54 Reports as Unsupported Installing the latest Kickstart update, 7.x-2.54, results in the Status report telling me I have an unsupported version of Drupal core. Screencap attached. Notice the installed and recommended versions are the same. I'm also getting emails saying my version of Drupal is unsupported. Does anyone know why this is happening and how to stop it?

Unfortunately, not sure what could be going on there. Drupal 7.59 is definitely the current version of core, so it may just be some odd bug generating a false negative. Does clearing the caches on the site help at all? If not, I'd just ignore it and / or look in the core issue queue for similar reports.


Drupal navigation always returns a 404 error I have been given a Drupal site which I have to get it running.

I have Apache / Drupal / MySQL up and running, and created a new .conf file in Active Sites, and set the document location to /var/www/html/

I have edited my hosts file so that I have an entry for

127.0.0.1 samplesite.com

If I browse to samplesite.com/index.php I see the index of the site. So far so good. It is all styled, and as I see genuine content I must be hitting the database

Now no matter what link I click on on that page, I get a 404 error. (Looking in the log files its a 404 523 error if that has any bearing on it.)

I then found out the admin userid (using drush), reset the password, and cleared all caches. Still the 404 errors.

If I go to samplesite.com/user or samplesite.com/admin, I still get the 404 error, not an admin login page.

As this is an existing site, and works online, I am blaming something in my setup / configuration (being as the url on a failed link is similar to samplesite.com/about, I am assuming it is in the navigation configuration, but now I am stuck).

Is there an apache url rewriting module (or drupal one?) that needs some configuration? Or can anyone suggest something else I may have overlooked in apache / drupal configuration?

I now have the line $base-url = 'samplesite.com'; in my settings.php file, and none of the other urls work. However it accepts that I am logged in as admin as I have an additional admin menu at the top of the page. (none of the links work though)
Curiously, if I disable wifi, then the page doesn't load at all (I wouldn't have thought that wifi on or off would affect localhost)

Ok, My fix came when I followed this thread https://www.drupal.org/node/1572984

I needed to add in the following.

<Directory /var/www/html>
   RewriteEngine on
   RewriteBase /
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</Directory>

However I only got here because of the help I received along the way, I think this was just the missing piece.

Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing ?q=user or ?q=admin. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about RewriteRule) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning RewriteBase in your .htaccess.

Option 2 - Admin option 'Clean URLs'

I you can use the ?q=adminURL, then try to navigate to /index.php?q=admin/config/search/clean-urls to check the current status of clean urls (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

Option 3 - base_url

Make sure the value of "base_url" is set correctly (in your settings.php).

Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.

Note (about your "The ?q=admin URL didn't ask me to log in" comment to this answer) Check if you get the same problem using another browser. If with another browser it works, then that part might be a cookie problem (delete the cookie in the browser where you have the problem, and try again).


Can I create a text field which is both a autocomplete taxonomy, and a freetagging field I want to let my users store a list of their interests. I don't know what they are going to say (or how many interests) so I am going to let them create their own, preferably as one big comma separated list.

But I'd also like to have those interests as taxonomy terms so that I can find users later on based upon their interests...

Can you suggest a way of doing that?

It would be best if the field was autocomplete too to reduce the number of variants so for example I might type into my interests field

Books, Movies, Hitch

and if the system has other people interested in "Hitchhikers Guide to the Galaxy" then it offers that to me, along with "Hitchhiking", "Hitch (film)" and so on...

(In case you are familiar with it what I am describing is very similar to the LiveJournal interests field)

I am using Drupal 7, Profiles2, and MySQL. I might consider writing a custom module for this if that is the only way, but only if there is demand for it elsewhere.

Hey- thinking about it I'd quite like the way that this site does its tagging of posts..... :-)

That is how the autocomplete taxonomy widget works by default?

It provides autocompletion, but users can also add their own new tags.

Simply add a taxonomy field to your profile, select the Autocomplete Widget and you're good to go.


Using Mysql LOAD DATA LOCAL INFILE with drush I want to able to load a huge CSV file directly into the database using LOAD DATA LOCAL INFILE like below:

LOAD DATA LOCAL INFILE 'Subscriber.csv' INTO TABLE temp_data FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'IGNORE 1 ROWS

If I enter into the mysql via command line using drush sql-cli and run the command above I get;

ERROR 1148 (42000): The used command is not allowed with this MariaDB version

After some research I found out that if you access mysql via the command line using the --local-infile flag, I can be able to use the LOAD DATA LOCAL. Below will be the statement that I use to get into mysql :

mysql --local-infile -u root -p -h mysql

Using the command above will make it possible for me to use LOAD DATA in mysql but i want to be able to use it with drush sql-query. How can I apply the --local-infile flag.

drush sql-query has a not-very-well documented option flag called --extra. This flag is used when connecting via the mysql command to add extra options to the command string. So a drush sql-query --extra '--local-infile' should enable Drush to connect the client with your needed option.


Default front page not showing https My website URL shows in browser https

But on https://test.com/admin/config/system/site-information

It's showing http.

What will be cause of this? Server configuration (apache)?

Does it relate to Base URL?

Yes. The field prefix is populated by the RequestContext:: getCompleteBaseUrl() method, the underlying property, completeBaseUrl, is assigned from $GLOBALS['base_url'] if it's set.

You'll have to test that out to see if that's the case for you, because you might have a web stack configuration that causes Drupal only to see unencrypted requests (e.g. HTTPS only handled at your load balancer / proxy server level), thus displaying the HTTP base.


hook_theme_suggestions_HOOK vs. hook_theme_suggestions_HOOK_alter Let's say some people are working on a contrib module (link) to provide some obvious template suggestions which are not covered by the default Twig Template naming conventions. View mode for fields, region for blocks etc.

Out of habit I'd use hook_theme_suggestions_HOOK_alter. I simply add my suggestions following some logic, done.

  This hook allows any module or theme to provide alternative theme
  function or template name suggestions and reorder or remove
  suggestions provided by hook_theme_suggestions_HOOK() or by earlier
  invocations of this hook.

Then I see there's hook_theme_suggestions_HOOK which more or less does the same except for reordering or removing suggestions. But basically looking at its description it does exactly what that contrib module is supposed to do.

  This hook allows modules to provide alternative theme function or
  template name suggestions.

And now I'm wondering which one of these hooks should be used at best? Is it totally up to us? Do there arise any disadvantages of using the *_alter hook? Do we better use the mere suggestion *_HOOK to allow other modules to intervene later in the process?

The linked module should try to add suggestions in hook_theme_suggestions_HOOK as long as it doesn't depend itself on existing suggestions, so that other modules still have the option to override these suggestions in an alter hook.

Hooks don't have priorities, which having two hooks, one main and one alter hook, is trying to compensate. This is like a priority system with only two levels. If you add something on the second level there is no third level for other modules, unless they resort to unusual solutions like module weights.


Create rule to e-mail only someone who has combined roles This is for a Drupal 6 install.

In rules there is an IF statement available of "If user has roles" and this can be set to be either an "and" statement or an "or" statement.

Within DO is an option to send an e-mail to everyone of a selected role.

I'd like to combine the selector of "if user has roles" using the "and" portion with the DO action of send e-mail to everyone of a selected role.

The site is currently using workflow & revisioning. Using Node Privacy Byrole I've assigned certain parts of the website to a specific department for editing.

Then using Workflow Access I've set up authors, editors, and publishers to limit the actions someone in a department may take on a node.

So there may be a user who is in the department role of "Marketing" and is also an "Editor." Then there may also be someone who is in "Marketing" who is also a "Publisher."

I'd like to notify say the Marketing Publisher (2 different roles) when a post changes workflow state, then have the Marketing Editor notified when a post changes to a different workflow state.

The workflow state is already available as an IF statement within rules, I just need to figure out how to create the DO statement to allow me to send e-mails based on this combination of roles.

Two solutions come to my mind:

Write a module that provides the action you require. See the Developer Documentation for Rules for how this is done.
Write a module that adds users to the role "Marketing Publisher" whenever he as both the role "Marketing" and "Publisher". The module would only have to implement hook_user($op = 'update') and hook_user($op = 'insert').


Force `` to scale to text field in the views-ticker module The Views Ticker module can create a vertical scrolling feed of content. There is an assigned height to each <li> based on the content item that takes up the most space. In my case, it sets the height of each <li> to 72px. Instead of assigning it a definite value, I want the size of each <li> height to scale to the size of the content as opposed to a fixed content.

I've attempted to overwrite it with CSS by setting the height to AUTO but it doesn't work.

If you have a recommendation for another module to use that will scroll content like the ticker does, please post.

Views Slideshows has an option for forcing equal heights, failing that I would suggest using a jQuery plugin like equal heights

Views Slideshows:

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.


Get a multiple value listing of related node IDs using Relation module and Views node ID field The situation

The awesome Relation module uses so called endpoints in a dummy field to show related entities to a given entity.

Sadly there is (still) no way to (really) decide what field values of the related Entities exactly these endpoints are which we want to show. You are only able to decide between "endpoints" or "endpoints and fields", which both result mostly in the same: a list of the linked titles of the related entities, more or less cluttering, depending on your additional relation fields.

The question

Is there something I miss to achieve this? I would like to prevent using performance hogs Views field view for such small task like a list of related node IDs per row in a Views table of listed nodes. Is there any work around or advice somebody can give? Thanks in advance.

Maybe related issues I found on DSX here:

Views related nodes with contextual filters multiple-value handling problem
create relation between two nodes using the relation module

A work around which could come in mind to an experienced Drupal site builder is to use Views module to get more flexibility in showing other fields of related entities listed instead of titles, by using the Views relationship advanced settings in connection with an existing field of related items like node ID.

Sadly the multiple value field handler of Views only appears on the Relation endpoint field itself, added directly in your Views view, but not in the node ID field by using the proper Views relationship to the relation <-> for this purpose.

The expected behavior is, that you are able to activate and modify multiple values of the related node ID field now in the node ID field settings like you did in the endpoints field before. But sadly that's not the case. You will always get the first related node ID or many duplicate records depending on how much related items you have with each related node ID per Views view row.


Check if user is logged in first time How can i check if user is logged in for the first time on site?

If it is, i want to show him a message...

Can someone help me?

Thank you!

** UPDATE **

As suggested by oknate, using hook_user_login:

function hook_user_login(&$edit, $account)
{
  if(!$account->access)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}

** Original less optimal method **

You can use hook_init() in D7, and check if they have a value for last access:

function hook_init()
{
  global $user;

  $first_login = db_query('SELECT 1 FROM {users} WHERE uid = :uid AND access = 0', array(':uid' => $user->uid))->fetchField();

  if($first_login)
  {
    drupal_set_message(t('This is your first login. Welcome!'));
  }
}


How to set a yml sequence config value via drush cset When the drupal config value (as defined in .schema.yml) is a sequence what is the correct syntax for drush config-set so that the value is a sequence not a simple string? For example, with the devel module
drush config-get devel.settings error_handlers returns

'devel.settings:error_handlers':
  1: 1

So what is the syntax to set the value to 4: 4. I have tried lots of combinations, such as 4:4  [4:4]. error_handlers.4 4 but have not hit on the right way yet. I could not find any examples or documentation, so asking here. Thanks.

Uh, I love riddles like this! And finally found a way!

You first have to delete the error_handlers config key.

$ drush -y cdel devel.settings error_handlers

And then set it again.

$ drush -y cset devel.settings error_handlers.4 4

Let's check.

$ drush cget devel.settings error_handlers
'devel.settings:error_handlers':
  4: 4

Yeah!

Just drush -y cset devel.settings error_handlers.4 4 without deleting it first would just append it and you'd end up with 1: 1 and 4: 4 both.


cURL hangs the hook_user_update I am using a cURL to notify remote site of some updates on my site. I use it with
hook_user_update()  which is used when user data is saved. Problem is that it takes a lot of time to do that (maybe slow remote server). User saving is slow and it takes sometimes a minute or two.

How could I make this work that cURL doesn't hang user update and they are not dependent in this way?

This is the code I am using now

/**
 * Implemention of hook_user_update(), Notify OS after updating user account
 */
function os_integration_user_update(&$edit, $account, $category) {
  $query = array(
    'source' => 'web',
    'action' => 'nCustomer',
    'customer_id' => $account->uid,
    );

  $url = url('http://admin.com/synch/index.php', array('query' => $query));

$username = 'admin_os';
$password = 'admin_pass';
$basic = base64_encode($username . ':' . $password);

$headerArr = array();
$headerArr[] = 'Authorization: Basic ' . $basic;

$ch = curl_init( $url ) ;
curl_setopt ($ch, CURLOPT_HTTPHEADER , $headerArr );
curl_setopt( $ch, CURLOPT_HEADER, 1);
// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
 watchdog('lelo_os_integration_os_error', 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']);
 // other info data http://php.net/manual/en/function.curl-getinfo.php
}

// Close handle
curl_close($ch);
}

The HTTPRL project provides you with a non-blocking HTTP client.

$url = url('http://admin.com/synch/index.php', array('query' => $query));
$username = 'admin_os';
$password = 'admin_pass';
$basic = base64_encode($username . ':' . $password);

httprl_request($url, array(
  'blocking' => FALSE,
  'headers' => array(
    'Authorization' => 'Basic '.$basic,
    'Host' => $_SERVER['HTTP_HOST']
   ),
));
$request = httprl_send_request();


Taxonomy Terms node count of different content type along with zero count in a hierarchy After much headache I was able to maintain a kind of hierarchy for the taxonomy terms, of the already continuing issue here, please click the below link

Taxonomy Terms node count of different content type

I did It like this, but still needs to do more.

In second step select the parent relation and check the exclude display.

Under format option select the parent taxonomy under group 1

I am getting the parent category under  tag and the child terms as list-terms. using jquery I can display it in an accordion style somehow.

Now the problem i am facing is that empty taxonomy terms with counter zero are not getting displayed, please help if anyone knows the solution.

Check what you have set for the "no results" behaviour on that field. You will not want it set to "hide".

Also check if it displays in the views preview. If it displays there but not on your page then it may be that your template is checking if a field is blank and before deciding whether to show it - you could solve this by setting a default/no results value of "0"


node edit tabs in a block Is it possible to move node edit tabs links in some block. I want to hide them from the orignal position and want to create a floating block which may contains all those links which are available in tabs.

I think you want to do something like this?...

http://vimeo.com/79462942

I did this with some jQuery and CSS.

jQuery to create and place "button" - in my case, this is a font-awesome icon. This may seem strange, but we're placing the button inside the div.tabs tag, and then placing div.tabs tag inside the h1 tag...

// edit node buttons
(function($){
    // wait til everything loads before firing
    $(document).ready(function(){
        //insert edit icon into div.tabs
        $('div.tabs').prepend($("<i class=\"icon-edit\"></i>"));
        //insert div.tabs into page title
        $('h1').prepend($('div.tabs'));
    });
})(jQuery);

Now, if this is all we did, it would look crazy! We need CSS to do the magic part...

/*first we hide div.tabs, but we also define properties for when we expose it later*/
    div.tabs ul {
    display:none;
    position:absolute;
    padding:10px;
    margin-top:-10px;
    background:rgb(0,0,0);
    border: 0px none;
    width:260px;
    border-radius: 4px 0 4px 4px;
    z-index:100;
    }

/*this exposes the tabs when we hover over the icon!*/
    a:hover.icon-edit,
    div.tabs:hover ul,
    div.tabs:active ul {
    display:block;
    }

/*position button - I want it to the left of the h1*/
    div.tabs {
    float:left;
    width:1em;
    }

Your selectors and styles may differ, but the essential thing is to have a trigger/button class (or id) that is inside the div you want to hide/show.


How can I show a view in panel with argument in drupal 7 I am using panel to show the content and i am using view.I am creating a forum and want the link based upon argument when i am creating view and giving some context ,in preview it is working fine but when i am trying to rum wirh url no value is coming can any one tell what I am doing wrong.thanks in advance.

In order to use "contextual filters" for a view within a panel, you need to change the style of the panel. It seems that even though they are called contextual filters, they expect an argument. Make sure you have the view panes enabled in modules and create the same view with the style of view pane. You will then get an additional menu called "pane settings". One of the settings is "argument input", select "from context" and the required context, and it should work fine. This was something I was really stuck on till  found this solution.

also, if you are trying to pass a taxonomy term, you have to make sure it is formatted correctly to use in the filter. See this post for details

Views contextual filters taxonomy name


Why doesn't Drupal use my block.tpl.php? I want my Drupal 7 theme to use a custom block.tpl.php for my navigation bar (Defined: regions[navigation] = Navigation bar). So I copied block.tpl.php from the block module to my theme directory and tried to give it different names (following different guides on the web). None of them seemed to work.
Then I wanted to make sure it was a naming problem so I changed the name back to block.tpl.php and changed its contents (removed the h2-tag for the title). I reloaded my site but nothing happened so there must be another problem.

Any ideas on how to fix this?

Thank

Most likely you just need to clear Drupal's caches.

Template file implementations are cached in the theme registry so you need to clear it for new files/theme functions to get picked up.

You can do so either at http://mysite.com/admin/config/development/performance or by using Drush.


How to apply a sequential number pattern in Pathauto? If the path name is same, I want to show display as below.

I want:

example.com/blog/path001
example.com/blog/path002
example.com/blog/path003 ...

currently:

example.com/blog/path
example.com/blog/path-1
example.com/blog/path-2 ...

But I don't know how to apply these patterns?
What should I do?

You need an additional module for this – Serial Field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

You then can use Serial Field + Token + Path Auto - to create serial numbers in urls, for example: http://www.example.com/issue/10 (where 10 is a type scope serial number).


custom block's BLOCK_VISIBILITY_LISTED not working on profile installation hook_install()? Why this cannot work in my profile installation?

array(
  'module' => 'views',
  'delta' => 'views-block',
  'theme' => $default_theme,
  'status' => 1,
  'weight' => 0,
  'region' => 'map_region',
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => '<front>',
  'cache' => -1,
),

Is just a copy of standard's profile hook_install() and i add a views block installed with the profile in $blocks array.

All is set right except block only visible in front page ("front" is set correctly in the block config 'pages' but the visibility setting is stuck to 'All pages except those listed')

Looks like the system module re-sets them upon install.

I had to do this in a module that gets installed after all other modules installation in the profile using

  hook_install_tasks()

and in the the new task's callback i enable the module with module_enable


"An illegal choice has been detected" I have an image field attached to a content type created. When I upload images to it, it gives me an error "an illegal choice has been detected please contact sight administrator."  I get this error when uploading images only on this content type.

I cleared watchdog entries, form and image cache tables; it started working again, but when I create a second page, the problem shows again.

How can I avoid this error?

I found the answer here.

The required field radio button was not selected, when the image was uploaded. It seems an error with the form validating when the image is uploaded.


"Error: Undefined class constant 'Symfony\Component\DependencyInjection\ContainerInterface::SCOPE_CONTAINER'" I am using drush 8.1.2 and drupal 8.1.

I ran composer update in /core as well as in the project root.  From what I can see it updates /core/vendor as well as /vendor (in project root).

Obviously this means that many of the libraries are duplicated; I am not sure if this is the idea.

Anyhow, when execute any drush command from /sites/default I get the following error:

  Error: Undefined class constant 'Symfony\Component\DependencyInjection\ContainerInterface::SCOPE_CONTAINER' in
  /myproject/core/lib/Drupal/Core/DependencyInjection/Container.php, line 16

If I open core/lib/Drupal/Core/DependencyInjection/Container.php in my IDE (PHPStorm), the IDE tells me there are multiple definitions for Symfony\Component\DependencyInjection\ContainerInterface, which is fair enough because there is one in core/vendor as well as vendor (in the project root).

Either way, the versions of Symfony\Component\DependencyInjection\ContainerInterface is exactly the same (version 2.8.6)

According to this post, it is important that they are the same, which they are, and the class constant is defined in both files.

I get the impression, the file is not being 'auto-loaded', but I do not know enough about Drupal 8 to figure out if it is or not.

For the record, when I open the project in my browser (hit the web site), it is working fine.

So the drush / drupal boot-strap process is not working.

Any ideas where to start looking please.

The problem is exactly that you executed composer update twice, in two different directories. You don't execute it from the core directory, but only from the directory containing the core directory. In fact, the composer.json file you find in the directory where you decompressed the Drupal archive contains the following lines.

    "merge-plugin": {
        "include": [
            "core/composer.json",
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

The include part is telling to Composer to include the core/composer.json file too when updating. Supposing that mysite is the directory containing the core directory and the other Drupal files, it is enough you execute the following commands to get in mysite/vendor all the dependencies necessary.

cd mysite
composer update

In my case, I get the following output. (It may change, basing on how often you execute those commands.)

  Loading composer repositories with package information
  Updating dependencies (including require-dev)
     Removing symfony/polyfill-iconv (v1.1.1)
     Installing symfony/polyfill-iconv (v1.2.0)
       Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-mbstring (v1.1.1)
    Installing symfony/polyfill-mbstring (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-php54 (v1.1.1)
    Installing symfony/polyfill-php54 (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-php55 (v1.1.1)
    Installing symfony/polyfill-php55 (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing guzzlehttp/promises (1.1.0)
    Installing guzzlehttp/promises (1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
    Removing symfony/polyfill-apcu (v1.1.1)
    Installing symfony/polyfill-apcu (v1.2.0)
      Downloading: 100%

  Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  Writing lock file
  Generating autoload files
   Drupal\Core\Composer\Composer::preAutoloadDump
   Drupal\Core\Composer\Composer::ensureHtaccess

Both Drupal 8 and Drush work for me.

drush status

  Drupal version                  :  8.1.1
  Site URI                        :  http://default
  Database driver                 :  mysql
  Database hostname               :  localhost
  Database port                   :
  Database username               :  database_username
  Database name                   :  database_name
  Drupal bootstrap                :  Successful
  Drupal user                     :
  Default theme                   :  bartik
  Administration theme            :  seven
  PHP configuration               :  /etc/php.ini
  PHP OS                          :  Darwin
  Drush script                    :  /usr/local/bin/drush
  Drush version                   :  8.0.5
  Drush temp directory            :  /tmp
  Drush configuration             :
  Drush alias files               :
  Install profile                 :  standard
  Drupal root                     :  /Library/Server/Web/Data/Sites/mysite
  Drupal Settings File            :  sites/default/settings.php
  Site path                       :  sites/default
  File directory path             :  sites/default/files
  Temporary file directory path   :  /tmp
  Sync config path                : sites/default/files/config_WZrobbGFfHIWBRmKDknFVfKgdyG1gKNFLBYcpBlbTZtEarG_rPEixLJFW6faE9yNFTjdkieQbA/sync

As side note, if you need to include the composer.json files modules could have, you can edit the mysite/composer.json file to contain the following lines.

    "merge-plugin": {
        "include": [
            "core/composer.json",
            "modules/*/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    }

Alternatively, you can use the Composer Manager module. I would suggest installing it, if you need to include any dependecy modules could have.


Custom form: How to implement a module's field widget In my custom form I have a file upload, which follows the array structure of file_element_info() in file.module in core. This is consistent with examples in examples module and date module has _date_api_element_info().

But looking at geofield or at openlayers and other modules I can not see what array values are possible/required.

As a general rule how do I find out how to add a field of a specific type to a custom form?

Edit #1:
Just read Where can I find complete documentation of hook_field_info? and everyone is being really helpful about Field API, but it is a steep learning curve. A specific example would really help (an not one of the simple core field types).

Edit #2:
So on my particular example in geofield.module I got (got the same using dpm(field_info_field_types('geofield'));):

function geofield_field_info() {
  return array(
    'geofield' => array(
      'label' => 'Geofield',
      'description' => t('This field stores geo information.'),
      'default_widget' => 'geofield_wkt',
      'default_formatter' => 'geofield_wkt',
      'instance_settings' => array(
        'local_solr' => array(
          'enabled' => FALSE,
          'lat_field' => 'lat',
          'lng_field' => 'lng',
        ),
      ),
      'property_type' => 'geofield',
      'property_callbacks' => array('geofield_property_info_callback'),
    ),
  );
}

But how does that translate to a form field array?

$form['location'] = array(
    '#title' => t('Location'),
    '#type' => 'geofield',
    '#required' => TRUE,
);

Or do I have the wrong end of the stick here?

In addition to the info posted by @Clive I think it's important to note that this problem can be addressed the other way round[*]: create a node type (or other entity type) with the required fields, and capture the data to process it as you wish when the content is saved.

To do this you would:

Create a custom content type (or other entity type) with the fields you need ;
Implement hook_form_alter to modify your form if you need special features that are not provided by normal content type forms.

From there it depends what you want to do. If you want the content saved (so that it is stored), and want to process the data after it has been saved, then you could implement hook_entity_insert. If you also want to process the data before it is saved, you could add your own submit handler in hook_form_alter as such:

array_unshift($form['actions']['submit']['#submit'], 'my_submit_handler');

If you want the data after it is submitted, but don't want it saved, you could replace the submit handler with your own:

$form['actions']['submit']['#submit'] = array('my_submit_handler');

[*] I realise I'm not answering the question, but I'm offering a solution to the problem :)


How do you perform a Guzzle POST request with "Basic Auth" for the current user? In my class, I have the following request:

    $rest_response = $client->post($endpoint, [
      'auth' => ['admin', 'admin'],
      'body' => $serialized_entity,
      'headers' => [
        'Content-Type' => 'application/hal+json',
        'X-CSRF-Token' => $token,
      ],
    ]);

It works because I have a user with the username/password as "admin"/"admin", but when that user's password is changed, it won't work anymore, as expected.

In the logs, I am getting an "access denied" error for the endpoint I am trying to POST to - and the user associated with that error says "Anonymous (not verified)". All other log messages printed out in my controller show the current user's username.

I am running Drupal core 8.1.9.

The question is - how do I use basic_auth to get the current logged-in user's credentials to be passed into the request?

You were so close  main thing here is the "Authorization" Header ...

 $current_user = \Drupal::currentUser();
 $account = $current_user->getAccount();

 $username = $account->name;
 // pass would be hard to get as stored hashed
 //... so you would need to get a bit tricky to "catch" the users password when they log in...
 $pass = 'admin';
 $auth = 'Basic '. base64_encode ($username . ':' . $pass);
 $rest_response = $client->post($endpoint, [
   'body' => $serialized_entity,
   'headers' => [
     'Authorization' => $auth,
     'Content-Type' => 'application/hal+json',
     'X-CSRF-Token' => $token,
  ],
]);

And just for fun:

  var basicAuthCredential = username + ":" + password;
  var bace64 =  btoa(basicAuthCredential);
  var Auth =  'Basic ' + bace64;
  fetch(url,{
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': Auth,
      'X-CSRF-Token': token
    },
    body: JSON.stringify(data)
}).then(response => response.json())...


how to add parameters to html email template I have a working html email using modules: Mail System, HTML Mail, SMTP Authentication Support.

And I want to include some parameters/variables in the html email template file:

htmlmail--htmlmail.tpl.php

some variables include: $base_path etc. from page.tpl.php variables

From what I've read from the Internet, you may use "hooking" and I haven't yet hooked variables so far for my template file.

you can use the yourtheme_preprocess_htmlmail() function for htmlmail email template in put in the template.php file of your current theme. I will give an example.

function yourtheme_preprocess_htmlmail(&$variables) {
  switch($variables['key']){
    case 'password-reset':
     $variables['var1'] = t('SAMPLE TEXT');
     break;
    case 'register-no-approval-required':
     $variables['var1'] = t('SAMPLE TEXT');
     break;
    break;
   }
   $variables['heading'] = t('Heading text');
   $variables['copyright'] = t('Copyright text.');
 }

In this example. I created some customized variables base on the mailkey and defined some others like heading, copyright