Social Feeds with Views Module I've been searching high and low for a feeds module that will show Facebook and Twitter feeds with the Views Modules (Drupal 7.x). With Twitter using oauth, many Drupal 7 social feed modules haven't caught up to using oauth yet. The main reason I want to use views with the social parsers is because I want to use animation(like slide show) to show each social feed as it comes in.

I have found Social Parsers for Feeds that will work with views module but none that will work for Drupal 7.x

Does anyone have any suggestions that will allow social feed modules to be used in the views moudle?

I guess you have some options:

You can use Activity Stream, the imported feeds become nodes so they can be re-created using views. You have a choice to enable only the modules you need. The Facebook add-on module also has a Drupal 7 release in the issue queue.

 Activity Stream builds a lifestream, a "River of You", by aggregating all your social activities in one place. Whether it's bookmarks on Del.icio.us, posts from Twitter or your blog, edits to wikis or enjoyed music and movies, anything you create can be gathered into one easy-to-read stream. Every item becomes a full Drupal node, allowing them to be searched, promoted, commented upon, and managed just like any other piece of content within Drupal.

Alternatively, you can use the TB Social Feed, the feed items become nodes so they can also be used with views.

This module we have developed for our responsive Premium Drupal theme TB Wall. We contribute this module to the community and hope you can re-use it in your projects and development.

**What does this module do?**

This module aggregates content from social media sites. The module will retrieve public RSS feeds or request the API and creates a node for each item. Your website visitors will be able to see your sharings directly on your website and drive those visitors to your social media account. This way you might increase facebook fans, twitter followers etc.

We currently support facebook, twitter, vimeo, youtube, instagram, Flickr. Anyone feel free to contribute to this module so we can add up other social media channels.

There is also Social Feed which has a Drupal 7 release in the issue queue, but it creates a block for the feed items rather than a node for each.

So i guess the first two options are what you need


Altering markup of language switcher I want to lightly alter the language switcher block's markup by adding additional classes, among others "clearfix" to clear the floats. I cannot however pin down where the markup is created.

This link http://drupal.org/node/1369090 (last post) suggests using template.php but again, I cannot see how I would alter the wrapper div's markup.

Is there any way to achieve this?

In D7, the language switcher block is created in locale_block_view():

function locale_block_view($type) {
  if (drupal_multilingual()) {
    $path = drupal_is_front_page() ? '<front>' : $_GET['q'];
    $links = language_negotiation_get_switch_links($type, $path);

    if (isset($links->links)) {
      drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
      $class = "language-switcher-{$links->provider}";
      $variables = array('links' => $links->links, 'attributes' => array('class' => array($class)));
      $block['content'] = theme('links__locale_block', $variables);
      $block['subject'] = t('Languages');
      return $block;
    }
  }
}

You can use hook_block_view_alter() to modify the markup of the block.

If you want modify the output of the links, you can override the theme_links() function in your theme using THEME_links__locale_block() in the template.php file.


What is the best practice for writing a link to the screen through t()? In Drupal 7, one could do the following one line::

t('Visit !mylink', ['!mylink' => l('my website', 'http://example.com')]);

But that no longer works in Drupal 8 or 9 .  So far, I've tried this:

First I create a link, Drupal 8 style:

$mylink = Link::fromTextAndUrl('my website', Url::fromUri('http://example.com'));

Then try to create a string that can be printed.  I've tried toString():

t('Visit @mylink', ['@mylink' => $mylink->toString()]);

However, we're not supposed to do this. The API docs says:

  Do not use this method to render a link in an HTML context. In an HTML context, self::toRenderable() should be used so that render cache information is maintained.

So I try to use toRenderable():

t('Visit @mylink', ['@mylink' => render($mylink->toRenderable()]);

But PHP 7.2 doesn't like it.  The call to t() produces the following Notice:

  Notice: Only variables should be passed by reference ...

Fair enough - but how is this done?

I could not find how to do this described in any of the obvious docs, such as:

https://www.drupal.org/docs/security-in-drupal/sanitizing-output
https://www.drupal.org/docs/security-in-drupal/writing-secure-code-for-drupal

So my question is:
What is the best practice for writing a link to the screen in Drupal 8?

(Environment: Ubuntu 20.04 LTS, Drupal 8.8.6 (core + devel), procedural code - e.g. hook_help()).

For a link enclosed in translatable text, Drupal core suggests to use t() and embed the HTML anchor tag directly in the translated string. In LinkGeneratorInterface::generate(), the example code for this case is the following.

$text = t('Visit the content types page', array(
  ':url' => Url::fromRoute('entity.node_type.collection')->toString(),
));

Searching for :url in the Drupal core code finds code like the following.

BlockContentController::add()

if (count($types) === 0) {
  return [
    '#markup' => $this
      ->t('You have not created any block types yet. Go to the block type creation page to add a new block type.', [
      ':url' => Url::fromRoute('block_content.type_add')->toString(),
    ]),
  ];
}

ListingEmpty::render()

  $element = [
    '#markup' => $this->t('Add a custom block.', [
      ':url' => Url::fromRoute('block_content.add_page')->toString(),
    ]),
    '#access' => $access_result->isAllowed(),
    '#cache' => [
      'contexts' => $access_result->getCacheContexts(),
      'tags' => $access_result->getCacheTags(),
      'max-age' => $access_result->getCacheMaxAge(),
    ],
  ];

Alternatively, Drupal core uses the following code.

block_help()

$themes = \Drupal::service('theme_handler')->listInfo();
$output = '
' . t('Block placement is specific to each theme on your site. Changes will not be saved until you click Save blocks at the bottom of the page.') . '
';
$output .= '
' . Link::fromTextAndUrl(t('Demonstrate block regions (@theme)', [
  '@theme' => $themes[$demo_theme]->info['name'],
]), Url::fromRoute('block.admin_demo', ['theme' => $demo_theme]))->toString() . '
';

template_preprocess_forums()

    if ($variables['tid'] != $topic->forum_tid) {
      $variables['topics'][$id]->moved = TRUE;
      $variables['topics'][$id]->title = $topic->getTitle();
      $variables['topics'][$id]->message = Link::fromTextAndUrl(t('This topic has been moved'), Url::fromRoute('forum.page', ['taxonomy_term' => $topic->forum_tid]))->toString();
    }


How to extend TableSort class I have a paged table that extends the TableSort class. The thing is, I would like to add some special parameters to the header links, so I need to extend the TableSort class. The problem is, it is not recognizing my new extended TableSort (MyTableSort) class. This is the code, any help would be greatly appreciated:

<?php
// $Id: RadiosDemo.module $
//This module demonstrates the radios default value problem.

class MyTableSort extends TableSort {
/**
* Compose a URL query parameter array for table sorting links.
*
* @return
*   A URL query parameter array that consists of all components of the current
*   page request except for those pertaining to table sorting.
*/
  public function tablesort_get_query_parameters() {
    return drupal_get_query_parameters($_GET, array('q', 'sort', 'order', 'nid'));
  }
}

