"Class not found" error when attempting to access inbuilt DateTime class I am attempting to convert a working Drupal 6 module to Drupal 8 in preparation for the up coming release, and as an exercise in learning the new system.

In my existing module, I do some calculations on whether or not it is currently the weekend or a weekday and output some HTML in a block based on that.

In my code I have a is_weekend() function which returns TRUE if it is currently the weekend, and FALSE if it is a weekday.

My code for that function starts like this.

function is_weekend() {
  $ESTTZ = new DateTimeZone('America/New_York');
  $dt = new DateTime();
  $dt->setTimezone($ESTTZ);
  $day = $dt->format("w");
  $hour = $dt->format("H");
  $minute = $dt->format("i");
  $weekend = FALSE;

  if ($day == 6) {
    // ...
  }

  return $weekend;
}

It works fine; however, when I try to put this function into my new block class I get the following error:

  Fatal error: Class 'Drupal\livequotes\Plugin\Block\DateTimeZone' not found in C:\Work\ex-global-8

How can I call this PHP class from within my own block class?

You're just running into namespace problems. DateTimeZone is in the root namespace, so refer to it as:

\DateTimeZone

Same for

\DateTime


Exclude from list view some articles based on their content type? i’m listing in a view a list of article filtered with taxonomy terms.

The result is like this :

taxonomy term 1
- article A (content type 1)
- article B (content type 1)
- article C (content type 2)

taxonomy term 2
- article D (content type 1)
- article E (content type 1)
- article F (content type 2)

taxonomy term 3
- article G (content type 1)
- article H (content type 1)
- article I (content type 2)

How can i exclude from this list some articles based on their content type ? For example, remove "content type 2".

Also, i’ve created a view which contains article C, F, I. How can i add a specific view to this list ?

Here is my view settings :

Here is the result in front-end :

You can add this rule to Filter criteria section as on screen


using an existing token as a variable in a custom token I am using simplenews to send out a newsletter.  I have a custom module.  It has a table that relates a user code to the user's email.

email_address                  user_code
bob.loblaw@lawblogs.com        37XylT12

In the simplenews email I will send, the idea is that each user will receive a link with their usercode in it (i.e., http://www.domain.com/?q=go&c=37XylT12).

I've been attempting to create a custom token to place in the text of the newsletter and replaced with my custom link prior to send.  However, I have two issues: 1) I cannot find an example of a token that includes a db_select query to return data and 2) I cannot find a way to access the simplenews email token ([simplenews-subscriber:mail]) in my custom module -- I need this value to lookup the code.

If someone could point me in the right direction, I would appreciate it.
KMT

Accessing the database to set a token is not different from accessing the database in other cases.

function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $sanitize = !empty($options['sanitize']);

  $replacements = array();

  if ($type == 'YOUR TOKEN TYPE') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'YOUR TOKEN':
          $replacements[$original] = /* CODE TO QUERY THE DATABASE */;
          break;
      }
    }
  }

  return $replacements;
}

As for accessing the value of a token defined from a module, when you know the token you are looking for, you can call token_replace() passing the token for which you want to know the value as first parameter. Keep in mind that your implementation of hook_tokens() is going to be called again; be careful of not causing a loop.


How to remove number of reads under each node? I'm using Drupal 7. After enabling the Statistics module, I see, under each node, how many times it has been read (e.g. "4 reads"). How can I remove this expression while I'm using it ("Content statistics: Total views") in my views?

I needed a simple page counter but did not want to see the "reads" on every node page even as the site admin. For my drupal 7 "fusion" sub theme I used this in my template.php

function yourfusionsubthemename_preprocess_node(&$vars) {

unset($vars['content']['links']['statistics']['#links']['statistics_counter']['title']);

}


Mouseover instead of click Has anyone gotten the Quicktabs module to work on mouseover/hover instead of click?
There was a patch for version 6.x-2 that does not work with the current version.

I ended up making a couple of edits to quicktabs.js. At its most basic, in line 24 I changed 'click' to 'mouseenter' and changed the name of the quicktabsClick() function to quicktabsHover().

When the user clicked the link in the tab, though, the page refreshed; I added the following at line 25 (below the new call to quicktabsHover):

$(this).unbind('click').bind('click', quicktabsClick);

I also added a new function:

var quicktabsClick = function() {
    return false;
}


How can I allow a user to send private messages but prevent other users from sending that user a private message? I have a "system" user that sends "Welcome to the website" private messages as well as announcements to users.  I am able to send these messages via rules; however, I don't want users to be able to reply to these messages.

I tried disabling private messages for the system user but that option disables both the receiving and sending of private messages (I checked-- if private messages are disabled for a user, no private message can be mailed from that user using rules).

I don't need a solution that is bulletproof; hiding the reply form on the private message view screen is sufficient.  However, I dug through the private message module code and was unable to find any way to do that.

There are two ways to do this.

The pm_block_user module has settings that allow for role-based configurations for who is allowed to write whom. However, it is only possible to add positive rules. Meaning, you wold need to add all your users into a normal role that the system user is not part of and then allow users of that role to write users of that role.
Implement hook_privatemsg_block_message() and block the system user id.

You're welcome to provide option two as a patch in the main module (e.g. allow to choose a system user whom you can't write/reply and is maybe also themed differently). This is an often requested feature.


How to add Block Into View? I want to add a block which is created by a view. This block has slider and I need to put between some fields of view.

How can I do this?

There are a few ways to do this.

The simplest is to add your block view to the header or footer of the new view.  To do this, go to the configuration page for the new view and click Add next to Header or Footer (in the middle column).  Choose Global: View area and then select your view.

Alternately, for maximum control over layout, you can use the Panels module, but it is much harder to set up.

Another option is the Views Field View module.  Here is a tutorial about how to set this up.

One further option is the Viewfield module.


Is it wise to edit the default Google Analytics path exclusions? The Google Analytics module has a default configuration under the "Pages" tab: "Add tracking to specific pages". The listed exceptions are:

admin
admin/*
batch
node/add*
node/*/*
user/*/*

I'm using Webform, which generates confirmation pages like node/125/done by default. I could of course create specified paths for each of my webform confirmation pages, but there are many on the site (over 50), so the easier route would just be to remove node/*/* from the GA exclusions.

What repercussions might arise from this?

It should mean that pages such as EDIT nodes, will appear and be tracked by google analytics, which could cause false numbers.  You could change the exceptions by removing the

node/*/*

but including other specifically excluded content, such as

node/*/edit.

You would want to keep an eye on google analytics to see if other pages are creaping in and then exclude them as you find them.


How can I let anonymous users view user profiles by role? I have 2 different roles like A and B.

I want anonymous users (everyone) can view user profiles from A role but can't view user profiles from B role.

In summary, A role profiles is open for everyone but B is not.

Access user profiles permission or View profiles permissions module is not enough for that.

Thanks in advance.

You can use Views to achieve this. Under Page Settings change Access to Role & select Anonymous users from the list. Check exported view shown below:

$view = new view();
$view->name = 'user_profiles';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User Profiles';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User Profiles';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  1 => '1',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['label'] = '';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
$handler->display->display_options['fields']['uid']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['uid']['link_to_user'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['make_link'] = TRUE;
$handler->display->display_options['fields']['name']['alter']['path'] = 'user-profile/[uid]';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_user'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Roles */
$handler->display->display_options['filters']['rid']['id'] = 'rid';
$handler->display->display_options['filters']['rid']['table'] = 'users_roles';
$handler->display->display_options['filters']['rid']['field'] = 'rid';
$handler->display->display_options['filters']['rid']['value'] = array(
  5 => '5',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user-profiles';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->display->display_options['defaults']['pager'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: User: Rendered User */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_user';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['label'] = '';
$handler->display->display_options['fields']['rendered_entity']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['display'] = 'view';
$handler->display->display_options['fields']['rendered_entity']['view_mode'] = 'full';
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 1;
$handler->display->display_options['defaults']['arguments'] = FALSE;
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['path'] = 'user-profile/%';

In my case, I wanted to list user of role field executive.


Generating URLs based on taxonomy vocabularies and terms I have a Drupal 7 website and I have 1 Vocabulary "Interviews" containing terms Celebrity and Director.

I want my website content to be available at URLs like this:

http://example.com/interviews/celebrity/title

http://example.com/interviews/director/title

In your Pathauto Patterns (Admin>Config>Search and Meta Data>URL Aliases>Patterns /admin/config/search/path/patterns ) in the Content Paths section, find the appropriate content type and use the Tokens (called Replacement Patterns) to fill in the field.

In the described case, it might be something like the following:
[node:content-type]/[node:field-category]/[node:title]
or
interviews/[node:field-category]/[node:title]

Be sure to expand and check what tokens you have available.


How to make exposed filters to hide filed with no value I am using exposed filters in Views to give user opportunity to select attribute.
I used field with taxonomy term as exposed filters.

As a result, exposed filter shows all possible variants for this field (all terms), instead which really were used in this material. I mean, that user can select any term from vocabulary even if I did not use this term in this content type material.
How to hide unused terms in exposed filters?

The below code comes from a current project of mine. I've made it more generic for your purposes, so it's untested. You'd need to modify the query depending on your usage - it's going to throw errors if you use as-is.

<?php
// Add this to a custom module, replace "mymodule" with your module name
function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  //dsm($form); // Display available form vars
  $field_id = 'id_assigned_in_views'; // Change for the field ID in question.
  // Only alter forms with the necessary field.
  if (isset($form[$field_id])) {
    // Do your entity_field_query or db_query here
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', array('tags'))
      ->propertyOrderBy('weight');
    $result = $query->execute();
    $terms = $result['taxonomy_term'];
    // Add a default so the filter is optional.
    $options = array('' => t('- All -'));
    foreach($terms as $tid=>$term) {
      //dpm($term);
      $options[$tid] = $term->name;
    }
    // Alter the field.
    $form[$field_id]['#type'] = 'select';
    $form[$field_id]['#options'] = $options;
    $form[$field_id]['#size'] = 1;
  }
}
?>


How to create a block with views filter form available on each page of the site? This is for a site of a small real estate agency.

I have a property_offer content type set up and offer type vocabulary, with 4 terms (Buying, Selling, Put out to lease and Take on lease). Then I have created a view with page display, for the front page of the site it lists all the offers, and there is also a page for each of the 4 terms.

How do I create an exposed filter for this view which must be available as a block so I can put it in a region of the site and it'll be available on all the other pages too?

Views support "Exposed form in block", see in views editing page. Set it to "Yes", and it will appear in blocks.


Change "Public file system path" with Amazon S3 I want to keep my media files, all files in the "default/files" folder in the Amazon S3 account. I've opened the "admin/config/media/file-system" page and there is the "Public file system path" field, which by default is set to sites/default/files.

I can't imagine how can I connect my Amazon account with this file system path.

I'm using Drupal 7.

You are looking for the following module: AmazonS3.


JQuery accordion works in admin but not for anonymous D7.18
I have a similar problem to another question but the solution did not work for me.
I have added my jquery accordion file  (accordion.js) to the subtheme.info file and a file called  accordion.js to the subtheme folder.
The accordion.js code is

(function($) {
Drupal.behaviors.accordion = {
attach: function (context, settings) {
   //code starts
  $("#accordion").accordion({
  autoHeight: false
  }
  );
   //code ends
  }
 };
 })(jQuery);

The accordion effect works correctly when logged in as admin but does not when logged out.
Firebug shows  for the anonymous user but none of the other classes that are shown when logged in as admin.
I am using the Omega Theme.
I am completely stuck as to how to resolve this

jQuery UI is bundled with core in D7 ( see /misc/ui ).
To add jQuery Accordion JS you can just go:

e.g, in template.php

function THEMENAME_preprocess_html(&$variables) {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.accordion');
}

After that, clear all caches and check the javascript files have been added in the HTML source of the page as anon.


Hide flag field from certain nodes in view I'm new to Drupal, so I may be missing some "obvious" things

I've installed the flag module, so users can flag their content to make it appear on top of other views. The thing is, when I display the list of content to the user (including both published and unpublished nodes), flag shouldn't be available if the node is unpublished

I tried to alter the view using the hook hook_views_pre_render, but I don't seem to have access to the flag content for removing (I guess my hook is being called after the flag hook, but I'm not certain about that). I tried this:

function mymodule_views_pre_render{
  switch ($view->name) {
    case 'usernodes':
      foreach ($view->result as &$row) {
        //Custom field with publish states, 3 means it is published
        if ($row->field_publish_state[0]['raw']['value'] !== '3') {
          //Unset the two values related to flags I could find
          unset($row->flagging_node_entity_id);
          unset($row->flagging_nodeuidisnotnull);
        }
      }
      break;
  }
}

But the flags are still rendered

What I think could work:

I could use the hook hook_views_post_render, and edit the second parameter ($output) but it feels wrong to actually override the HTML output (it would become a messy code)
I could change it using some Javascript, when the page loads, but it doesn't feel right
Using Views PHP and then inserting a Global PHP field (as noted by code.rider below), but users have access to views and they could make a mess with that field

What would be the best way to hide the flag field for certain rows?

Install the Views PHP module and enable it. This will allow you to
embed php into a view cell.
Add a new nid/node id field to your View. Make sure to check the
“Exclude from display” checkbox.
Add a new Content: Published field to your View. Make sure to check the
“Exclude from display” checkbox.
Rearrange your fields so that your hidden nid field and published
field  at the top of all fields. This is important. It needs to be
“available” as an element to the custom php field we are about to
add, and if it’s after, the custom php field won’t see it.
Add a new Global: PHP field.
add the following code to the Output Code section of the field (in
php):

if ($row->status) {
  print flag_create_link("the_machine_name_of_your_flag", $row->nid);
}

 Use  delimiters to enclose PHP code.
Click the apply button

use flag field in Sort criteria for sorting content mean flagged content on top
this is a tested solution.
hope this solve your problem.


How to create a user after ldap authenticaion? I am using ldap for Drupal 7.  After successfully authenticating, how do I create a Drupal user.

The LDAP module will also allow you to automatically create a user after authentication.

Once you configure your server, look at the third tab LDAP
authorization Choose edit to configure that server
Under basic, enable and Only apply the following LDAP to drupal role
configuration to users authenticated via LDAP.
You can set the role of the new user by checking  drupal roles are
specified by LDAP attributes under IIB. Also name the field that will
be use to determine role
Configure part III. LDAP to drupal role mapping and filtering For
example, if the title field is Staff you may want to give a staff
role Staff|staff
Part 4    IV.B. When should drupal roles be granted/revoked from
user? Check "When a user logs on"
IV.C. What actions would you like performed when drupal roles are
granted/revoked from user? Check Revoke drupal roles previously
granted by LDAP Authorization but no longer valid.

There are other settings that you can configure but this should get you started.


Change content location in node template My content is normally displayed in a specific region that takes up 75% of the screen width, which is usually desired.
However on 'User Profile' pages (and a few others) I want it to take 100% of the width.

I created a user-profile.tpl.php file, which contains the content wrapped in a div that takes up the full screen width using bootstrap like so:

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

The content is rendered, but it's wrapped in the normal content region that is only 75% of the width.  This is a simplified version of the content that is rendered:

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

you need to change the page-user.tpl.php to be able to remove the class from the content region. see here How can I create page.tpl for user’s profile page?


How to add Pager to a custom page? I have a list of items which is fetched from an REST API and displayed in a page 10 at a time. These items are not stored in Drupal database in any way. I managed to have a basic pager which is just a Previous & Next. But as per design the list should have a full pager.

So, how can I add a Full Pager in such page?

There are some examples on drupal.org of adding a pager to the page, if you want to use the one that core uses:

https://api.drupal.org/api/drupal/core%21includes%21pager.inc/function/pager_default_initialize/8.2.x

The second example should work for you:

  $page = pager_find_page();
  $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
  $offset = $num_per_page * $page;
  $result = mymodule_remote_search($keywords, $offset, $num_per_page);

  // Now that we have the total number of results, initialize the pager.
  pager_default_initialize($result->total, $num_per_page);

  // Create a render array with the search results.
  $render = [];
  $render[] = [
    '#theme' => 'search_results',
    '#results' => $result->data,
    '#type' => 'remote',
  ];

  // Finally, add the pager to the render array, and return.
  $render[] = ['#type' => 'pager'];
  return $render;

I have done this before in my own wired up search pages, it should solve your issue.

You can replace $num_per_page above with 10, if you do not have a custom module to store the setting.

You could go further, and in your code create a service that handles just attaching the pager. I was doing some sandboxing exploring the search API, and came up with this. First, you need to define your service and inject it to your controller (I refer to mine as pager_service).

  /**
   * @var \Drupal\velirsearch\Service\PagerService
   */
  private $pager_service;

  /**
   * SearchResults constructor.
   * @param \Drupal\velirsearch\Service\PagerService $pager_service
   */
  public function __construct(PagerService $pager_service) {
    $this->pager_service = $pager_service;
  }

  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    $pager_service = $container->get('velirsearch.pager_service');
    return new static($pager_service);
  }

Then, a method that attaches a pager:

     /**
       * Convenient method to obtain a pager to attach from the pager service.
       * @param $totalRows
       * @param $limit
       * @return array
       */
      protected function attachPager($totalRows, $limit) {
        return $this->pager_service->getPager($totalRows, $limit);
      }

Then, the service:

namespace Drupal\velirsearch\Service;

use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class PagerService implements ContainerAwareInterface {

  use ContainerAwareTrait;

  /**
   * @var \Symfony\Component\HttpFoundation\Request
   */
  private $requestStack;

  /**
   * PagerService constructor.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   */
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $requestStack = $container->get('request_stack');
    return new static($requestStack);
  }

  /**
   * @param $totalRows
   * @param $limit
   * @return array
   */
  public function getPager($totalRows, $limit = 10) {
    pager_default_initialize($totalRows, $limit);
    return ['#type' => 'pager'];
  }
}

Then, when you need it...

  $render[] = $this->attachPager($results->getResultCount(), 10);

  return $render;

You don't necessarily have to go that far, I was just looking for ways to reduce the code needed to attach a pager to different instances of search result controllers. YMMV.

Note that I did not use the third argument to pager_default_initialize, $element, which you will need if your page will have multiple pagers on it.