/**
* Implementation of hook_menu().
*/
function RadiosDemo_menu() {

  // Added a link to navigate to the demo node display page
  $items['RadiosDemo/Problem'] = array(
    'title' => 'Demo of Pager Problem',
    'page callback' => 'RadiosDemo_displaynodes',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Function which will display all the nids in a paged table
 */
function RadiosDemo_displaynodes() {

  $headers = array(
    array('data' => 'nid', 'field' => 'nid', 'sort' => 'ASC'),
    array('data' => 'status', 'field' => 'status'),
    array('data' => 'title', 'field' => 'title'),
  );

  // Select nid from published nodes with 20 pager limit
  $query = db_select('node', 'n')
    ->condition('status', 1)
    ->extend('MyTableSort')
    ->extend('PagerDefault')
    ->orderByHeader($headers)
    ->limit(30)
    ->fields('n', array('nid', 'title', 'status'));

  $results = $query->execute();

  $rows = array();

  foreach ($results as $result) {
    $row = array();
    $row[] = $result->nid;
    $row[] = $result->status;
    $row[] = $result->title;

    $rows[] = $row;
  }

  $html = theme('table', array(
   'header' => $headers,
   'rows' => $rows,
  ));

  $html .= theme('pager', array(
    'parameters' => array(
      'banana' => 'banana'
  )));

  return $html;
}

Like any other extender, the TableSort class implements the SelectQueryInterface interface.

Your code doesn't work because tablesort_get_query_parameters() is a Drupal function, not a method defined from SelectQueryInterface. To change the behavior of an extender, you need to re-define one of the methods listed in the documentation for SelectQueryInterface.

References

Extenders


Render a file in a specific view mode Which is the right way to render a file in a custom view mode?
I'm using Media, 7.2 branch, I've custom view modes and I want to print in a tpl a file (based on fid) in the view mode "header_image".

You'll want to use the file_view_file() function provided by the File entity module. The function has three parameters: a file object, the name of a view mode (or an array of custom display settings) and optionally a language code.

If you only have a file ID then you can do a file_load on the ID to get a full file object to pass to the function.

Note that file_view_file() returns a array as expected by drupal_render() so, depending on how you are incorporating the file into your template, you may have to render the returned array using render().


Need block context in hook_form_alter I'm trying to get my module to work: it replicates an exposed filter of a view into a block to display on other pages. Altering the form generally works, but it unfortunately works globally, ie. my changes are also applied to the original filter form on the views page.  That's because I use a simple checking of $delta which does not give me a context - sort of module signature that embedded the form.

I tried both hook_form_alter and hook_form_FORMID_alter - the variables passed to those functions don't seem to carry that info though.

Is there a way to get this kind of context?

If you are displaying this block on only certain pages, looking at $_GET['q'] or arg(#) will tell you that path or one of its arguments, so maybe you can switch on that?  eg, path/to/my/page is in $_GET['q'] and arg(2)=='my'.  Note that paths to nodes are system paths, not aliases, so the path might be just node/# but you can do a drupal_get_path_alias() to find it if need be.  If you are displaying the block only on certain node types, you can grab $node=menu_get_object() and then switch on $node->type as an example as well.  In fact, if you do it that way, $node->path should already point to the aliased path, and it's already cached for your performance pleasure :)

Oh, and failing all the above, you could do all of this in a custom module block, too, eg, in there do something like:

$block['subject']='// subject goes here';
// do the hook form alter
$content=views_embed_view( // the view in question );
$block['content']=$content;

return $block;

All of the php above presumes D6, minor changes apply to D7, but since it is being called in the block itself, the form alter should only change the view there (unless it is also being displayed elsewhere on the same page)


Find all entities of a given type? I am working on an admin interface for a module that uses a custom entity type. Is there a function or some way that I can use to find all entities of a given type, so that I can show users a list of them?

You're looking for the EntityFieldQuery class:

$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_my_field', 'value', 'a_value')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_my_field', 'value', 'DESC');

$results = $query->execute();
if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $nid => $node) {
    // Do something with the node object
  }
}

The above code loads all node entities with a content type of article. It filters on a custom field called field_my_field and the status property of the node. I only put that in for reference you wouldn't need it to load all nodes without any filters. Same goes for the order by statement.

Hope that helps.


Use order number instead of order id in Drupal Commerce checkout URLs I'm trying to make the order_number be a randomly generated alphanumeric string and use it as the only customer facing unique ID that the customer ever sees relating to their order.  However, the auto-incremented order_id still appears in all the checkout and order URLs.

Looking for examples of if this is being done in the wild on https://drupalcommerce.org/showcase, I found Lush, whose order_id increments by multiples of 5 in the checkout and order URLs.  It's hard to tell if this is still the order_id or the order_number being displayed in the URL.

A popular solution is to change the order_number into an alphanumeric pattern on hook_commerce_order_presave(), like what’s mentioned here: https://drupalcommerce.org/discussions/8900/how-change-order-number-numerical-default-alpanumeric-pattern.  The problem with that is the order number gets a new format, but the order id itself remains the auto-incremented integer and is still displayed in the checkout and order URLs.

Most examples I found recommend altering the commerce_order table and setting the starting order id to 1000 and letting it increment by 1 from there.  Like what’s mentioned here: https://drupalcommerce.org/questions/3172/how-can-i-change-starting-order-number.  This is a somewhat better solution, but still not as customizable as I would like because the order_id is still incrementing by 1.

The most promising solution seems to be encrypting and decrypting the order_id in the URL using hook_url_inbound_alter() and hook_url_outbound_alter(), like what’s mentioned here:
Drupal Commerce | Hide or set an alias to the order number in the checkout path.  This however requires the php mcrypt library, which I will not be able to use on my production server.

Any help, examples, or advice would be greatly appreciated!

Thanks @bob!

Just a bit of background:  I'm dealing with a 3rd party order fulfillment company who provides me with an API to generate orders in their Magento system after orders are created in my Drupal Commerce system.  The 3rd party passes back the order number from the Magento API, which I store as $order->field_vendor_order_number in Drupal Commerce.  Later I actually replace the Drupal Commerce $order->order_number with the custom field I created to temporarily hold the 3rd party's order number. I do this after successfully processing the customer's payment, so unfortunately all the checkout pages leading up to the "thank you" page still have the internal commerce order_id in the url because the order hasn't been created in the 3rd party's system yet, and therefore I don't have the proper order number that I want to show the customer yet.

Here are the rules, actions, and callbacks that send an order to the 3rd party and save the order number they respond with as the new Drupal Commerce order_number:

/**
 * Implements hook_default_rules_configuration().
 */
function example_store_default_rules_configuration() {
  $rules = array();

  /**
   * Add a reaction rule to send the order to 3rd party for fulfillment upon checkout completion.
   */
  $rule = rules_reaction_rule();

  $rule->label = t('Send Order for Fulfillment');
  $rule->tags = array('Example Store');
  $rule->active = TRUE;

  $rule
    ->event('commerce_checkout_complete')
    ->action('example_store_send_order_for_fulfillment', array(
      'commerce_order:select' => 'commerce-order',
    ));

  $rule->weight = 1;

  $rules['example_store_send_order_for_fulfillment_rule'] = $rule;

  /**
   * Add a reaction rule to update the order number to the one assigned by 3rd party fulfillment upon checkout completion.
   */
  $rule = rules_reaction_rule();

  $rule->label = t('Assign Fulfillment Order Number');
  $rule->tags = array('Example Store');
  $rule->active = TRUE;

  $rule
    ->event('commerce_checkout_complete')
    ->action('example_store_assign_fulfillment_order_number', array(
      'commerce_order:select' => 'commerce-order',
    ));

  $rule->weight = 2;

  $rules['example_store_assign_fulfillment_order_number_rule'] = $rule;

  return $rules;
}

/**
 * Implements hook_rules_action_info().
 */
function example_store_rules_action_info() {
  $actions = array();

  $actions['example_store_send_order_for_fulfillment'] = array(
    'label' => t('Send Order for Fulfillment'),
    'parameter' => array(
      'commerce_order' => array(
        'type' => 'commerce_order',
        'label' => t('Order to send for fulfillment'),
      ),
    ),
    'group' => t('Example Store'),
    'callbacks' => array(
      'execute' => 'example_store_send_order_for_fulfillment_callback',
    ),
  );

  $actions['example_store_assign_fulfillment_order_number'] = array(
    'label' => t('Assign Fulfillment Order Number'),
    'parameter' => array(
      'commerce_order' => array(
        'type' => 'commerce_order',
        'label' => t('Order to assign a new fulfillment order number'),
      ),
    ),
    'group' => t('Example Store'),
    'callbacks' => array(
      'execute' => 'example_store_assign_fulfillment_order_number_callback',
    ),
  );

  return $actions;
}

/**
 * Callback for rules action to send the order for fulfillment to 3rd party API and process the response
 * Save the 3rd party order number into a custom field on the order entity
 */
function example_store_send_order_for_fulfillment_callback($order) {
  include_once DRUPAL_ROOT . '/services/ExampleStoreService.php';
  $objExampleStoreService = new ExampleStoreService();
  $arrResponse = $objExampleStoreService->SendOrder($order);

  if ($arrResponse['status'] === 'success') {
    $order->field_vendor_order_number['und'][0]['value'] = $arrResponse['order_number'];
    $order->log = 'Order Number from 3rd party is: '.$order->field_vendor_order_number['und'][0]['value'];
    $order->revision = TRUE;
    commerce_order_save($order);
  }
}

/**
 * Callback for rules action to assign the new order number received from 3rd party fulfillment
 * Take the order number stored in the custom field and actually save it as the order entity's order_number
 */
function example_store_assign_fulfillment_order_number_callback($order) {
  if (isset($order->field_vendor_order_number['und'][0]['value']) && !empty($order->field_vendor_order_number['und'][0]['value'])) {
    $order->order_number = $order->field_vendor_order_number['und'][0]['value'];
    $order->log = 'Order Number '.$order->order_number.' saved.';
    $order->revision = TRUE;
    commerce_order_save($order);
  }
}

However instead of going to the default "Checkout Complete" page, I created a rule that reacts to the checkout_complete event by redirecting to "store/order/[commerce-order:order-number]".  Notice it has a weight of 10, to ensure it's the last thing I want to do when reacting to the checkout_complete event.

{ "rules_redirect_to_custom_checkout_complete_page" : {
    "LABEL" : "Redirect to custom checkout complete page",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "TAGS" : [ "Commerce Checkout", "Example Store" ],
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "redirect" : { "url" : "store\/order\/[commerce-order:order-number]\/" } }
    ]
  }
}

I added a hook_menu entry for this, which accepts the order_number instead of the internal commerce order_id as an url argument:

/**
 * Implements hook_menu().
 */