getResultCount(), by the way, is a method provided from Search API ResultSet class.

edit: now looking at my answer, your pager service does not need to inject the RequestStack at all. I was probably thinking of another idea and never finished it or figured I did not need it.


How to modify the display of custom line items in the ADD To Cart Form? My issue is this, imagine that I have created a few custom line item types in Drupal Commerce called:

Text on TShirt FRONT
Text on TShirt BACK

I use these two fields in the ADD To Cart Form checkbox so that the customer can specify what the want on the fron of the Tshirt to say and the back. So far so good.

The issue is that how do I change the display of this product node so for example I don't want it to appear in a single column but in two columns side by side.

I have tried Panels, I have tried Display Suite, this is not working. I can't even change the order of fields say I wanted the back to show up first and then the front.

I have tried changing things around in line item configuration display, which doesn't work and I have also tried changing the disply of the product display content type, (which btw does not even show the individual fields of the add to cart forms).

I am not good with coding so I would appreciate if I can work on this from the front end with any modules.

You can add additional fields directly to the 'add to cart' form on a per item basis with the help of the Commerce Customizable Products module. This allows you to create additional custom line item types. When you create the field there is a checkbox under ADD TO CART FORM SETTINGS that will add these fields to the add to cart display.


How to display a custom render element after an existing one? So I've implemented hook_ENTITY_TYPE_view hook.

In there I add a view mode to the $build array:

$build['sessions'] = array(
  [
    "#markup" => "
Sessies
",
    "content" => array(
      Drupal::entityManager()->getViewBuilder('node')->viewMultiple($nodes, 'speaker_sessions')
    )
  ]
);

What happends now is that this will allways be rendered before all the other content. How can I manipulate this? Adding #weight to this element does not seems to effect the other content.

Are you sure that code is correct?

$build['sessions'] = array(
  [
    "#markup" => "
Sessies
",
    "content" => array(
      Drupal::entityManager()->getViewBuilder('node')->viewMultiple($nodes, 'speaker_sessions')
    )
  ]
);

It appears you are creating 2 arrays (array() and []). The given example hook_ENTITY_TYPE_view() looks like this:

$build['mymodule_addition'] = array(
  '#markup' => mymodule_addition($entity),
  '#theme' => 'mymodule_my_additional_field',
);

The problem you are likely having is because of the nested array. If you apply a weight to the inner array, it will sink to the bottom of the outer array. You however still have no control over the position of the outer array. So either use a single array and add the weight there, or use the double array as it is, but apply the weight to the outer array.

But that conflicts a bit with your question because this is not a view mode, it is just an extra render element.


Commerce- How can I modify order details with hook_commerce_paypal_wps_order_form_data_alter()? I want to modify the information Commerce sends to PayPal so that the order description on PayPal describes the product, not the order (users on my site can only order one of two products, so I think that is more useful).

This is what I want to change:

These strings are in the Commerce Website Payments Standard submodule. I am using the hook_commerce_paypal_wps_order_form_data_alter() function as suggested in the answer to this question.

However, in the API, there is no example for this function (I also looked at the Commerce Examples module but didn't find anything), and I'm a bit lost about how to handle it.

The string I want to override is defined in commerce_paypal_wps_order_form() in this section:

    // Define a single item in the cart representing the whole order
    'amount_1' => commerce_paypal_price_amount(commerce_currency_convert($amount, $order_currency_code, $currency_code), $currency_code),
    'item_name_1' => t('Order @order_number at @store', array('@order_number' => $order->order_number, '@store' => variable_get('site_name', url('<front>', array('absolute' => TRUE))))),
    'on0_1' => t('Product count'),
    'os0_1' => commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()),
  );

I want to change item_name_1 to t('My string') and remove on0_1 and os0_1.

I tried this:

function MYMODULE_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $data['item_name_1'] = t('My string');
  unset($data['on0_1']);
  unset($data['os0_1']);
}

But nothing is changed, even after clearing the caches.  I'm having a really hard time debugging this because it is called immediately before the redirect to PayPal, so even if I use dpm() I'm not able to see it.

When you can not see the HTML output of debugging tools such as dpm(), you should use the utility function dd() instead. The logging data will be stored in a file called drupal_debug.txt which you can inspect later.


Hotel Diamond and Metatag: the META information doesn't appear in front page I have a site using Drupal 7 and the Hotel Diamond theme. I am trying to add META tags to all the pages in my site (description, Open Graph tags, etc.), and it's working in all of them except the front page. What I do is:

I have Metatag 7.x-1.13
In the admin page, I go to "Modules/SEO", and I make sure that Metatag, Metatag:OpenGraph, Metatag:Facebook, Metatag:Twitter Cards and Metatag:Views are activated.
I go to "Content" and, in each of the pages, I hit "Edit" and add the descriptions in "Meta tags".
I go to "Configuration/Search and metadata/Metatag" and, in "Global: Front page", I add my description for the front page.

When I check my pages, all of them have the proper META tags... except the front page.

I've seen this question, but I don't really understand the answer: how do you assign a node to be front? Besides, in the case of Hotel Diamond, there seems to be a front page already assigned that you modify by editing it directly when logged in.

To change/set the front page go to admin/settings/site-information, where you can set the path for the node that you want to be your front page.


List all groups where the profile owner is a member? I need to put a block inside the profile page, that shows all the information of the profile owner, regardless of the logged in user. (There are some information out there in the forums about how to catch the logged in user´s information).

I need to list all groups where that user is a member of. And I can´t. I´ve tried a lot of combinations, and the last one seemed correct, why isn´t working? What am I missing?:

This is my current configuration:

Contextual filters
(author) Usuario: Uid
Provide default value (User UID from URL)

Relationships
Content: Author
(author) OG membership: OG membership from User

Filter criteria
Content: Type (= Group)

What am I missing?
Thanks for your help!!!

You should have a view that comes with OG called "OG User groups". If you clone that view and change the contextual filters to "Content ID from URL", or change your current view to reflect the provided one you should be good.

If you don't have access to the view these values should work:

Contextual filters
OG membership: Entity id

Relationships
OG membership: Group Node from OG membership


How do I filter users by status not blocked? I created a Drupal 7 view that displays users profile 2 fields. However if i disable the user their fields are still visible in the view. Is there a way i can filter users by their status of blocked or active?

The steps are:

View name: test
Show: Profiles
of type: All

Page title: test
Display format: table.

click "Continue & edit" button.

In the "FIELDS"

add the "Profile: User uid" field and add all fields related to the profile module.

Then add a relation in the path: Advanced-> RELATIONSHIPS

select the "Profile: User uid" field.

mark the checkbox "Require this relationship".

Click "apply (all displays)" button.

Then add a filter to "FILTER CRITERIA".

Seach and check the field: "User: Active"

We checked the checkbox: "Expose this filter to visitors, to allow them to change it"

Click "apply (all displays)" button.

Click "save" button.


After add node redirect to previous page How I can do this.. After Add/Edit node for specific Content type redirect to previous page..

You can achieve this by

Make sure the ?destination parameter in your url is filled out. This will redirect you to the page defined in the destination parameter.
Use the node save redirect module. This module allows you to configure the redirect path per node type after saving a node.

Node Save redirect module.

This module provides a method of specifying a location to take the user after saving a piece of content.

A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are.

  Default - Default behaviour Return to Edit page after saving
  Return to content overview page (assuming the user has access
  permissions Re-redirect to another location. (any valid drupal
  path)


How to get block id on block add & edit form? Blocks are plugin in Drupal-8, I need to add a form element in the block add form & all the block edit forms.
I am able to add the new form element in the form by form alter. But i need to get the block id on submit(custom submit handler). For block add forms block id has to be new block created & for block edit form, the existing block id.

How can i get the block id?

Have a lookt at Extend Block Class and my answer there about the block_class module.

It does exactly the same to add configurable CSS classes to blocks.


Not showing the URL pattern option Drupal 8, When we go to URL aliases section, there is no URL pattern option like Drupal 7.

Do I need to install any other modules to have this feature available?

Edit

Added screenshot

Drupal 8

Drupal 7

Those options are provided by the Pathauto module.

At time of writing, the Drupal 8 version of Pathauto is unfortunately not usable; you can follow progress here


Metatag for each content I ve used MetaTag module to change the tags in my node . but this changes me to all nodes. I want different tags for different nodes Is there any possiblities to do so?

Maybe I'm not understanding your question. You can globally change all metatag information at /admin/config/search/metatags. To change the meta information on a per-node basis, edit the node and click on the Meta Tags tab at the bottom. You can then update the meta information for that specific node:


apache 2.2 + mod_pagespeed + varnish Did anyone try the combination Drupal 7 + apache 2.2 + mod_pagespeed + varnish?

Does it produce any problem?

IS Drupal own CSS and JavaScript aggregation mechanism needed if mod_pagespeed is used?

Have yet to test it out. I do know that domain specific code CAN be better in comparison to a generalized tool like mod_pagespeed; but I would imagine it would take a lot of effort to beat mod_pagespeed. mod_pagespeed should bring an improvement in comparison to drupal's core aggregation; you will get CSS & JS Compression among some other nice things.

In Drupal land we are working on improving the page load time. Here are some projects for that.

http://drupal.org/project/wpo
http://drupal.org/project/bundlecache
http://drupal.org/project/advagg
http://drupal.org/project/css_emimage
http://drupal.org/project/imageapi_optimize
http://drupal.org/project/closure_compiler
http://drupal.org/project/cdn

Long story short: Use mod_pagespeed today; checkout some of these projects in the future.


Performance Problem: Delay on first request I put together a D7 site with a Minelli subtheme.  Along the way I experimented a lot with different themes, different modules.  Somewhere along the way I developed an odd performance issue, and now I don't really know what theme/module/config caused it.

The problem is that when I first visit the site, it takes about 15 seconds before the first page shows.  I can then move around the site and it is very responsive.  If I leave it for an hour or so, then come back to it, the first request is again very slow.

I have cleared the cache's so that shouldn't be the problem.  Also, I have disabled themes and modules which I am not using.  I moved the site to new infrastructure but the problem followed it!

Where do I go next?

There are three things that I would check.

One, if you are on a production site and not editing PHP files, then you should ensure that APC is enabled, has enough memory, and has a long TTL (you could go with a day or never expire if you wanted).  You can also consider setting apc.stat=0.  The APC docs have all of the information you need for setting the TTL.  For choosing the amount of memory, you should stick the apc.php file somewhere protected and monitor the memory usage and churn statistics.  Adjust the APC memory so that your miss rate is very low.  Initial slowness could be because APC is full and emptying out (IIRC, APC dumps the entire cache when it is full instead of employing LRU or more advanced cache strategies).

Second, make sure you have MySQL tuned appropriately.  You can use mysqltuner to adjust your buffer sizes.  Your initial slowness could be because of loading tables from disk and/or query cache misses.  While not perfect, mysqltuner does get you going in the right direction.

Third, make sure you have a real Drupal cron strategy.  Personally, I would disable automagic cron on "admin/config/system/cron" and set up a crontab to run every night.  You can also try out Elysia Cron if you really do need finer grained control over things.  This way you can the necessary tasks run as often as you need, but have the normal ones run overnight.  Your initial slowness could be from cron runs happening every hour.  You can confirm this by looking at when cron runs on "admin/reports/dblog" and trying to match up with your slowness.


Can I set a status message to be displayed when a user clicks a link? Here's my setup:

I have a page about Pineapples.  There is a link to the Pineapples page in the main navigation menu. When a user clicks that link, they go to the page.

I also have a separate link on the homepage to the Pineapples page.  When a user clicks the homepage link, I want to send them to the Pineapples page, but I also want to show a status message with a little more information.

Is there a Drupal-y way to do this?

I think you need to make a custom form with a submit button (the button should be your "link" button), and then you can do what you want.


Add a link to unflag all node By default, it just available to flag or unflag an item, reference here. I want to add a link to unflag all flagged node of current user, is there any way to do that?

At this moment, I get the code to clean all flagged node, but I don't know how to make this snippet as a link

db_query("DELETE FROM {flag_content} WHERE sid = %d", flag_get_sid());

Create a custom module that implements hook_menu().  Use that to create a path and a custom callback function that will run your query.  Something like:

/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['flags/remove/%user'] = array(
    'page callback' => 'MYMODULE_remove_flags',
    'page arguments' => array(2),
    'access callback' => 'MYMODULE_check_access',
    'access arguments' => array(2),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

// Adding custom functions, etc

To get started on creating a custom module, the Module developer's guide


How can I add an external (CDN) CSS style sheet to a theme? I'm trying to add Font Awesome to a Bootstrap subtheme I have made.

Here is the code I am using in subtheme.libraries.yml, which is based on the documentation for hosting external JS libraries in Drupal 8:

font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css: { type: external, minified: true }

Unfortunately this results in a WSOD.  The error log gives these two errors:

  Warning: constant(): Couldn't find constant
  CSS_HTTPS://MAXCDN.BOOTSTRAPCDN.COM/FONT-AWESOME/4.5.0/CSS/FONT-AWESOME.MIN.CSS
  in Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension() (line
  143 of
  /srv/bindings/code/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).

And:

  Warning: Illegal string offset 'weight' in
  Drupal\Core\Asset\LibraryDiscoveryParser->buildByExtension() (line 143
  of
  /srv/bindings/928c941920f8443d9e50a3d908967fee/code/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).

My understanding was that for a sub theme you defined the CSS as such:

global-styling:
  css:
    theme:
      css/style.css: {}

...as discussed here: https://www.drupal.org/node/2165673


Edit button on content which users have permissions to edit, including their profile If I am logged in as an administrator, I get the contextual edit buttons an all blocks and nodes and can edit. If I am logged in as a user with less permission, but still enough to edit that content, those buttons aren't there. There are also no edit buttons on the user profile pages for any types of user, so if you are not an admin, you cannot easily edit this. I was hoping for a way to either turn on the contextual admin style pencil buttons for all users with permission to edit a specific bit of content, or at least be able to add my own buttons in the node or user template if allowed.

Contextual Links are a Permission that can be enabled for different roles via admin/people/permissions. If enabled, it will only show the options that user has access to.

If I wanted to add my own custom buttons in different situations, I'd start with Display Suite which allows me to create custom fields (which might be my buttons) and show/hide those buttons based on View Mode, content type, etc.


How to make billing cycles available as product attributes? On our current billing system (from which we are trying to switch to Drupal Commerce) customers can select a product and then easily select between monthly, quarterly and yearly payment periods. In other words, billing cycles can be selected as product attributes.

And I can't figure out how to make billing cycles available as product attributes on a DC setup. According to the instructions on Commerce License Billing products are bound to billing cycle types. Does that mean I have to create three different products (for each monthly, quarterly and yearly billing cycles) for every single good or service product we offer on our website to customers? Doesn't make much sense for websites selling tens different types of services. I would appreciate if someone could point me to the right direction of configuring this.

Yes, you need to create different products that are linked to the billing license configurations you want. This means that if you want monthly, quarterly, and yearly billing options, these would each be tied to products and then available via a dropdown.


entity_metadata_wrapper Changes not being saved to user Profile2 profile Challenge:

I have a profile2 taxonomy term reference field (single select) on user profiles called "field_member_interest_group".
On save/update of the user profile, I wan to A) See if the user has a role of "Elephant", then if so, select the term of "Elephant Group" from that user's taxonomy term reference field and save the changes.
"MYMODULE" is the name of my module in lowercase.

My (not working) Code:

function MYMODULE_user_update(&$edit, $account, $category) {
    $account = user_load($account->uid);
    $profile_profile = profile2_load_by_user($account->uid, 'profile');
    $profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile->pid);

    if (in_array('Elephant', $account->roles)) {
        $termX = 3942; //tid of "Elephant Group"
    }
    $profile_wrapper->field_member_interest_group->set($termX);

    //Save changes to the profile entity
    $profile_wrapper->save();
}

Problem:

The changes are not saved to the user account, they are ignored completely.

Any thought on what could be going wrong?

I believe entity_metadata_wrapper expects the second parameter to be an object. As in:

$profile_wrapper = entity_metadata_wrapper('profile2', $profile_profile);


Is there a list of default fields and default widgets for drupal 7 Where can I a list of available (in the core) fields and widgets and their names so I can reference them when adding fields to my own node-type definitions ?

To get a list of all field definitions use field_info_fields()

Returns all field definitions.
Use of this function should be avoided when possible, since it loads and statically caches a potentially large array of information. Use field_info_field_map() instead.

You can ignore the second paragraph of that as field_info_field_map() hasn't actually been included in a Drupal release yet.
For widgets use field_info_widget_types()

Returns information about field widgets from hook_field_widget_info().


Can Drush update custom modules? I'm currently using Drush Make to pull custom modules, installation profile, and various other modules/libraries when I provision a new Drupal site.

What I'd love is if I could use drush upc to update my custom modules.  I'm not sure if this is possible if I provide some magic meta data to drush or include my .git with a specified remote host.

My understanding is that Drush leverages the update status module in core for this functionality so this may not necessarily be a Drush specific issue.

Any help or suggestions on where to look would be appreciated.

As you said, Drush relies on the update status module of Drupal to find code updates.  If you wanted to use this mechanism for your own custom modules, you would have to make a server that had clones of the d.o modules you used, since pm-updatecode works with a single update server, and also has the same xml data structure for the releases of your custom modules.

There are two easier solutions:

Publish your custom modules on drupal.org - very easy, and a great option if your modules can be shared openly.
Just check out your custom modules from git; after running pm-updatecode, iterate over each custom module and do a 'git pull'.

The later could be integrated with drush pm-updatecode, either as a post-updatecode hook or as a feature request submitted in the Drush issue queue (patches welcome).


BrowserTest on a multisite gives an error My sites directory looks like this:

default, site1, site2, site3.

The default directory is empty. I want to run tests against my site1 database. So I have put its details in phpunit.xml

Here is my phpunit.xml set up.

  <php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value="http://d8.site1.dev"/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="mysql://site1:site1@localhost/site1"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value=""/>
  </php>

And then my actual test:

<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;

/**
 * Simple test to ensure that main page loads with module enabled.
 *
 * @group my_module_tests
 */
class LoadTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['my_module'];

  /**
   * A user with permission to administer site configuration.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->user = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($this->user);
  }

  /**
   * Tests that the home page loads with a 200 response.
   */
  public function testLoad() {
    $this->drupalGet('node/add/product_list_page');
    $this->assertResponse(200);
  }

}

Then from the core directory of Drupal I run:

../../vendor/bin/phpunit --group my_module_group

Then I get this error:

1) Drupal\Tests\my_module\Functional\LoadTest::testLoad
copy(/var/www/site/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

Why is it looking in my empty default directory and not site1 for this file?

It is possible to have a multisite directory setup with PHP Unit.

Since your default directory is empty, I suggest creating a symbolic link from the default directory to the site1 directory. You can do that by using commands similar to this one from sites directory.

ln -s sites1 default

Not sure, but you may also need to adjust the $sites variable in sites.php.

Also, make sure you specify a printerClass like this in the last line.

<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">

Here is what my php tag looks like in phpunit.xml (I use SQLite though and specify an output directory.) You may need to adjust directory permissions so that it is writable. I test on my remote machine with a FQDN, not sure if that is ideal though.

<php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value="https://dev.example.com"/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="sqlite://dev.example.com/sites/dev.example.com/files/.ht.sqlite"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/path/to/document/root/sites/dev.example.com/files/simpletest/browser_output"/>
</php>

Also, I run the phpunit command from the Drupal core directory like this (I do not use group ID but I know it may be possible.

sudo -u www-data ../vendor/bin/phpunit ../modules/contrib/example/tests/src/Functional/ExampleHomepageTest.php

Here is what my test looks like. It will need the correct directory structure and classname.

<?php

namespace Drupal\Tests\example\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests to ensure Example.com Homepage is reachable
 *
 * @group example_ui
 */
class ExampleHomepageTest extends BrowserTestBase {

/**
 * Modules to enable.
 *
 * @var array
 */
protected static $modules = ['node', 'user'];

protected $profile = 'standard';

/**
 * {@inheritdoc}
 */
public function setUp() {
parent::setUp();

}

/**
  * Tests that the reaction rule listing page works.
  */
public function testHomepage() {

  $account = $this->drupalCreateUser(array('administer site configuration'));
  $this->drupalLogin($account);

  $this->drupalGet('<front>');
  $this->assertSession()->statusCodeEquals(200);
  $this->assertSession()->pageTextContains('cleaning');
 }
}

This page will be useful: https://www.drupal.org/docs/8/phpunit


error 500: Premature end of script headers: index.php Everything works except the /node/[nr]/edit page of only one content type page. And it's not for every page of this specific content type. Only one.

So let's say I have a content type "product" and created 5 nodes with that content type. Editing 4 of them works but for one the error 500 Premature end of script headers: index.php occurs.

I tried increasing the memory limit in the php.ini all the way up to memory_limit = 1024M (and restarted apache after that) but this changes nothing. Btw I'm using Acquia DevDesktop and the PHP version is 7.0.15. I also tried downgrading the PHP version (and there also increased the memory limit) but this won't do anything either.

Please help me, I'm incredibly thankful for every answer I can get!

@mcaleaa answer helped me on an acquia based site. To fix it I commented out the following lines in development.services.yml:

parameters:
  http.response.debug_cacheability_headers: true


How to properly alter the output for fields of type file? I have a file upload field which's format is set to generic file. It prints the following markup:

    Lorem ipsum

    ...

But I'd rather not show the img at all, alter url text, something similar like this:

    $filename
    $description text of this field

What hooks would I have to use for this? And why is this so hard to find on the docs?!

I'm guessing a bit here as I can't see what you have installed/configured...

The file formatter function is file_field_formatter_view(), and the only formatter which has an image attached to it runs through theme_file_link(). I would assume that's where the markup you're referring to comes from.

You can override that in your theme:

function MYTHEME_file_link($vars) {
  ...
}

Or, if you can get away without having to reproduce the function, just preprocess is:

function MYTHEME_preprocess_file_link(&$vars){
  ...
}


Accessing Webforms Parameters in hook_form_alter I got a webform which is embedded in a paragraph template. I do this via renderArray which works pretty well - the form is embedded. However I need to grab parameters - the only example I could find is about how to get "GET" parameters or about how to set default values via parameter. This is not what I need. I need the host paragraph as ID in my hook_form_alter. But I cannot find the value.

     {{ {
       '#type': 'webform',
       '#webform': 'contact',
       '#values': {
         'paragraph_context': 21
       },
       '#parameters':[{'a':'1122'}]
       } }}

The hook_form_alter $form array should contain either "#values" or '#parameters' but they are not included. - at least not in an easy findable location.

Are they in any deep sub sub sub location in the array?
or is there a mystic way to define the parameters for the webform, so hooks can pick them up?

Oh when you ask your self why I just don't use the default value to fill the value of a field directly... The reason would be, that I actually have to create the select form field options first. That's why I need the id to the paragraph - it contains all the holy data stored in its entity.
===================================== EDIT ================
After 3 hours of searching and heavy use of Xdebug I found it.
$form_state->build_info["callback_object"]->originalData['value_name']

However it is a protected property. So I cannot access the value. There must be an easier way to get form parameters. Is there any?

I can't see a way to access the originalData property you mention. It's a protected property and there's no getter defined. See the callback_object's class in the webform module at src/WebformSubmissionForm.php.
I'd take a slightly different approach here. Since you are building custom values based on the paragraph id, it seems appropriate for the paragraph id to be included with the submission data. To do this, add a new hidden element to your webform for the paragraph id, e.g. with machine name paragraph_context.
Then, to provide a default value for your hidden field, update your twig like:
{{ {
  '#type': 'webform',
  '#webform': 'contact',
  '#default_data': {
    'paragraph_context': paragraph.id,
  },
} }}

(Note: I don't see any mention of the values or parameters options you're using in the How to embed a Webform documentation on d.o.)
Lastly, access your paragraph_context value via the #default_value key for your hidden element in your hook_form_alter(). For example:
mymodule_hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id' && !empty($form['elements']['paragraph_context'])) {
    $paragraph_context = $form['elements']['paragraph_context']['#default_value'];
  }
}


usage of theme_more_link in zen template.php I have tried to change the text in the 'Read more' link by putting:

function myzen_more_link($url, $title) {
  watchdog("template.php","myzen_more_link");
  return '
' .
    t('( more ... )',
    array('@link' => check_url($url),
    '@title' => $title)) . '
';
}

In the template.php in my zen subtheme folder but it does not appear to work.

Almost all of the discussions I have seen about formatting the "more_link" concentrate on its placement.  Can anyone tell me why this theme override does not take effect?

What you have done should work. Have you remembered to clear cache?


Alter the wrapper of radios buttons in a custom module In a custom module, I have created a custom form. In this form, I need to alter the markup of the radio buttons wrapper and add a new attribute.
After reading many posts and testing, I can alter all the form elements (form-item, first fieldset...) except this wrapper.

This is the markup I am outputting.

<fieldset ...>
  <legend>Mylegend</legend>

    ...

          ...

  </fieldset>

I see that the related system template is radios.html.twig. I tried to copy and paste this template in the templates directory of my module without success. I tried to use theme => 'my custom theme' in the definition of my field. I tried to use a preprocess function in my module.

What is the simpler method to alter this wrapper?

You can do this directly in the form.

Add this to the radios element:

'#attributes' => [
  'attribute_name' = 'attribute_value'
],


Alternative to drupal_goto Within a page callback, I need to:

Create a new node.
Retrieve the nid from that new node.
Create an entity reference in an already existing node (referenced in a parameter passed to my page callback) TO that newly created node.

The first thought was to use drupal_goto. However; drupal_goto "ends the request".

  (per
  http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_goto/7)

As expected, I execute the drupal_goto('node/add/newnode'); The node gets created, and I'm out of the page callback...

Any suggestions would be most welcome!

Perhaps something like this:

function mymodule_page_callback($parent_nid){

  global $user;
  try{
    // Create new node, assumes default LANGUAGE_NONE
    $node = new stdClass();
    $node->title = 'Title';
    $node->type = 'my_type';
    $node->language = LANGUAGE_NONE;
    $node->uid = $user->uid;
    $node->status = 1;
    node_object_prepare($node); // Sets some defaults.
    $node = node_submit($node); // Prepare node for saving
    node_save($node); // Returns $node by reference with nid

    // Set entity reference on parent node
    $parent = node_load($parent_nid);
    $parent->field_entity_reference[LANGUAGE_NONE][] = array(
      'target_id' => $node->nid
    );
    // Save parent
    node_save($parent);
    // Go to edit form for new child node
    drupal_set_message("Node created");
    drupal_goto('node/'.$node->nid.'/edit');
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
    drupal_set_message("A problem occured creating the node", 'error');
    drupal_goto(); // front page
  }

}


Designing different content types with the same fields' name (shared fields) For my website I need several content types (at least five), but all that have some fields' name in common as title, subtitle, body, teaser, image and so on.

Shall I use the same field (machine name) for all the content types or is better an its own field for each content type?

For example, if I have the two content types "articles" and "recipes" and create the field "field_subtitle", shall I use this field for both content types or is better to create the two fields "field_articles_subtitle" and "field_recipes_subtitle"?