function example_store_menu() {

  $items['store/order/%'] = array(
    'page callback'   => '_example_store_order_view',
    'page arguments'  => array(2),
    'access callback' => TRUE,
    'type'            => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Custom page callback for store/order/%
 * @param  string $order_number - order number from 3rd party fulfillment api
 * @return array - order as renderable array
 */
function _example_store_order_view($order_number) {
  if (!empty($order_number)) {
    $order = commerce_order_load_by_number($order_number);
  }

  if (!empty($order)) {
    $entity_view = entity_view('commerce_order', array($order->order_id => $order), 'customer', NULL, TRUE);
    return theme('example_store_order_complete_thank_you', array('entity_view' => $entity_view));
  }
  else {
    drupal_set_message(t("No order was found for order number ". $order_number . ". Please check your order number to make sure it is correct."), 'error');
    drupal_goto('store');
  }
}

And a custom hook_theme entry to handle the template for this custom "Order Complete Thank You" page, which mainly just displays the rendered order entity.  If you have any Google Analytics e-commerce tracking code, this is the template in which you'd want to place those scripts. I'm not displaying it in this stripped down example, but I rigged mine up to only render those scripts on the first visit of this page, that was if the customer refreshes the thank you page, Google Analytics won't see duplicate tracking.

/**
 * Implements hook_theme().
 */
function example_store_theme($existing, $type, $theme, $path) {
  $module_path = drupal_get_path('module', 'example_store');
  return array(
    'example_store_order_complete_thank_you' => array(
      'variables' => array(
        'entity_view' => NULL,
      ),
      'template' => 'example-store-order-complete-thank-you',
      'path' => $module_path.'/templates',
    ),
  );
}

Contents of example-store-order-complete-thank-you.tpl.php:

//Render the order entity
print render($entity_view);


update node field Programmatically I want to learn to alter node fields after a migration. I have a custom module and inside is a .inc file I use as a script that I will run once using drush eval module_load_include. I want to learn a simple task like replacing text inside all nodes body field. First I load all nodes, then search the body fields for all nodes for the word "red" than I want to replace that word with "blue" How would I write this? This is my starting point

<?php

use Drupal\Component\Utility\Html;
use \Drupal\node\Entity\Node;

function _update_node() {

// load nodes
foreach($nids as $nid) {
    $node = Node::load($nid);

// do the work  here

  $node->save();

}

Then I want to run this script once. My module name is create_content. So I can run the command.

drush eval "module_load_include('inc', 'create_content', 'create_content'); _update_node();" > debug.txt

Here is how to update body field :

$nodes = Node::loadMultiple();
foreach($nodes as $node){
  $html = $node->body->value;
  $html = str_replace('blue','red',$html);
  $node->set('body', [
          'summary' => 'the summary',
          'value' => $html,
          'format' => 'full_html', // probably,
          /**
           * Correspond with format you need in admin/config/content/formats
           */
   ]);
   $node->save();
}


PluginNotFoundException: "The "iframe" plugin does not exist." at core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52" how to solve such error:

Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "iframe" plugin does not exist." at /var/aegir/platforms/drupal8-dev/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52" while reading response header from upstream, request: "GET /admin/config/content/formats/manage/basic_html HTTP/1.1"

The plugin 'iframe' have been existing since i found it in the enabled filter list

  http://drupal.stackexchange.com/questions/218781/create-a-new-text-format-filter

then i believe when i have clear the cache at some stage it came up with this exception  when trying to acces again to

        admin/config/content/formats/manage/basic_html

where i have initially add this plugin filter

The exception come up when i am trying to uninstall the module so it is problematic

it seems that this error is reccurent when i googleized it but i did not found where the problem lies

removing manually the module and deleting the %iframe% entry in config table should do

it happens when  there's no definitition of the plugin

   /*protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) {
// Avoid using a ternary that would create a copy of the array.
if (isset($definitions[$plugin_id])) {
    return $definitions[$plugin_id];
}
elseif (!$exception_on_invalid) {
    return NULL;
}

throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));

so what i understand is my custom module dont have a valid plugin manager !?

https://www.drupal.org/docs/8/api/plugin-api/d8-plugin-discovery


How to enable free tagging? I'm using Drupal 8 and I would like to allow free tagging my website. There should be a field on the node edit page for tags that the user can add new or existing tag(s) to the page.

What field should I use and how must I configure it?

I do not know what a free tagging cloud is, but I can help you with setting up a free tagging field.

On your entity (content type), add an entity reference field that references taxonomy terms. Optionally you can limit to a specific vocabulary. Also select the checkbox to create new items if they do not yet exist.

Then on the manage form display tab of the content type, make sure that you select the Autocomplete (Tags style) as the Widget for your created field. This should give you a free tagging text field.

(You can use the Article content type of a clean Drupal site as example)


How to use Views PHP to rewrite results of a field? I am using Views PHP  to rewrite fields in Views.
I can access all variables BUT those that have a build mode. In my case, I have Content: Node field (which can be build according to any display), which should is accessible using the variable $row->nodefield. However, the content of that variable is always empty. I have tried with other variables, and every field with a build mode will not be rendered in Views PHP .

Is this a design issue or am I missing something?

I'm using Drupal 7 and Views 3

EDIT

Using dpm() on available values return the following:

dpm($row)

dpm($data)

Above the "Output Code" section you should check the $data variable in the "Value" field.

Usually I just dpm($data) to find the field I need.  Then you can save it to the $static['myvalue'] variable for use in the "Output Code" field.

It is confusing but for some reason if you try just the $row->xxx variables in the "Output Code" section they are empty or set to the node-id.


do thumbnail image styles lower the page load This may not be a Drupal specific question, but when I use image styles to resize from a full to thumbnail size, will the page load still behave as if its a hiqh quality image, or does it lower the page load?

I'm trying to figure out if there should ever be a reason to provide two upload fields on a content type, one for a high quality image and one for a lower one.

Uploaded images are scaled depending on the preset you choose for display. Thus, a typical high resolution image which might have 8 MB is reduced to maybe 150 kB when using a thumbnail preset. This of course lowers the bandwidth, the original image is not loaded.

So, there is no need to create a second image field. If you haven't seen it yet, you might want to take a look at the Colorbox module. It lets you choose to display an image as a thumbnail and only upon clicking on that preview the full image is loaded (or just another size you defined).

Just a note: Colorbox is not the only module that is providing that feature, there are a lot of similar modules, the original was called Lightbox. On drupal.org, there's a page comparing all available lightbox clones.


Using variable_get from DrupalWebTestCase I would like to pull certain configuration items from settings.php from a DrupalWebTestCase in order to test my module (in this case, a SFTP module).
I want to do it this way so that I don't hardcode my SFTP credentials.

For example, in my DrupalWebTestCase, I have:

  public function test_sftp()
  {
    $this->assertTrue(variable_get('mymodule_test_sftp'));
    // then I would try to connect, etc....
  }

In settings.php:

$conf['mymodule_test_sftp'] = array(
 'host' => 'example.com',
 // etc...
);

When I run the unit testing suite, this unit test fails, the value returned by variable_get is NULL.

Edit:

Running the code below, returns the correct database settings, but I get "Undefined index: mymodule_test_sftp":

  public function test_sftp()
  {
    global $databases, $conf;
    $this->assertTrue($databases);
    $this->assertTrue($conf['mymodule_test_sftp']);
  }

Just faced a similar issue. What I have found out is that in your DrupalWebTestCase child class you still have access to all variables defined in settings.php before calling parent::setUp(). Which means you can do something like this:

class MymoduleWebTestCase extends DrupalWebTestCase {

  public function setUp() {
    $mymodule_test_sftp = variable_get('mymodule_test_sftp');

    parent::setUp();

    variable_set('mymodule_test_sftp', $mymodule_test_sftp);
  }

}


Load Javascript Conditionally Based on Form Value I have two different kinds of webforms, one I'll call "type 1" and one I'll call "type 2". Depending on the type of webform, I want to conditionally add either type1.js or type2.js. The type of webform is has a hidden field called formtype that an admin would set either to "type1" or "type2," and then, theoretically, I would pull in the proper Javascript based on that value when the form loads.

My hook_form_alter() function looks like this:

<?php
/**
 * Implements hook_form_alter().
 */
function module_name_form_alter(&$form, $form_state, $form_id) {
  if($form['submitted']['formtype']['#default_value'] == 'type1'){
    drupal_add_js($js_path . 'type1.js');
  }
  elseif($form['submitted']['formtype']['#default_value'] == 'type2'){
    drupal_add_js($js_path . 'type2.js');
  }
}
?>

This does actually cause the proper javascript to load, but I get a Drupal message saying:

Undefined index: submitted (etc.)

My question is: why would I be receiving this error message even though the logic appears to work? I'm also open to other ways of handling this use-case.

FYI, I'm using Drupal 7.

You applied this code for all forms on your site, but only webform has $form['submitted'] element. To fix this issue you may use next code snippet

<?php
/**
 * Implements hook_form_alter().
 */
 function module_name_form_alter(&$form, $form_state, $form_id) {
   if (!empty($form['submitted'])) {
     if ($form['submitted']['formtype']['#default_value'] == 'type1'){
       drupal_add_js($js_path . 'type1.js');
     }
     else if ($form['submitted']['formtype']['#default_value'] == 'type2'){
       drupal_add_js($js_path . 'type2.js');
     }
  }
}
?>


Custom field Rules implementaion I added new "Markup" field into commerce_product table using custom module. Now I need to create a rule to calculate (sell_price=prod_price*markup), but I can't acccess Markup field throught Rules selectors. Is there a UI , or what hooks should I implement to solve that problem?
Here is complete comm_markup module code:

function comm_markup_schema_alter(&$schema) {
  $schema['commerce_product']['fields']['markup'] = array(
    'type' => 'float',
    'not null' => TRUE,
    'default' => 1,
    'description' => 'Price markup field',
  );
}

function comm_markup_install() {
  $schema = drupal_get_schema('commerce_product');
  db_add_field('commerce_product', 'markup', $schema['fields']['markup']);
}

function comm_markup_entity_property_info_alter(&$info) {
  $properties = &$info['commerce_product']['properties'];
  $properties['markup'] = array(
    'label' => t('Price markup'),
    'type' => 'decimal',
    'description' => 'Gross price multiplier (defines profit amount).',
    'schema field' => 'markup',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
}

function comm_markup_views_data_alter(&$data) {
  $data['commerce_product']['markup'] = array(
    'title' => t('Price markup field'),
    'help' => t('Multiplier. Adds profit to the gross price.'),
    'field' => array(
      'handler' => 'views_handler_field_numeric',
      'click sortable' => TRUE,
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );
}

Simple UI solution:

Add a condition of "Data Comparison"
Data selector - commerce-line-item:type
Value equals - "Modification" (or whatever your custom line item type is called)

Now when you add a condition that checks for a field, all the fields on that custom line item type should appear. Example, "Data value is empty - commerce-line-item:custom-field".
Thanks to trevorkjorlien comment at Drupal.org


I can't use strong tag in wysiwyg I watch Introduction Advanced Theming in Drupal 7 (drupalize.me), and I create custom theme frot that video tutorial. I can't use <strong> and <em> in CkEditor. I can use only <b> and <l>, but CkEditor create <strong> and <em>. That tags has no effect when I save my node.
Why? What is wrong? When I change the theme to Bartic, everything works OK, but in the custom theme from that video tutorial, those two tags are not rendered as I would expect.

CSS resets usually take the emphasis off of <strong> and <em> tags by default.

All you need to do is add a rule like this to your main style sheet (main.css):

strong {font-weight: bold;}
em {font-style: italic;}

That will re-reset the <strong> and <em> tags to display as you'd normally expect.


To process uploaded file for certain content type, how to? For example:

A new content type Photo is created
The optional core module Upload is enabled
Such that users can upload JPEG files

How can I:

In view mode of a Photo node, show a small "View EXIF" button next to the Photo
When the user click the "View EXIF" button, my module show some EXIF info about that photo

i.e.:

add a button only for a particular content type (Photo in this example)
trigger a hook to process a uploaded file (a JPEG file in this example)

Thanks!

Use the Exif module to grab your exif data from the uploaded image:

Use some simple theming (eg: create node-photo.tpl.php if you are using d6 and content type is called 'photo') - there do some simple jquery show / hide type stuff with a div wrapped around your exif data.


Custom fields in user's default tab I'm a first-time stackexchange user, long time Drupal 6 developer.

I'm just starting playing with Drupal 8 and I know I'm going to love it when I get used to working in it but right now I'm in that frustration phase where it's unfamiliar again and I can't do even the simple things! I wonder if you can help.

I would like to add dynamic content (probably just #markup) to the user's main tab. At the moment, the user tab only contains the familiar text 'Member for xxx'.

Under Drupal 6 I just handled hook_user, something like:

function mymodule_user($type, &$edit, &$user, $category = NULL) {
  switch ($type) {
    case 'view':
      $user->content['the_time'] = array(
        '#type' => 'markup',
        '#value' => 'Epoch = ' . time() . '',
        '#weight' => 100,
      );
      break;
  }
}

(I've not checked the above actually runs, but it's a modified version of something I'm using on a live site).

What's the equivalent under Drupal 8? I'm looking at the following:

function mymodule_user_view(array &$build, UserInterface $account, EntityViewDisplayInterface $display) {
  $build['the_time'] = array(
    '#type' => 'item',
    '#markup' => 'Epoch = ' . time() . '',
  );
}

Although this works (after clearing the caches) I don't think this is the recommended way to do it, as I'm not seeing dynamic content, the hook is only called once and the text is cached.

I really hope someone can point me in the right direction!

The question how to put a custom field in the user tab is already answered, btw you don't need '#type', when using '#markup' in drupal 8.

As you said at the end, this is a caching issue. In general it is not a good idea to put the time in the html of every page, you better do this in javascript. If you don't care about performance, then you can disable the cache:

$build['#cache']['max-age'] = 0;

This does not work for anonymous users, because in drupal 8 there is also the page cache enabled by default. If you deliver a different page on every request, you don't need this module and you can uninstall it.

If you want to disable it only for the user default tab, then use this command:

\Drupal::service('page_cache_kill_switch')->trigger();


How to change documents to another category painlessly I have 4 content types eg Parts, Service, Marketing, and Sales.

I've now created one category with 4 content types sub-categories instead.

Is there a painless way of changing each documents category?

I've experimented with [Node_export][1] but that did not allow me to import into a different category.

Try Node Convert, it allows you to change one content type to another:

  Node Convert adds a menu tab "Convert" on the node view page, i.e.
  node/1/convert, which gives the ability to convert the node from its
  current node type to another node type. The module provides the means
  to transfer all the field values of the current node type into fields
  on the destination node type, or discard them.

Then you can use Views Bulk Operations to do it in batches.


How can I add classes to rows depending on the loop index? I have received a design where they want to have the latest three articles links put on the top of the front page (over their respective images) so that the first is taking left half of the page and second and third to split (vertically) the right half top.
I thought that view-view--latest-articles.html.twig would solve the problem elegantly like this:

{% for row in rows %}
    {% if loop.index == 1 %}

          {{ row }}

    {% elseif loop.index==2 %}
    ...   // dull and inelegant code dismissed
    {% endif %}
{% endfor %}

But if I put debugging code for loop.index into the code it only shows the index once and splurts out all the rows after it, never minding my if. It still shows the index once, so I know it IS using the template.
Am I missing something or trying just to it in a wrong way?

And as it so often happens:
Just after fighting a pair of hours with this and then finally asking the question here, I found out the solution myself. I had to make the code in views-view-unformatted--latest-articles.html.twig (i.e. had to add the -unformatted to my question part).


Is it possible to control a User's Role based on their Email Address? Currently I am emailed everytime time an employee at my company needs their account role upgraded to 'Authenticated' to 'Employee', any suggestions on a way to automate that process?

Thanks!

"Auto Assign Role" and "Apply for role" modules seem to be close to what you are asking for.

https://www.drupal.org/project/autoassignrole
https://www.drupal.org/project/apply_for_role

If they don't fit your exact use case then I suggest looking at the way autoassignrole_user_presave() works as a starting point for custom coding. http://cgit.drupalcode.org/autoassignrole/tree/autoassignrole.module#n183


How to bulk update entities using the Feeds module, without existing mappings to a "unique target" Importing new entities with feeds using a published csv file is very handy. I use Google Sheets to publish a csv file and use Feeds to create new nodes, which then can be updated based on a unique target field.

However, I have a number of sites that need their content to be bulk-updated in a similar fashion, but these entities were not imported through Feeds, so no unique target / hash check is present to update them.

Is there a way to make drupal import a feed and check for existing entities using the title field, and modify/populate the corresponding fields?

You could use a custom text field as unique target by using the "Unique values" validator of the Field validation module.

You could also implement hook_feeds_processor_targets_alter() in a custom module to add a "unique callback" to a target. In that callback you can implement your own logic for retrieving an existing entity.

See https://www.drupal.org/node/1307732#field_as_unique_id_7 for a list of steps for both solutions.
See also feeds.api.php for more information about implementing "unique" callbacks.


Can cookies safely be stored in the public filesystem (sites/default/files)? One of my modules does some CURLing, and to do this it creates a cookie on the Drupal server. Where should I locate this? Where it will be nice and safe? Is there a convention? Is sites/default/files considered safe?

The risk depends on the nature of the cookie. If these cookies contain session data, they could be used to take over you session, which is considered to be high risk.

Your public files folder (sites/default/files) has public read access, meaning that everybody can obtain a file (once they know its name) by going to example.com/sites/default/files/[FILENAME]. This is not safe and perhaps not the best solution for the type of cookies described above.

Instead, you can save it to the private filesystem. Instructions for Drupal 7 and 8 differ, so best to look up the instructions you need. The ultimate safe solution would be to move your private filesystem outside of your webroot (some tutorials create it as subfolder of sites/default/files). Safer would be to place it in a folder next to your public_html/www folder or anywhere else on the filesystem, where it is not accessible from the internet.

If you configure it properly on SITE/admin/config/media/file-system, you can then use the streamwrapper private:// to read and write the files.

If these cookies do not contain any data that could be considered to be sensitive, sites/default/files (or public://) should be good enough.


LDAP Query View Errors for RSS I'm trying to add an RSS feed to a LDAP Query view, but I keep getting and error message.

"Row style plugin requires specifying which views fields to use for RSS item."

Is there a way to show an RSS feed from LDAP in Views?

UPDATED WITH IMAGE

LDAP lets you query an LDAP service, create a View of an ldap query, process an ldap result using Feeds, or import/update Users to your site.

An RSS view, provided by Views RSS, is simply a contributed View type from a community module. You must tell Views what fields should show up in the RSS feed you're creating. Typically there is a Settings option next to the Row Style to set what fields to display.

See the attached settings options (which is using an LDAP Query View). You need to make your LDAP Query first using the LDAP module, then add a new Display Type of type Feed in Views and then configure the Fields settings for the RSS feed.


Why is "drush cc all" failing with "undefined function user_load()" After updating my Drupal test server to have a fresh copy of the database and code from the production system, "drush cc all" would fail with a message saying

  PHP Fatal error:  Call to undefined function user_load() in /usr/share/pear/drush/includes/drupal.inc on line 138

I'm running drush version 6.2.0 with a drupal 7.25 system. I'm using memcache as cache_default_class.

The problem went away after I restarted memcached.

I discovered that by running drush with -d and seeing a PHP error about a $theme value not being a valid index. Tracing the code showed that access to cache_bootstrap was getting empty arrays for the module and theme data.

From now on I plan to restart memcached or flush its cache on my test server after rebuilding its database. (I've done this kind of rebuilding dozens of times before with no issues.)


Twig Translation String without Enabling Interface Translation Is it possible to provide translation strings to Twig, without the Interface Translation module enabled?

We have Content Translation enabled but do not want to enable Interface translation (we would like the Drupal administration menu system to remain in English).

We have a couple of landing pages that base most of their content on a translated entity however, there are still a few labels and links we would like to translate using {{ 'foo'|t }} in Twig.

Is this possible? And if so - where would the translation stings be stored?

Our solution in the end was to create a new Twig extension called tr.

The class of the extension plugin checks to see if a 'translations' directory exists in the current theme. If it does, it reads the containing YAML translation files into an associative array (en.yml, es.yml, fr.yml etc.)

When {{ tr('source string') }} is called in the twig template, it will check the loaded associative arrays to see if there is a translation available for the current language and requested string. If there is it will return the translated value.

This works for us since in our case we're only translating a fairly short list of values - short strings and labels like 'Read More', 'Learn More', 'Subscribe' etc. The rest of our translated content comes from the content translation of the entities.

Hope this helps...


How do you add "Rating Field" to a content type? I know that there are many rating or voting module like:

Fivestar
Rate
Star

etc for drupal 7, I haven't found any modules for Drupal 8. How can I create a simple 5 star rating widget in Drupal 8?

Ideally I would like a solution, that doesn't require much coding, but can be achieved using existing modules and configuration.

Do it yourself version:

You also can add a custom field, integers, with min 1 and max 5 values.
After this you only need to theme the display of the field, in a twig template maybe.

For achieving the star effect, there are plenty of solutions for that on google (css / js perspective).

One of them is to use field type List (integer) and in options use this values (so there will be select/radios with stars shown, but stored as a integer):

1|★
2|★★
3|★★★
4|★★★★
5|★★★★★


How to programmatically get list of available image styles I'm able to get a list of fields using

$fields = array_keys(\Drupal::entityManager()->getFieldDefinitions('node', 'ce_meeting'));

But is there a way to get a list of Image Styles instead?
Something similar to

$fields = array_keys(\Drupal::entityManager()->getImageStyles());

to spit out an array

['thumbnail','original','medium','large','small']

Is there a function to display a list of available image styles?

use

use Drupal\image\Entity\ImageStyle;

and load all image style with

$styles = ImageStyle::loadMultiple();

Also you can use  entity_load_multiple  with

 styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();


Looking for either "Date Field Popup Widget (Views Filtering)" or "Date Field Reference (with Popup widget)" I've been looking for quite a while, but I can't seem to find a solution in Drupal 7.

Anyone know a module or a method of filtering a date field popup widget, to only allow dates to be selected based on a views filter in the node creation form?

Or a way to reference another date field (possibly via Entity reference) that allows me to still use the date popup widget?

Any help would be much appreciated. Thank you.

Date Restrictions provides restrictions on allowed values based on several criteria. It still doesn't implement filtering by views results, but you may give it a try.


Ouput Node Reference Field Title in Drupal 7 When creating templates in Drupal 6 I can output just the title for the value of a node reference field like so:

echo $node->field_example[0]['safe']['title'];

I'm trying to do the same thing in Drupal 7 - I've tried many variations like the examples below but the output is always blank or throws an error:

print $content->field_example['und']['0']['node']['title'];

print $content['field_example']['#object']['field_example']['und']['0']['node']['title'];

Any help on how to grab the 'title' value is much appreciated.

print $field_example[0]['node']->title;

This ended up being the syntax needed to pull just the title from the value of a node reference field.


How to make a template for content type with panels I´ve created a content type "Products" with "N" fields and I try to create a template for this content type, each product should have its own page.

How I do this?

Google searching I found this solution.

https://www.drupal.org/node/1422454

Best regards!


How do I create custom webform element? How can we create a custom element type in Drupal 8 webform, similarly to implementing hook_webform_component_info() in Drupal 7?

I am not sure if you are looking for a composite element or just a simple one, but I found a great example for a Composite element posted by the user lpalgarvio.

Using the example module makes it all simple, in this case you are extending the class WebformCompositeBase to implement your own composite element.

Another example would be to take a look at the elements which ship with Webform module and how each is implemented. According to the webform 5 (D8) module maintainer he is wanting to add such an example into the webforms module.

Update:
There are three examples of custom elements in the webform module itself, all quite clear and detailed:

Composite element - webform/modules/webform_example_composite
Element - webform/modules/webform_example_element
Handler - webform/modules/webform_example_remote_post
Config examples - webform/modules/webform_examples (pre-built forms)


Add followers' list at the end of discussion I want to add following functionalities in Drupal 7.

Any forum-user can have followers, So I want to show followers list on forum-user's profile page. (Like this)
Those followers should be automatically subscribed to all the posts by that author.

I'm using Advanced Forum module. How to do this using Views module or any other possible way?

You can do this using Flag module.

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.

Creating Following & Followers


Drupal 7, Entity Reference user autocomplete field I have a custom content type that has a users: entity reference autocomplete field. For some reason the list gets populated as [realname] ([name]). In other words the realname and username tokens are both shown in the autocomplete list. Is there a way to only show the realname token?

I would like to go from this...

To this

Set up a view for the autocomplete.

You can use this tutorial: http://speaksdrupal.com/blog/custom-entityreference-handlers-using-views

Then add that as the view to use for autocomplete.

http://screencast.com/t/8m0O7F8zV

Whatever fields are searched will show up in the drop down.  So if you remove e-mail from the list of fields searched, it won't show up in the drop-down.


How many blocks can be handled? I migrated to drupal 8 and now it has 760 blocks. I plan at least to triple this number. Blocks are placed into nodes content with Insert Block module. When I was setting up website the database was 200 mb, now when cache is not cleared it's 2gb+. There are two tables 1gb each.

At the moment when I save or edit block structure it takes 10 seconds to save it. CPU is't at 100, so website is working fine so far, but I'm worried that it might break down due to very large cache tables.

What do you think I should do to save performance other then stop adding blocks?

From a capabilities and code perspective, there is no practical limit to the number of entities in a system (blocks, nodes, users).  drupal.org is a good example of this; it has tons of users and nodes on it.

That doesn't preclude needing to properly scale out the rest of the system.  This is particularly important in a Drupal 8 system, where caching is used extensively.  One of the most overlooked aspects of this is properly tuning the database.

Out of the box, MySQL can have some bad default parameters.  MySQLTuner can provide some guidance on how to adjust your system, particularly the buffer size.  If your cache tables get large, I/O from them can slow down when they are hitting disk.

When you get to the point where you need to squeeze more performance out of a tuned site or if you are memory limited for proper tuning, you may want to consider a non-database caching solution like memcache or Redis.  These can really help with large systems.


How to delete a value from a multi-value entity reference field with EntityMetadataWrapper I have multiple values in an entity reference field.  I want to delete one of those values, but ::clear doesn't seem to work.  I basically just want to do an unset, like:

$wrapper->field_entityrefs[3]->delete();

or something clean like that.  What is the best way?

This seems to work:

$wrapper->field_entityrefs[3]->set();

Also, to test if the field is there in the first place:

$wrapper->__isset('field_entityrefs');

I'm now finding myself calling __isset() on all wrapper fields.


why cannot I edit admin permissions for the permission page in D8? All permission boxes for administrators are disabled "greyed out".

I can do it via drush but not through the UI.

That's because administrator is an admin role, that means it has all the permissions all the time. Editing it via drush won't do anything.

If you want a role not have all permissions it must not be an admin role, but that means you need to manually add new permissions.


Model field of view and hide if empty Hello this is my file views-view-field--sitemap--views-data-export--field-image.tpl.php :

<?php

$fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

echo $fields["field_image"]->content;

When I check the box to hide empty if the image field, the empty fields are hidden in the preview of view but not out. How to hide empty fields when the view is displayed? I think there is a line to add in the template file.

<?php

if (!empty($field->original_value)) {

  $fields["field_image"]->content = '<image:loc>' . $field->original_value . '</image:loc>' . '<image:title>' . $row->field_field_image[0]['rendered']['#item']["alt"] . '</image:title>';

  echo $fields["field_image"]->content;

}


When should the dependency from a Drupal core module be explicit? The Standard profile declares the Node module as one of the modules it requires, and so does the Minimal profile. That is not true for the History module, which is required from the former but not the latter.

When should I declare my module as depending from a Drupal core module? Should I assume the installation profile / distribution always requires the module from which my module depends?

As in all versions of Drupal, if your module depends on another module, you should always explicitly declare it as a dependency.


Multiple Image upload in drupal 7 I want to upload mulitple image at a time , for more clarification i have mention below link

http://www.olx.com.pk/posting.php?categ_id=378

when you click on add photos , you can upload 20 picture at a time.

This has been answered before, but I can't mark it as a duplicate or flag.

You can use the the Plupload module to allow multiple uploads and even set limits by going into the code.


How to modify the Drupal Solr Search fields / apply custom fields / modify results Am attempting to understand the report in admin/reports/apachesolr (Drupal 6). There are a large number of fields, and I am trying to understand

1) Are these the fields within the Solr index that are being populated, or are these within Drupal?

2) Assuming they are the Solr index fields, how can I make reference to them? For example, I have added a custom module that hooks into hook_apachesolr_modify_query

$query->add_filter("type", 'job'); // Works fine

$query->add_filter("sis_cck_field_job_approved", 1); // Unsure

Will this filter on those custom CCK fields?

In addition, I am attempting to customise the way that the search captures search terms, applies those additional terms to specific fields and potentially saves them for emailing at a later date. With a little research I have come across Panels + Apache Solr Panels as one approach, and Views 3 and Apache Solr Views as an alternative approach. Is either preferred for a production site? I am specifically looking to

1) Add extra field filters to the search form

2) Build custom field filters (e.g. between Date X and Y)

3) Format the returning results, to show / hide specific node data, and censor particular fields based on a role.

Greatly appreciate all and any response!

Craig Moore

I think that you may find that the Apache Solr Views module will do what you are wanting fairly well.


Display block only on a specific page I would like to display a block only on the [root]/dashboard page, and I would like to do this from my custom module defining the block, not from the Drupal admin interface. How can I do this? Thanks you!

Also, where would this condition be better to be written? In hook_block_view() within the module or in the block template file?

The code would go in hook_block_info(). You can use the pages property to define the list of pages the block should be shown on. e.g.

$blocks['recent'] = array(
  'info' => t('Recent content'),
  'pages' => 'dashboard',
  'visibility' => BLOCK_VISIBILITY_LISTED
);


How to change dropdown field function to buttons in privatemsg module I am using private message module.

In that there is a option to mark the messages as read and unread using drop down.

Here it looks like : http://drupal.org/node/709180

Instead of that i need to place two buttons called "Mark as Read" and "Mark as Unread" and needs to perform the same action.

How can i do it?

Any help will be grateful.

Thanks in adavnce...

You can implement hook_privatemsg_thread_operations_alter(&$operations) (unfortunately not documented but called in _privatemsg_action_form()) to change the mark as read and mark as unread operations to use a button, as does delete. They are defined in privatemsg_privatemsg_thread_operations().

Something like this:

<?php
function yourmodule_privatemsg_thread_operations_alter(&$operations) {
  $operations['mark as read']['button'] = TRUE;
  $operations['mark as unread']['button'] = TRUE;
}
?>

Note: This requires Privatemsg 6.x-2.x


How to call limited data items per page? I am using one custom module, which is getting data from the database, with the following code.

function rs_get_doors() {
  $doors = array();
  $doors_nids =  db_select('node', 'n')
  $doors_nids = $door_nids->extend('PagerDefault')->limit(10);
    ->condition('n.type', 'vivarium_door')
    ->fields('n', array('nid'))
    ->orderBy('n.title', 'ASC')
    ->execute()
    ->fetchCol();

  foreach ($doors_nids as $nid) {
    $wrapper = entity_metadata_wrapper('node', $nid);
    $doors[$nid] = array(
      'name' => $wrapper->title->value(),
      'fee_nid' => $wrapper->field_fee_category->value()->nid,
    );
  }

  uasort($doors, 'rs_doors_natural_sort');

  return $doors;
}

it is getting thousands of nodes at time in a single page and it takes too much time to load.

So I think I need to paginate the query. How can I achieve this?

$doors_nids = db_select('node', 'n')

->condition('n.type', 'vivarium_door')

->fields('n', array('nid'))

->orderBy('n.title', 'ASC')

->extend('PagerDefault')->limit(10)

->execute()

->fetchCol();

Hopes this will helps you.


How to control field visibility in Views based on permission? I am displaying Flag links via Views. By default the Flag module provides settings to control whether the Flag link appears eg. only appear on own content, only appear on others content etc.

The dilemma is that when displaying the Flag links via Views this no longer has any effect, and the Flag link will always display in the View. I have two Flags; one for owners of content and another for non-owners of the content. Depending on whether the user viewing the content owns the content or not I would like to display one Flag link or the other. This will allow owners for example to "delete" their own content, while non-owners to only hide content which is not theirs. If Views fields respected permissions this would be straight forward, but they don't seam to at least in my experience. How can this be done?

Take global php field in view and write below logic in.

global $user;
$node=node_load($nid);
$author=$node->uid;

if($user->uid==$author)
{
   print flag_create_link('flag_machine_name', $nid); // flag for author
}
else
{
  print flag_create_link('flag_machine_name', $nid);//flag for other users.
}

Hope this will help.

NOTE : replace flag_machine_name with your specific flag's machine name which you want to display.


Gmap won't show infobubbles when clicking markers (with View Module) First some information:

Drupal Version - 7.41
GMap Version - 7.x-2.10
Location Version - 7.x-3.7

I'm using the gmap module on a webshop i'm creating.

I made a custom content type for this (gmap) which simply has basic fields + a location field I've added. So far so good.

I've added one of this custom content, with the locations I need added through  the location tab in the options. I've made a view that displays these all of these custom contents (there's only one, but still displays it) which is working fine. The  problem is that, one clicking on the marker, it doesn't show the information while I've set it up to do so.

The issues start when I go to the configuration of my GMap Location. I get these errors

Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, object given in check_plain() (line 1571 of /Applications/MAMP/htdocs/kickstarter/includes/bootstrap.inc).

So I'm guessing i'm giving in something which is an object instead of a string, which should be a string in fact. If I scroll down, I notice the that it says "Marker for " but doesn't give any content type after saying just that. I'm assuming that is the error? I'm also getting a few errors in my console

I really have no clue what to do, if i installed the wrong version or if I have some wrong settings somewhere?

Quick edit: using blocks in my regions, not really touching the PHP code I don't think that's a real issue.

I just found the issue myself through googling better. Sorry

https://www.drupal.org/node/2241573#comment-10493640

Some bad code at line 999 of the gmap.module file, remove this and it will work :)


Assign new role to user after puchasing a product I installed and configure Drupal commerce successfully in Drupal 8 and now I want to change the role of a user when he/her purchase a product. E.g I have a product type test and user role paid now when the test user purchase a product I want to assign the paid role to this user after successful purchase.

I did this in Drupal 7 via rules module but how in Drupal 8.

For Drupal Commerce on Drupal 8, Rules is not complete or integrated. This leaves many such tasks like this for custom development. Fortunately, it's also easier to alter individual parts of the Commerce system thanks to Drupal 8's object oriented architecture. In this case, you'd write a new class called an event subscriber to assign that user role on the "placed" transition - the point at time an order completes checkout or is placed by an administrator. It should then handle assigning the user role to the order owner.

There may be contributed modules available for Rules integration to support individual tasks like this, but it hasn't been a core priority as of yet while we focus on other major feature groups (e.g. shipping, addressbook, recurring billing, etc.).


How to access/print fields in non-Drupal php files? I'm using Drupal's php filter to add php code in node body of some of my nodes. Among other things, I'm also including a php file. That php file is doing some non-Drupal work and it is included in those nodes properly. However, I can't print Drupal's fields in that file.

Here is an example of php code in node's body field:

<?php

some work is happening here

include 'non-drupal.php'; // include non-drupal php file

some work is happening here

?>

Here is an example of non-drupal.php:

<?php

echo date('h:i:s'); // This works

print $title; // This doesn't work

?>

When I open that node, I can see the time, but there's no node title displayed.

Is it possible to print node fields from "external" php files?

EDIT (code added from dropbucket) I have tried with adding this code from Dropbucket, but it's not working either):

<?php

echo date('h:i:s'); // This works

function get_node_title($nid) {
return db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
} // This doesn't work (There is no output, but no errors displayed either)

?>

You could try it with drupal_bootstrap, but it is not tested.

define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$title = drupal_get_title();
echo $title;


Value in my custom base field added to user entity isn't saved I've created a new custom basefield for user entity type like this:
function hd_is_integration_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['is_uid'] = BaseFieldDefinition::create('text')
      ->setName('is_uid')
      ->setLabel(t('IS User ID'))
      ->setDescription(t('ID of this user in HD IS.'))
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
  }
}

I've also updated the entity schema with update hook:
function hd_is_integration_update_8001(&$sandbox) {
  $field_storage_definition = BaseFieldDefinition::create('string')
    ->setName('is_uid')
    ->setLabel(t('IS User ID'))
    ->setDescription(t('ID of this user in HD IS.'))
    ->setSettings([
      'max_length' => 50,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => 0,
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => 0,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('is_uid', 'user', 'user', $field_storage_definition);
}

The field is displaying fine in the user edit form, but any value added in it isn't saved. What am I missing, please?

In the end, I mofified my approach using https://www.drupal.org/project/one_time_password as an example. The difference is probably in the installation of the field definition - hook_install() works just fine.


Where and why are style tags removed in the render process? I have a block (in Drupal 8) that renders a field of a node. This is my build function:

public function build() {
  $node = $this->getNode();
  $build = array();
  $markup = array();
  $current_lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

  if ($node && $node->hasTranslation($current_lang)) {
    $node = $node->getTranslation($current_lang);
  }
  else {
    $node = false;
  }

  if ($node) {
    $fieldsToRender = array(
      'field_slider',
    );

    $viewmode = 'default';
    $entityType = 'node';
    $display = $this->getEntityViewDisplay();
    $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);

    foreach ($fieldsToRender as $field_name) {
      if (isset($node->{$field_name}) && $field = $node->{$field_name}) {

        $displayComponentSettings = $display->getComponent($field_name);

        if (!is_array($displayComponentSettings)) {
          $displayComponentSettings = array();
        }

        $fieldRenderable = $viewBuilder->viewField($field, $displayComponentSettings);
        if (count($fieldRenderable) &&! empty($fieldRenderable)) {
          $rendered = render($fieldRenderable);

          if ('' !== $rendered) {
            $markup[] = $rendered;
          }
        }
      }
    }

    if (count($markup)) {
      $build = array(
        '#type' => 'markup',
        '#markup' => implode("", $markup),
      );
    }
  }

  return $build;
}

When I dpm($rendered) after $rendered = render($fieldRenderable); it gives me the wanted markup, in which at some point is an inline style tag that comes from inside a paragraph's template.

For some reason though, the inline style tag is removed in the final block output. I thought it was maybe due to the filters in the page.html.twig but just rendering the region using {{ page.regionname }} makes no difference.

So, where (and why) does Drupal strip that style tag?

PS: I also noticed in the block version of the field strips the twig debug comments, while the above mentioned dpm output still contains them. So I guess it has something to do with how the block handles the build function's returned markup...

To complete Clive answer, you could directly use your $fieldRenderable variable into a new renderable array that you will return from your build() function.

Example (not tested) :

$build = [];
foreach ($fieldsToRender as $field_name) {
  // Do your stuff
  $build[] = $fieldRenderable; // you can put whatever you want for the key
}
return $build;

The render process is done when you return the $build variable.


Translate node with node fields I'm using the Node Field module. When I translate a node its respective node fields are not copied to the translation, forcing me to recreate them by hand. Is there a workaround to this?

I ended up solving the problem by using hook_node_insert:

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  // Only act if we are dealing with a content type supporting translations.

  if (translation_supported_type($node->type)) {

    if ($node->tnid != $node->nid) {

      $sql = "INSERT INTO node_field( nid, type ,title ,machine_name ,show_title ,hidden ,value ,weight ,settings)
          SELECT :new_node, type, title, machine_name, show_title, hidden, value, weight, settings
          FROM node_field
          WHERE nid=:old_node";

      db_query($sql, array(':new_node' => $node->nid, ':old_node' => $node->tnid));
    }
  }
}


How to group taxonomy and node flags together? I have 2 view block displays. One view displays flagged nodes and other displays flagged taxonomies. I need to print latest 8 flagged contents (nodes + taxonomy) in a single display sorted by title or term name, in ascending order.

Any suggestions about how to achieve this?

You could use the Views Contextual Filters OR module. Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

Create a view using 2 contextual filters (=both of the filters you already have for your 2 views), and combine them with an OR.


Drupal Form API Facebook Login I have Facebook for Drupal installed on my Drupal instance. My application and everything is working fine. I want to make it so one of my custom content types requires Facebook login to submit. Can I do this using the hook_form_alter()? This will be for anonymous users. I want them to see the content type (which they can already see) but once they fill in the fields and hit submit the form will require for them to be logged in through Facebook. Should i use that hook or can i accomplish this in another way?

I found out that the Drupal for Facebook module has User Management capabilities which allows me to automatically assign a temporary role to any users authenticated via Facebook. I added a role and changed the permissions to allow for the posting of my custom content type. Everything is working now! Hope this helps someone!!


Pre fill multiple paragraphs while adding node I want to prefill multiple paragraphs when user click on "add node" for specific content type. What would be a good way to do this ?

You can't reuse existing paragraphs, you have to create new paragraphs for each node:

$paragraph1 = Paragraph::create([
  'title' => 'Paragraph 1',
  'type' => 'paragraph_type1',
]);
$paragraph1->save();

$paragraph2 = Paragraph::create([
  'title' => 'Paragraph 2',
  'type' => 'paragraph_type2',
]);
$paragraph2->save();

$node = Node::create([
  'title' => 'Node with two paragraphs',
  'type' => 'article',
  'field_paragraph' => [$paragraph1, $paragraph2],
  ]);
$node->save();

You could place this code in a custom controller:

  public function addCustomContentType() {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => 'custom_content_type',
    ]);

    // create paragraphs, don't save them yet, in case the node is not submitted

    $paragraph1 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 1',
      'type' => 'paragraph_type1',
       // more field data
    ]);

    $paragraph2 = $this->entityTypeManager()->getStorage('paragraph')->create([
      'title' => 'Paragraph 2',
      'type' => 'paragraph_type2',
      // more field data
    ]);

    // prefill the paragraph field in the node with the paragraphs
    $node->field_paragraph = [$paragraph1, $paragraph2];

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;


Custom PHP vs Drupal Workflow for a Web Application not Websites This question can be too ambiguous but i think many new drupal users face this difficulty like me.

There are many blogs which says that Drupal is a CMF and we can use it for making Web Application rather then using it like Wordpress for articles and pages.

For the sake of example lets say i have to make a task management system with a specific Application style UI and features. If i would have to make it by custom programming i would be making tables for tasks, users, task_attachments, clients and so on and will make relations accordingy.

My question is how we can do all this stuff in Drupal? Nodes are for content and i would not go for nodes to achieve this. The other thing is Entity but How one can properly utilize Entities. If i have to list all tasks for a specific user, If a user want to update a status of his task or attach some file, If its a team and other team members should also be allowd to post updates on tasks. These are the common application scenarios that we usually make in this kind of application.

If someone provide a brief workflow then it would be a great effort for helping beginners like me to use Drupal as a developer rather than doing a data entry job by installing modules and copying content , images.

There is a good example erpal.info but its too advanced for me at this level to jump into it. but a mini erpal would be great.

Thanks Alot.

Your questions are somewhat vague but I'll provide some examples:

For instance I have a site that from a CSV file allows certain visitors emailed access keys to access a Webform and its tracked via a custom Node that has an embedded field collection and this relationship + status is tracked via a Relation. I use the Migrate module to add or update allowed visitor information from the CSV.