Are shared fields better or worst in term of performance?

Performance isn't a huge issue in my opinion, the advantages you will gain from having correctly built relational data will outweigh any performance gains.

Use the same field across your different content types. If you are storing the same "thing" then semantically using the same field has many advantages.

Doing things that are common to that field work across content types. Eg, pulling out the subtitle and displaying it under the H1 in the page template.
Some common settings across the entities. This means that if you know a subtitle will never exceed 200 characters, you need only enter this one, keeping your models a little more dry.
If you would like to ever list these things together, you can use views to list the common fields with no extra effort.
CSS can be written more generically. Subtitles are usually grey and italic, this can be applied across bundles or entities much easier if the fields are common.

There are some disadvantages of creating lots of fields across entities to represent the same data:

Messy field lists and lots more database tables. While this wont have too much of an impact on performance, it's simply a technical debt that can be avoided.
Messy code. Having to reference ->field_articles_subtitle vs ->field_subtitle is simply duplicating information we already know (that we are working with an article).

In terms of CSS, if you would like to define custom types of formatting to different entities you can always use:

.node-type-article .field-field-name{ custom-css: true; }

In short, for the example you stated use the same field.


Theming / modifying the markup of default search block form I'm trying to modify the basic search block form that comes with Drupal 7 core. I have a custom theme and inside my templates folder I copied the search-block-form.tpl.php and modified it like so

<form action="/fi" method="post" accept-charset="UTF-8" class="ng-pristine ng-valid form-inline" novalidate role="form">

        <input
            title="<?php print t('Type in your search terms'); ?>"
            type="text"
            name="search_block_form"
            value=""
            maxlength="128"
            class="form-text" />

    <?php print $search['hidden']; ?>

<button
    type="submit"
    name="op"
    class="btn btn-default">

</button>

But when I look my rendered markup on page it is totally different.

<form action="/fi" method="post" id="search-block-form" accept-charset="UTF-8" class="ng-pristine ng-valid">

            <input title="Type in your search terms" type="text" name="search_block_form" value="" maxlength="128" class="form-text">

    <input type="hidden" name="form_build_id" value="">
    <input type="hidden" name="form_id" value="search_block_form">

<button type="submit" name="op" class="btn btn-default">

</button>

</form>

Why is there an extra div inside the form and where is my form-inline class and who put that id on my form? Why isn't my markup rendered as I wrote it? I also tried to remove all unnecessary preprocessing by overriding xxx_preprocess_search_block_form and xxx_form_alter but nothing seems to work.

And yes I have tried to clear theme cache many times.

This is driving me insane about Drupal. All this "magical" stuff that keeps happening when I'm trying to accomplish even the most simplest templating tasks. Could someone please explain what is going on? Thanks!

First of all nothing is "magical" and if you are new to drupal then you have not looked into the Form API or ignored it.

What you are trying to do resides on hooking into the form api using the hook_form_alter or hook_form_FORM_ID_alter functions.  The "magical" inline elements on your form are being handled by the form API I spoke of.  You are trying to enter form elements and a button into a template file which is not only a security issue but is not the way that drupal handles forms.

You will need to create a custom module and add your hook_form into there and use the form api I spoke of to handle what you are trying to do.


Rewriting output of a field in node.tpl One way is to use $node->field_myfield[LANG][0][value]="value" that needs another line for getting field's language using field_language().

Is there an easier and cleaner way?

You should use the field_view_field() function. Have a look at Rendering Drupal 7 fields (the right way).


Weekly Calendar Block I'm looking to display a weekly events calendar. I've set up content type event and added a starting day field. What I'm essentially looking for is this:

So the interface is a tabbed one, so as long as I can get the current week and its events grouped by date I should be fine, but I need to be able to pull future weeks via ajax in a manner the Calendar View does. So the question is this: can this be done with some Calendar View template? How can this be put together with views? I tried to modify the Calendar block provided as Views Template, but all I ended up was a monthly block.

Thank you in advance.

You can do something quite close to that with views.  When you set up your view (or just use the one that comes with the Calendar module and clone it and start editing your new copy).

Just make sure you go to the Calendar settings and choose 'Week' as your Calendar type:

Of course, you have to choose which fields to display for your event type and here's what you'll roughly end up with:

I've added css to my theme to change the look of this calendar page, and that's probably a separate topic.  Most of the functionality you want is available through the calendar module... just set your type!!

Hope this helps.

================= EDIT =========================

So, after reading your comment, here's how I'd modify the solution above.  Same calendar, but choose 'Day' as the calendar format.  Then under the 'Header' section, add a Header and choose "Global: text area".  Here, using php, we can output links to how many ever days you need before and after today's date... since this doesn't happen automatically.  You'd need to enable the php filter module to make this possible.

So, using the 'php filter' format for the global text, you can add the following code (I would check it to display even for empty views...):

<?php
print( "" . date('l') . " | ");
print( date("l",strtotime("+1 days")) . " | ");
print( date("l",strtotime("+2 days")) . " | ");
?>

The above just prints out today's week day, then tomorrow and the day after.  You can change to suite your needs.  I've also only printed the first one as a link.  You see, the day calendar format can be navigated by just going to /2012/11/23 to get to Nov. 23rd of this year, etc.  Very easy to figure out the links, so you can build your own menu using php in the header.

This is the output you'd get, and of course, you can always beautify with css:


Remove Drupal Login Link I'm trying to remove the login link from the Drupal site.

However, despite the User login being set to none. It still shows on the site.

Is there a way to hide the link?

Thank you,
Kevin Davis

There is a login block that you need to disable.
structure > blocks disable the login block.


Drupal commerce order total ignore changed unit price I have problem with commerce order total counting.

Every product has two prices (two fields). One price for everybody and second for exact role. I have rule which change prices if user with exact role is logged in.

When i browse product with exact role all prices are ok. If i add some product to cart a go to my cart product prices and total price is still good. But when i go to checkout total price is set to 0.

In checkout are all products with good price but total price is 0.

Rule for changing price is simple:

event: calculate product price
condition: user role
action: set a data value (commerce-line-item:commerce-unit-price -> second price field)

Do anybody know what could be wrong? Thanks for every advice.

Try to downgrade rules to v 2.7. For more details look at https://www.drupal.org/node/2408705

  Important: Rules 2.8 has a critical regression that causes checkout
  rules to not work. Follow #2403851: Commerce pricing rule not working
  for more details, and downgrade to 2.7 for now.


Cannot access responsive image sources from Twig In Twig I am unable to retrieve the file source for each responsive image style on a ImageItem. How should I be getting this information?

-You can use a theme hook to wire in the responsive image sources (yourtheme.theme)

-You can set your content / (or custom entity) "manage display" / the image field: set responsive display. So it will send to the dom all of the url's when rendering the item.


How do I dynamically set up different cookies for multiple domains? My site uses the Domain Access module to maintain multiple domains and sub-domains, such as:

www.domain1.com, apple.domain1.com, orange.domain1.com
www.domain2.com, dog.domain2.com, cat.domain2.com

Users from the same domain (for example, domain1.com) should be able to go back and forth between the different sub-domains (www, apple, orange) without having to log in each time.

If I set the cookie domain inside services.yml, users from domain1 will be able to go back and forth between domain and sub-domain; however, users from domain2 won't be able to use the site.

parameters:
  session.storage.options:
    cookie_domain: '.domain1.com'

If I don't set cookie_domain, users from either domain will have to log in each time when they go between sub-domains and domain.

In Drupal 7, it was possible to change the cookie configuration dynamically as explained on cookie domain disables other top domains.

In Drupal 8, the cookie_domain is set in a YAML file that can't be changed dynamically. A workaround on Drupal 8 is to load dynamically a different YAML file as explained here: https://bit.ly/2Nwgzlr. However; this is not an option for sites with a large number of domains and sub-domains.

Writing a new YAML file per site and modifying the settings.php every time a new domain is added to the pool, is not the most productive way. There is always a way of overriding things inside the Drupal code. I hope this is not the exception.

Can anyone tell me what hook or class I can use to implement the logic I need?

You should be able to do this by altering the services container: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services.

You can put your logic in there to dynamically set/override values that would usually be set static in a .yml file.


Collapsable, grouped field in View (Bootstrap, D8) I am setting up a view in Drupal 8, but am stuck on a problem. I'm using a table view, where some of the fields are grouped. These fields can have from 0 to maany values. Therefore, I would like to "collapse" them, showing only the first value unless you click to show them all.