I use the Webform API, EntityFieldQuery's and drupal hooks to do my webapp business logic. Drupal core and contrib modules provide additional APIs. I use Views Send for bulk emailing.

I have another form site for class reviews for a campus. I use Migrate to pull $form structure info from a 3rd party survey database and then use a custom drupal entity and the drupal Form API to build a custom form from remote data. The remote database has a custom schema for say: Question, Options, Question position in Form, Form ID, etc ... it gets converted into a drupal $form array with some simple PHP in a Migration class. Again I use Relation to track what the student has completed between a uid and a nid. I use the drupal authorization mechanisms such as authmaps to integrate our local LDAP server.
On another site students should fill out like 10 content types after login. I use hook_menu_alter and a cookie to assure a student has Opted-In daily to EULA's for uploaded content. Then I use the core Form API to link 10 node edit forms on submission from 1 to another. Creating a kind of workflow for the student.

There are numerous times where knowing the Drupal contributed modules that help you create business logic, such as: Rules, Triggers, Rules Link, Maestro and WorkBench all help you create types of business logic.

Modules like References, Relation, Field Collection, Paragraphs let you create "embedded relationships". Mix and match as you need.

... I got tired of linking contrib modules :P


Webform E-mail send to selected user When the user is fill out my webform they are going be asked "who refer you to this page." The user would pick a user. I want to be able to send the results e-mail to that person programatically once they have submitted their question.

So I'm looking for a module allow me to e-mail the webform results base on  "who refer you to this page."?

I believe hook_node_presave() along with user_load() is your answer

something like this:

function hook_node_presave($node) {
if($node->type == 'webform') {

$uid = user_load($node->FIELDOFUID);

$uid->mail;

// do your mail send here with $uid->mail;

}

}


Where do you store arbitrary home page data? There's some welcome heading, text, video that goes on the front page. Currently this is stored in variables but it feels wrong to me because, well, it's a wall of text and variables is loaded on every page. Any module helping here?

If its all editable why not creating a content type "homepage"?
There will be only 1 node of this type(so what...)


How to translate the URL alias (path) for an English version to an Arabic version? I have a dual language site (English and Arabic). In the English version I added a URL alias: projects/commercial.

But I can't find a way to have that translated to the Arabic version. I need that because the path is used by a breadcrumb module.

Any suggestions?

Edit: I am using pathauto, but my problem is that the URL is for a view that lists certain projects based on contextual filters. So I added the alias projects/commercial instead of projects/7 the breadcrumb works fine in English but not in Arabic

For URLs related to nodes, users or taxonomies

Consider using the Pathauto i18n module for this. Excerpt from its project page:

  ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

pathauto_i18n_node (for nodes).
pathauto_i18n_user (for users).
pathauto_i18n_taxonomy (for taxonomy).