I found a javascript that seemed to be just what I wanted ( https://jsfiddle.net/z0qvv7tk/11/ ), however, I can't seem to be able to utilize it. I loaded the script in  and tried several things to get add the ul class to my list, including:

Editing the tpl-files for view, both under my theme and on views directly. In hindsight I suspect I was editing the list-style view, and not the list for the fields in one of my attempts.
Rewriting the fields - this also didn't yield any results since the field is grouped.
Adding css-classes to the field - of course this didn't work, since I need to add it to the list, not the item.

I am using lists to show the grouped fields. The view can be found here. The field in question at the moment is the field for members, but I would like the same effect for some of the others eventually.

Since I couldn't get the script working, I started looking for modules. I tried Views Accordion, Views Fieldset, Views fieldsets among other, with none of them working as I intended.

After this I discovered that Bootstrap has various collapsable options, and I tried rewriting/editing the .tpl again - with no luck.

Can any one help me in the right direction? As long as it is collapsible, preferably showing the first value, I am open to any solution.

I solved it using Bootstrap. I hid the field, then added it one more time. Then I rewrote the second field like this:

Show members

{{ field_research_group_ext_members }}
{{ field_connected_user_names }}


Messing with several versions of drush When I run
drush --version

I get next output:
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
 Drush Version   :  7.4.0

For getting rid of the warning, I have been told I to install drush version 8.
So I issued:
composer require drush/drush:8

giving next result:
./composer.json has been updated
Running composer update drush/drush
Loading composer repositories with package information
Updating dependencies
Nothing to modify in lock file
Installing dependencies from lock file (including require-dev)
Nothing to install, update or remove
Generating autoload files
9 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

So I suppose drush was already at version 8, but issuing the command above, I still have the same result: version 7.4.0. I am probably messing with several versions of drush.
I would like to understand better how to get rid of the old version, and being sure I am using the last one.

You are mixing up the globally installed Drush with a locally installed Drush. To run the local Drush from your project, run vendor/drush/drush/drush --version from inside your project. This will give you 8.0.0 which is a bit old. Better get the latest Drush 8 release with composer require drush/drush:^8. Currently this is Drush 8.4.8.
Next, you can consider to either update the globally installed Drush (not recommended) composer global require drush/drush:^8 or alternatively (recommended) install the Drush Launcher instead. The Drush Launcher is just a wrapper command to always pick up the project-local Drush. So you can easily run Composer-based D7 and D8/D8+ projects on the same machine in parallel and calling drush --version in a project will adjust accordingly.
If your project is D8 or D9 install Drush 10 instead composer require drush/drush.


How to add autocomplete to a textarea on a form? I would like to add autocomplete functionality to a textarea form element in Drupal 8. I have a fully functioning custom textfield which has autocomplete working on the same form. I have confirmed that the Textarea element has the processAutocomplete function. Therefore, I'm uncertain as to why this wouldn't work.

I realize that adding an autocomplete to a textarea is a bit unorthodox, but that's not the question. I have seen this done in Drupal 8, so I know it's possible. I just don't know if they used a form to accomplish it.

I have added the appropriate code in the routing file:

my_module.autocomplete_name:
   path: '/my-module/test-autocomplete'
   defaults:
     _controller:'\Drupal\my_module\Controller\Controller::functionName'
     _format: json
   requirements:
     _access: 'TRUE'

I have also added the field appropriately on the form:

$form['text_area'] = [
  '#type' => 'textarea',
  '#title' => t('Test text area'),
  '#default_value' => $authentication_configuration->get('text_area'),
  '#autocomplete_route_name' => 'my_module.autocomplete_name',
];

Finally, I have the appropriate logic in the referenced controller:

public function testAutocomplete(request $request) {
  // Set up the array to be returned and get the user input
  $matches = array();
  $input = $request->query->get('q');
  // If there is user input
  if ($input) {
    $words = explode(' ', $input);
    foreach ($words as $word) {
      /*
       * Logic for generating an autocomplete list of matches
       */
    }
  }
  return new JsonResponse($matches);
}

Textareas don't support autocomplete out of the box, you have to get a bit creative to make it work.

First you'll need to override the attach method of the autocomplete behaviour; add a library with a JS file containing this:

(function ($) {
  Drupal.behaviors.autocomplete.attach = function attach(context) {
    var $autocomplete = $(context).find('input.form-autocomplete,textarea.form-autocomplete').once('autocomplete');
    if ($autocomplete.length) {
      var blacklist = $autocomplete.attr('data-autocomplete-first-character-blacklist');
      $.extend(Drupal.autocomplete.options, {
        firstCharacterBlacklist: blacklist || ''
      });

      $autocomplete.autocomplete(Drupal.autocomplete.options).each(function () {
        $(this).data('ui-autocomplete')._renderItem = Drupal.autocomplete.options.renderItem;
      });

      $autocomplete.on('compositionstart.autocomplete', function () {
        Drupal.autocomplete.options.isComposing = true;
      });
      $autocomplete.on('compositionend.autocomplete', function () {
        Drupal.autocomplete.options.isComposing = false;
      });
    }
  };
})(jQuery);

The function is a straight copy of the core attach method, with the textarea added to the selectors, and a few references altered.

Then you'll need to add the autocomplete process method to the form element (it's not there by default), and also reference your library:

use Drupal\Core\Render\Element\Textarea;

...

$form['text_area'] = [
  '#type' => 'textarea',
  '#title' => t('Test text area'),
  '#default_value' => $authentication_configuration->get('text_area'),
  '#autocomplete_route_name' => 'my_module.autocomplete_name',
  '#process' => [
    [Textarea::class, 'processAutocomplete'],
  ],
  '#attached' => [
    'library' => [
      'mymodule/autocomplete'
    ],
  ],
];

Clear the cache and you should see the results immediately.


Programmatically modifying global custom text field in view I have a (Apache solr) view with a Global: Custom text field in addition to my normal fields. This field is meant to get value from a custom function/existing field/passing an existing field to a custom function and using return value in one of my modules per each result and I am trying to accomplish this functionality without using Views PHP module.

I referred this very similar query and tried the following approach which did not yield me the result:

hook_views_pre_render:

function mymod_views_pre_render(&$view) {
  if ($view->name == 'mymodview' && $view->current_display == 'mymod_display') {
    $result = &$view->result;
    foreach ($result as $num_idx => $result_obj) {
      $result[$num_idx]->nothing = $result_obj->an_already_available_field_or_fxn_call;
    }
  }
}

Also tried the same code with hook_views_post_execute to no avail. Using $view->field['nothing']->options['alter']['text'] = 'My custom text'; set the default text value to all fields which was not my desired result.

Based on the post linked earlier tried the following code in my theme's template.php

template_preprocess_views_view_fields:

function mytheme_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  if ($view->name != 'mymodview' && $view->current_display != 'mymod_display') {
    return;
  }
  foreach ($view->field as $id => $field) {
    $vars['fields']['nothing']->content = 'Some global custom text content';
  }
}

I am unable to determine what I am missing out on owing to my relative inexperience with views functionality and guidance on achieving this programatically would be much appreciated.

have you tried to use a custom handler? This way you don't need to override nothing.

Related to: Move php in views to module


How to create content type "News" A site user needs to be able to add news to Drupal 8 site.

Some news might be own contents and some news might be from external sources.

If the site user is adding a news which is from an external source, the site user should be able to add a node by just entering the source URL(i.e. examplesite.com/xyz).

If the site user is adding a news which is their own content, the site user should be able to add a node by entering the contents which may have number of paragraphs with titles and few images for each node.

Site user also should be able to add nodes without any coding.

I already create a role and the user for the role.

I created a content type "News" which currently have title and body fields.

How can I create a content type which meets the above requirements?

It sounds like you're off to a good start. Next, you'll need to add a new field to your content type for links to external news articles.

Home >> Administration >> Structure >> Content types >> News >> Manage fields

/admin/structure/types/manage/news/fields/add-field

Add a new field of type Link and label it something like News Link. Save the field.

Decide if you want to allow only one link to be saved in this field, or multiple values. Save the field settings.

Decide if you want to allow external links only in the field (the default is "Both internal and external links"). Save settings.

After that, you'll still need to make a whole bunch of decisions about how to display News content items ... but the Link field seems to be a missing link in your description.

Good luck!


How would I apply a transition to a State Machine field? I am trying to transition a state_machine field on the User entity during an event. What I have thus far is:

/* @var \Drupal\user\Entity\User $user */
$user = User::load($id);

/* @var \Drupal\Core\Field\FieldItemListInterface $state_field */
$state_field = $user->get('field_screening_status');

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $state_field->get(0);

$transitions = $state->getTransitions();

$state->applyTransition($transitions['mark_needs_screening']);

Of course, this does not actually save it to the user. I would actually need to call:

$user->set('field_screening_status', 'needs_screening');
$user->save();

But, how might I instead use the state_machine API to apply the transition to a user field?

Here's what I ended up with. Would be curious if the community has a better solution.

/* @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser());

/* @var \Drupal\state_machine\Plugin\Field\FieldType\StateItemInterface $state */
$state = $user->get('field_screening_status')->get(0);

$transitions = $state->getTransitions();

if (array_key_exists('mark_needs_screening', $transitions)) {
  $user->set('field_screening_status', 'needs_screening');
  $user->save();
}

UPDATE: Thanks to @lisastreeter in #commerce on drupal.slack.com

$user = User::load($id);
$state = $user->get('field_screening_status')->first();
$transition = $state->getWorkflow()->getTransition('mark_needs_screening');

if ($transition) {
  $state->applyTransition($transition);
}

Not sure if that get(0) change to first() really made the difference, but it works now.


Calendar Prev/Next buttons linking to wrong dates In the calendar month display for August with the path calendar/2015-08, the forward and next page buttons offer the user a link to October -- completely jumping over September straight to October.

That is, the Next link in the above picture jumps straight to
calendar/2015-10.