Example (also from project page):

When you create node without pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: not exist
Deutsche alias: not exist

When you create node with pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: it/articolo/first_article
Deutsche alias: de/artikel/first_article

For URLs related to views or panels

Use the i18n_path (Path Translation) sub-module of the i18n module. Refer to its Community documentation for more details about it.


Table with total per month I created a table with operations sorted by date. How to display a second array with the total transaction per month ?

I want to show by example the total in September 2016, the total amount of August 2016 ...

Table should display one line per month with the total amount of transactions.

The same month are not grouped :-(

I would recommend trying to use  Views Aggregator Plus

See Example here: https://www.drupal.org/node/2361413
It says a similar thing would work(aggregate and group by column).

God Bless.


A quick way to load images from a list of urls With media file selector widget it's possible to add images right from the web, without prior downloading them to the desktop.

But it quickly get's rather tedious if you have a list of image urls.

For adding multiple images from local drive there is a wonderful plupload module. But what's about convenient loading of remote files?

Haven't tried it, but I would use the Feeds module with a csv import of the urls to the files.

You may also need http://drupal.org/project/media_feeds.  I think this video shows how to do this http://ia600704.us.archive.org/35/items/WorkingWithMediaInD7/usingmedia.mp4


how to add content to a menu I want to publish a node to a custom menu page like "people" rather than the front page "Home." I tried many ways, but I cannot deal with this matter.

Could somebody tell me how to do it?

Have you reviewed the standard method of creating menus and adding nodes to menus?  Take a look at Working with Menus.


Add AJAX to form that was loaded through AJAX I may be missing something really basic here but it has been bothering me for a couple of days now.

I have a page that basically contains a link which loads another page through AJAX. The page that is loaded is basically a simple node/add form for articles. The problem is that the form that is loaded does not contain any AJAX behavior (I even installed the AJAX example module and the simple ajax checkbox that it is adding does not work). I do not know if it relevant but the fieldsets in the node add form are not working either.

I did some research and I am suspecting that I need to do something on the AJAX callback that loads the form. I read about Drupal.attachBehaviors which I tried attaching to the element where I'm loading my form but it does not seem to be working.

I'd be happy to edit my question to add some code but I was wondering if I'm missing something really basic.

Edit (my current code):

PHP:

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

  $items['aforms/article'] = array(
    'page callback' => 'aforms_get_form',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'delivery callback' => 'aforms_ajax_callback',
  );

  return $items;
}

function aforms_get_form() {

  global $user;

  module_load_include('inc', 'node', 'node.pages');
  drupal_add_library('system', 'drupal.ajax');

  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => 'article',
    'language' => LANGUAGE_NONE,
  );

  $form = drupal_get_form('article_node_form', $node);

  return $form;

}