I'm at a loss. I've tried cycling Ajax in the view which did nothing.

I'm running the following modules:

$ drush pml | grep calendar
 Date/Time  Calendar (calendar)               Module  Enabled        7.x-3.5
 FullCalen  FullCalendar (fullcalendar)       Module  Enabled        7.x-2.0
 dar        (fullcalendar_colors)
 dar        (fullcalendar_legend)
 dar        (fullcalendar_options)

And I see the this view is rendered in the ./sites/all/modules/date/date_views/theme/date-views-pager.tpl.php

<?php if (!empty($next_url)) : ?>
 49       <li class="date-next">
 50         <?php print l(($mini ? '' : t('Next', array(), array('context' => 'date_nav')) . ' ') . '&raquo;', $next_url, $next_options); ?>
 51       </li>
 52     <?php endif; ?>

drush dl date --select
Choose one of the available releases for date:
 [0]  :  Cancel
 [1]  :  7.x-2.x-dev  -  2015-Jun-16  -  Development
 [2]  :  7.x-2.9-rc1  -  2015-Mar-27  -  Supported
 [3]  :  7.x-2.8      -  2014-Jul-29  -  Recommended, Security
 [4]  :  7.x-1.x-dev  -  2013-Sep-30  -  Development

So if I have 7.x-2.8 - It's okay.   7.x-2.9-rc1 or  7.x-2.x-dev  both jump ahead by two months.drush dl date --select

Of the ones available, dev and rc1 have an issue with the next button. 2.8 is fine but it defaults the calendar name to include the first day of the month. So you must choose between a bad title format or a bad next button.

My solution: I moved back to Date 7.x-2.8 and then overrode date-views-pager.tpl.php in my theme with the following:

<div class="date-nav-wrapper clearfix<?php if (!empty($extra_classes)) print $extra_classes; ?>">

<?php
        print date("F", strtotime($nav_title))
            . ' '
            . date("Y", strtotime($nav_title));
        ?>


What is the best workflow to migrate a site using domain access? i have a site with 20 subdomains using the domain access module on a dev server and i want to migrate them to a production server.

There is only a change from

  subdomain.maindomain.eu

to

  subdomain.maindomain.de

What is the best to do it ?

Can you be a little more specific, are you just wanting to migrate the whole database to a new installation or are you migrating content into an existing installation

In the first case it should be fairly simple,

Put your site in maintenance mode and then flush all the caches.
Take a backup of your sites directory.
Copy the database to the new server.
Upload the drupal installation and then the sites directory to your new server
Modify the settings.php to connect to the database on the new server.
Using a DB admin tool such as phpmyadmin modify the "domain" table in the database on the new server, there is a field in this table called "subdomain" this relates to the url of your domains so just modify this to suit your needs.


Adding a subtitle to the main title My Website name is Subham Soni.

I want to add two more lines below it.

One as "Developer" and then in another line a quote along with the author.

How do I do it?

As @Smalution pointed out, this is generally done using the site Slogan option which is set at /admin/config/system/site-information.

This is the standard way of doing this but relies on the theme you are using have the line

<?php print $site_slogan; ?>

Some where in the page.tpl.php

If you are creating your own theme, or hacking some one elses make sure this is in there. But, in some themes (this goes for Garland that ships with D7) you will see something like

<?php print $site_name_and_slogan ?>

in the page.tpl.

This is because the page template has gone through a preprocess function in the template.php i.e function garland_preprocess_page(&$vars) and the slogan has been wrapped with the title and a new variable created :

$vars['site_name_and_slogan'] = $site_name_text . ' ' . $slogan_text;

So if you can't see $site_slogan straight away that's probably why.


How to add fields from other modules in Drupal 6 Views? I have a Drupal 6 website with Ubercart 2 and the "Delivery time slots for Ubercart" module installed, and I have created a View to pull a custom report of order info. I need for that report to also include the delivery time slot chosen by the shopper on each order, but that module apparently does not have Views integration. Is there a way for me to pull the time slot value (and/or any other arbitrary database field that related to the other data I am pulling in, I assume based on the order ID) for each order into the view?

I appreciate any feedback! Thanks!

You can try out the below modules. They are meant for getting data directly from the database into views.

Table Wizard

Data Model

If both of them doesn't suit your requirement then you could use the Views Custom Field write php code directly into the view and collect the required fields using database queries.

You could also do the direct query with in the views template files.


How do I get third party jQuery plugins to work with Drupal? I am trying to use the Slider Revolution jQuery plugin (from ThemePunch) on my Drupal site to create a slider on the front page.

I cannot for the life of me figure how to get this working. I have manually built a simple HTML page (outside of Drupal) to check the plugin and it works flawlessly, I just cannot seem to get it working in Drupal.

Drupal version: 7

Slider Revolution version: 4.1.2

Instructions for Slider Revolution: http://pastebin.com/gxNSV4hh

My theme is using jQuery 1.9.0

I have added into mytheme.info:

scripts[] = js/rs-plugin/js/jquery.themepunch.revolution.js
scripts[] = js/rs-plugin/js/jquery.themepunch.plugins.min.js

I have added to my front page:

My Caption

            ...

My Caption

            ...

        ....

Using Tracking Code module I have added (before /body) :

Slider Revolution file jquery.themepunch.revolution.js is structured like:

(function(jQuery,undefined){

    ////////////////////////////////////////
    // THE REVOLUTION PLUGIN STARTS HERE //
    ///////////////////////////////////////

    jQuery.fn.extend({

    // OUR PLUGIN HERE :)
    revolution: function(options) {
    ...........
    ...........
    }})

})(jQuery);

Slider Revolution file jquery.themepunch.plugins.min.js is structured like:

(function(t){"use strict";var e=t.GreenSockGlobals||t;if(!e.TweenLite){
    ..........
    ..........
);

(function(e,t){
    ..........
    ..........
})(jQuery)

How do I go about implementing this in Drupal? I believe Drupal expects jQuery/Javascript to be in a specific format (https://drupal.org/update/modules/6/7#javascript_compatibility) but I really don't know where to start with this. JS/jQuery really isn't my thing so I'm unsure what needs changed/added to make this compatible with Drupal.

Update: it works flawlessly, even with jQuery 1.7 : http://build.kaipee.co.uk/drupaltest/

Looks like it's an issue with my site/theme :(

Read Managing Javascript in Drupal 7 for the full details, but basically you're looking for something like this:

(function($, Drupal) {
  Drupal.behaviors.sliderRevolution = {
    attach: function(context, settings) {
      $('.tp-banner', context).once('sliderRevolution', function() {
        $(this).revolution({
          delay:9000,
          startwidth:1170,
          startheight:500,
          hideThumbs:10
        });
      });
    }
  }
})(jQuery, Drupal);


What is the memcache report screen telling me? I'm experimenting with memcache and installed it via these instructions on a dev box. I think I have it working.

The config file is mostly left at default:

# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""

My Question: What am I looking at here? How do I know how "effective" this set up might be? For example, when the sets row says "0.14/s; 773 sets (29.97%) of 2,579 commands", does that mean 29.97% of insert/updates where cached?

I'm having difficulty reading this report.

Those are operations on your memcached server.

Sets: Data placed into cache by sets/second; by absolute number (by % of total commands); and a display of total number of commands. Sets are expensive (it represents needing to retrieve from your DB or other slower data sources) so you want this to be as low as possible, relative to gets.
Gets: Data requested from cache by gets/second; by absolute number (by % of total commands); by absolute number of cache retrievals (by % of total gets); by absolute number of cache misses (by % of total gets). Gets are the entire reason you employ memcache (to retrieve from fast memory rather than a slower disk/network) so you want this to be high as possible, relative to sets.
Counters: The number of increment/decrement operations performed on memcached counters.
Transferred: The ratio of read to written data. Since it's in absolute data amount, it gives you an idea of how much you're saving in reading from slow disk/network storage.
Per-connection average: The average amount of data and memcache operations made in a Drupal connection by gets/sets. The should give you an idea of how much memcache is employed on a Drupal request.
Available memory: The amount of memory used / available on the server. This is another metric showing how much you're utilizing memcache.
Evictions: The number of evictions or cached data removals from your memcached server.


Drupal Commerce payment transaction: execute script and pass variables When you need to create a new transaction method for Drupal Commerce, you need to dive into the code. And that's something I have zero experience with. BUT the following couldn't be hard. I already created a new payment module (just copied and edited the payment example module so I have a new payment method).

In commerce_payment_example.module you have the function commerce_payment_ideal_transaction that is been executed by the submit button of the checkout form. The only thing I need to do is to execute a script on submit (in HTML you can do this with <form method="post" action="script.php">, and pass three variables with it: the amount ($charge ?), the order ID ($order->order_id ?) and a description ($order ?). Could someone help me on the right way?

the transaction is meant to be created on a successful response of your provider (this could be payed, denied or whatever), usually an IPN.
meaning you have to provide a MENU_CALLBACK item in hook_menu.
most likely information about the order will be posted, make sure you get the order id back.

if you really want that on the payment form submission, just call the method (commerce_payment_ideal_transaction) in the hook_redirect_form. the question here is, how do you decide if a payment was successful or not ;)