function aforms_ajax_callback($form) {

  print drupal_render($form);

  drupal_page_footer();

}

JS:

(function ($) {

Drupal.behaviors.aforms = {
    attach: function(context, settings) {
        $('body').on("click", "#load-me-up", function() {

            $('#target-container').load('/aforms/article', function() {
                console.log('Before attach behaviors executed');
                console.log(context);
                console.log(settings);
                Drupal.attachBehaviors();
                console.log('After attach behaviors executed');
                console.log('Drupal object:');
                console.log(Drupal);
            });

        });
    }
}

})(jQuery);

You need to provide Drupal.attachBehaviors with the context (what was added) and the Drupal.settings. You should also use context in your script, so the JS should be rewritten something like this (not tested)

(function ($) {

  Drupal.behaviors.aforms = {
    attach: function(context, settings) {
      $('body', context).on("click", "#load-me-up", function() {
        $('#target-container').load('/aforms/article', function() {
          Drupal.attachBehaviors($(this), settings);
        });
      });
    }
  }

})(jQuery);

You need to use context on the $('body') to avoid the handle to be attached multiple times.
In the load callback you need to add $('#target-container') to attachBehaviors, but in this case $(this) should be the same thing.


How to get field structure for a custom content type? I have created a custom content type (mytest) via the Drupal 8 UI.

The content type contains a list field which has the following key|values:

gp|GP
device|Device

I have tried the following code to retrieve field, but it not there.

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'mytest');

Does any one know how to retrieve a List field structure?

I have to say sorry, I made a mistake in my other part of code.

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'mytest');

is correct, it returns all fields belongs to "mytest"


Webform data tables name change d7 to d8 tables to delete records from I have converted my d7 webforms to d8 with custom modules ... looks great
Previously I pulled data down from the database daily and deleted records from the webform_submissions and webform_submitted_data tables. (worked flawlessly for years)
With d8 the names are webform_submission and webform_submission_data.
Does anyone know if deleting the records from these two tables affects any other tables?  I intend to do as before... read daily, delete daily.
Thank you

I agree that you should use the 'Entity API' but if you are deleting 1000's of records I understand why you would want to do it using SQL.

Below are all the tables that are used to store webform submission related data.

webform_scheduled_email
webform_submission
webform_submission_data
webform_submission_log


Print taxonomy term name in node.tpl.php How can I print the taxonomy term name in node.tpl.php?

The following prints the name as a link, but I just want to print the name as text so I can make it a <div> class.

<?php print $terms ?>

$term = current($node->taxonomy);
echo '
' . $term->name . '
';


Overriding system.site.uuid with an environment variable I have a need to have separate sites behave as if they are clones of each other; that is, they each need to have the same site UUID.

Due to the environment I am operating in, I am unable to change the site UUID via drush config:edit once the site is installed as I have no SSH access to the environment. Likewise, the only way I can create a new site in this environment is to upload the files, create an empty database and then run the install script. This creates a new site, with a new UUID, and therefore is no longer a clone. Once sites are installed in the environment, my only way of interacting with them is through the administration UI.

Any site I create in this environment will have the same code base; it is not a matter of messing things up by importing the wrong config.

I can import the same database  into the new site once it is installed using Backup and Migrate, thereby changing the UUID (I assume). However, this does not quite solve the problem because it may be the case that I need to create sites via scripts in our continuous integration system.

My initial solution is to add a line in settings.php to override the configuration item in question, ie:

$config['system.site']['uuid'] = 'this is the site uuid';

However, when I export the configuration, the override value is not respected and configuration is exported using the original value. I can test this by exporting the configuration from a clone and trying to import it. If the UUID was being overridden 'fully', then I would expect the configuration import to fail.

Ideally, I would like to set the site UUID through an environment variable or service, so any site with access to the variable or service would be able to use the same UUID, and therefore be considered clones.

Has anyone had any success with something similar?

In the end, it was a matter of getting Drush to work on the remote environment.

I was also able to build a small module to update the site UUID of an existing site, however we didn't end up using it. The code for that is available at this repository.

Essentially, this boils down to running something like this:

\Drupal::configFactory()
    ->getEditable('system.site')
    ->set('uuid', $uuid)
    ->save(TRUE);

Where $uuid is whatever the UUID you want, whether this is generated manually or loaded from a service.


What does extension-provided configuration mean in Config Snapshot? Configuration Snapshot enables snapshotting of extension-provided
  configuration. It's used by Configuration Synchronizer to support
  updating configuration provided by modules, themes, and the install
  profile.

Recently I checked my database and found there are two tables
config
and
config_snapshot
I found that the module Config Snapshot creates the table config_snapshot table
While reading through project page text,I see it says "it enables snapshotting of extension-provided configuration"
What does extension-provided configuration mean ?

As commented by Clive,

  “Extension” seems just to be being used as a catch-all term for
  modules, themes and installation profiles. Those three are the only
  things that can provide config outside of core, so it seems a safe bet


image slider for drupal I'm making my first drupal website and I want to have a image slider on the homepage. I would like there to be a page in the backend where the end-user can upload and choose which images are in the slideshow. I looked at the nivo-slider module but it only allows the creation of one slider and what I really need are two separate sliders one for English and one for French content.

Is there a module that has this functionality already? If I wanted to create something like this myself would that involve making a module or can it be part of my theme's code somehow?

You can use the
View Slideshow module and create many blocks of slider from the content you create.

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


Use views to create a custom sql query? I'm still not comfortable writing sql queries. As i'm pretty new to drupal module writing.

Are there any potential issues with using views to generate a sql query? In terms of security or future considerations?

Example:
Generate a form dropdown on the usermenu of number of users by role.

Grabbed this query via creating a view

  $query = "SELECT users.uid AS uid,
   users.mail AS users_mail,
   users.name AS users_name
   FROM users users
   INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
   WHERE users_roles.rid = 7";

Convert database object into array:

while ($user = db_fetch_object($result)) {
  $reps[$user->uid] = $user->users_name . ' - ' . $user->users_mail;
}

Spit out the options and create a form dropdown:

// Generate output of all the client reps
$form['Business']['profile_txi_account_rep']['#options'] =  $reps;

The only real downside that I can think of is that the SQL that is generated can be really verbose, as it is not meant to be read by humans.

Very often, I will take a first pass at functionality for something using Views, grab the SQL, and then refine/optimize.  In fact, using Views to generate the initial SQL can be very handy for figuring out what you need to do your JOINs on.

One catch is that Views knows about internal structure.  If you do something that changes underlying table structure, Views will compensate automagically.  You would need to update your SQL manually.  One place this happens is with Drupal 6 and CCK, when you change fields from single value on a single content type to multiple value and/or add them to multiple content types.

All of that said, the new database abstraction layer and EntityFieldQuery does make life easier, and you may not need to use Views as an intermediate step.


Why is libraries-override not removing assets? My attempt to remove CSS and JS assets is not working.  I have placed the following declarations in my module's *.info.yml file.  But after clearing the cache, I still see the assets in the head of the document.  Is there anything wrong with my syntax:

libraries-override:
  global-styling:
    css:
      base:
        /themes/stack/css/lightbox.min.css: false
    js:
      /themes/stack/js/lightbox.min.js: false

Here is the relevant Drupal documentation:
https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme#override-extend

I also tried these for the key:

stack/global-styling
stack.global-styling

I also tried it without the full paths:

libraries-override:
  stack/global-styling:
    css:
      base:
        lightbox.min.css: false
    js:
      lightbox.min.js: false

Nothing is working so far.

This doesn't answer the original question, but turns out to be a better solution in my case.  You must clear your cache with each change to this function:

/**
 * Implements hook_library_info_alter().
 */
function example_library_info_alter(&$libraries, $extension) {

  // If you have 'stack' as your subtheme, you might have unwanted lightbox assets.
  if ('stack' === $extension) {

    if (isset($libraries['global-styling'])) {

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

      // Your conditions may vary.
      if ('book' == $path_args[1] && isset($path_args[2]) && is_numeric($path_args[2])) {

        // Helper function below.
        if (example_array_key_exists_r('css/lightbox.min.css', $libraries)) {
            unset($libraries['global-styling']['css']['base']['css/lightbox.min.css']);
        }

        if (example_array_key_exists_r('js/lightbox.min.js', $libraries)) {
            unset($libraries['global-styling']['js']['js/lightbox.min.js']);
        }

      }
    }
  }

}

/**
 * Recursively search for an array key.
 *
 * @see https://stackoverflow.com/a/2948985/861826
 *
 */
function example_array_key_exists_r($needle, $haystack) {

  $result = array_key_exists($needle, $haystack);

  if ($result) return $result;

    foreach ($haystack as $v) {
      if (is_array($v)) {
        $result = example_array_key_exists_r($needle, $v);
      }
      if ($result) return $result;
    }

    return $result;
}


How to run commerce_order_save() without triggering any rules? I need to run commerce_order_save() on several Orders in loop but without triggering any Rules.

Is that possible ?

It's possible, but the change would need to be sitewide (not just in the context of rules). You'd need to override the entity controller class used for commerce_product (which you could do with hook_entity_info_alter()), and re-implement its save() method so it doesn't invoke the entity hooks.

If that is undesirable (probably is), and you just need to update field values, you can use field_attach_update() instead, which will bypass the entity save process altogether:

$order->some_field[LANGUAGE_NONE][0]['value'] = 'foo';
field_attach_update('commerce_order', $order);

Other than those I don't think there's any way to accomplish it using the API.