Programmatically created content type don't have a delete link I'm developing a module that creates new content types through form that I created (not in hook_install):

function create_new_content_type($type, $name){
    $t = get_t();

    $new_node = array(
        'type' => $type,
        'name' => $name,
        'base' => 'node_content',
        //'description' => 'This is an example node type with a few fields.',
    );
    $content_type = node_type_set_defaults($new_node);
    node_add_body_field($content_type);

    // Check if we create content type or update.
    $status = node_type_save($content_type);

    // Replacement rule for the messages.
    $t_args = array('%name' => $content_type->name);

    if ($status == SAVED_NEW) { // create case
        watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
        return true;
    }

    return false;
}

When I go to admin/structure/types these I don't see the delete link.
I found here some similar questions that suggest to remove with /admin/structure/types/manage/<content-type-name>/delete but it's not a good solution for me.
Is it possible to display that link?

EDIT:
This is what I mean:

You could always take the dull axe approach and use a page_alter, eg, something along the lines of

function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $page['content']['system_main']['node_table']['#rows'][]=array(
      'Foo (Machine name: foo)
Here is my description of foo
',
      array('data' => l(t('edit'), 'admin/structure/types/manage/foo')),
      array('data' => l(t('manage fields'), 'admin/structure/types/manage/foo/fields')),
      array('data' => l(t('manage display'), 'admin/structure/types/manage/foo/display')),
      array('data' => l(t('delete'), 'admin/structure/types/manage/foo/delete')),
    );

  }

}

which will create a row for type foo.

Per additions to the question:  since the row is showing up but just without the delete link, you can go in and create it similarly, eg,

$page['content']['system_main']['node_table']['#rows'][NUM][4]=array('data' => l('delete', 'admin/structure/types/manage/foo/delete'));

where NUM is the row number where your content type is found. You might also want to check out Adding an operation to Content Types and the page_alter() there on a possible way you might be able to easily figure out NUM.

Another addition:

Could you just do this in your module:

$info = array(
    'type' => $type,
    'name' => $name,
    'base' => 'node_content',
    'custom' => TRUE, // fake it out to think it was made via the UI...
);
$content_type = node_type_set_defaults($info);

A cursory glance through the code and node_type_set_defaults() suggests that the only thing this does is allow this delete link to be presented in this very form.


Translate menu with wildcard I am creating a menu item using hook_menu() and what I want is to translate it when I am using a wildcard, because I have a multilingual site.

There is a solution, using t()[, but it's not the best approach.

$items['account/edit/%'] = array(
  'title'            => t('Edit account information'),
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('partners_add', 2),
  'access arguments' => array('edit account in partners'),
  'type'             => MENU_NORMAL_ITEM,
  'file'             => 'inc/partners.form.inc',
);

Does anyone know how to translate it using the Drupal interface?

Thanks in advance!

The point is moot, because the the hook_menu strings should not be translated at all. Your code should in fact be:
$items['account/edit/%'] = array(
  'title'            => 'Edit account information',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('partners_add', 2),
  'access arguments' => array('edit account in partners'),
  'type'             => MENU_NORMAL_ITEM,
  'file'             => 'inc/partners.form.inc',
);

I quote from: http://drupal.org/node/323101:

The Drupal 6 and 7 menu system stores menu item titles and descriptions in English. This allows the system to cache the data, but display to users using various languages on demand. For this to work, you should not use t() on the title or description of menu items in your hook_menu() implementation.
Again, we use plain English so that the menu system can store the English text and translate as required, benefiting performance. If, instead, we use t(), the menu system would store the menu item titles and descriptions in the language of the first visitor when the menu cache was rebuilt, which would not work as a base for translations on a multilingual site.


Ubercart most selling product in drupal 7 I'm using Drupal 7 on my site with Ubercart 7.x - 3.4. I want is an existing module or a view customization tips to make the most selling / best selling product.

Here is a view Export

$view = new view;
$view->name = 'best_sellers';
$view->description = 'Best Sellers';
$view->tag = 'Best Sellers';
$view->base_table = 'node';
$view->human_name = 'Best Sellers';
$view->core = 7;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Fields: uc_product_image */
$handler->display->display_options['fields']['entity_id']['id'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['table'] = 'field_data_uc_product_image';
$handler->display->display_options['fields']['entity_id']['field'] = 'entity_id';
$handler->display->display_options['fields']['entity_id']['label'] = '';
$handler->display->display_options['fields']['entity_id']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['trim'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['entity_id']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['entity_id']['alter']['html'] = 0;
$handler->display->display_options['fields']['entity_id']['element_label_colon'] = 1;
$handler->display->display_options['fields']['entity_id']['element_default_classes'] = 1;
$handler->display->display_options['fields']['entity_id']['hide_empty'] = 0;
$handler->display->display_options['fields']['entity_id']['empty_zero'] = 0;
$handler->display->display_options['fields']['entity_id']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['entity_id']['settings'] = array(
  'image_style' => 'thumbnail',
  'image_link' => 'content',
);
/* Field: Node: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['title']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['title']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['title']['alter']['trim'] = 0;
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['title']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['title']['alter']['html'] = 0;
$handler->display->display_options['fields']['title']['element_label_colon'] = 1;
$handler->display->display_options['fields']['title']['element_default_classes'] = 1;
$handler->display->display_options['fields']['title']['hide_empty'] = 0;
$handler->display->display_options['fields']['title']['empty_zero'] = 0;
$handler->display->display_options['fields']['title']['link_to_node'] = 1;
/* Field: Product: Buy it now button */
$handler->display->display_options['fields']['buyitnowbutton']['id'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['table'] = 'uc_products';
$handler->display->display_options['fields']['buyitnowbutton']['field'] = 'buyitnowbutton';
$handler->display->display_options['fields']['buyitnowbutton']['label'] = '';
$handler->display->display_options['fields']['buyitnowbutton']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['trim'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['alter']['html'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['element_label_colon'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['element_default_classes'] = 1;
$handler->display->display_options['fields']['buyitnowbutton']['hide_empty'] = 0;
$handler->display->display_options['fields']['buyitnowbutton']['empty_zero'] = 0;
/* Field: Product: Sell price */
$handler->display->display_options['fields']['sell_price']['id'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['table'] = 'uc_products';
$handler->display->display_options['fields']['sell_price']['field'] = 'sell_price';
$handler->display->display_options['fields']['sell_price']['label'] = '';
$handler->display->display_options['fields']['sell_price']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['trim'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['sell_price']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['sell_price']['alter']['html'] = 0;
$handler->display->display_options['fields']['sell_price']['element_label_colon'] = 1;
$handler->display->display_options['fields']['sell_price']['element_default_classes'] = 1;
$handler->display->display_options['fields']['sell_price']['hide_empty'] = 0;
$handler->display->display_options['fields']['sell_price']['empty_zero'] = 0;
$handler->display->display_options['fields']['sell_price']['set_precision'] = 0;
$handler->display->display_options['fields']['sell_price']['precision'] = '0';
$handler->display->display_options['fields']['sell_price']['format_plural'] = 0;
/* Sort criterion: Order product: Qty */
$handler->display->display_options['sorts']['qty']['id'] = 'qty';
$handler->display->display_options['sorts']['qty']['table'] = 'uc_order_products';
$handler->display->display_options['sorts']['qty']['field'] = 'qty';
$handler->display->display_options['sorts']['qty']['order'] = 'DESC';
/* Filter: Node: Is a product */
$handler->display->display_options['filters']['is_product']['id'] = 'is_product';
$handler->display->display_options['filters']['is_product']['table'] = 'uc_products';
$handler->display->display_options['filters']['is_product']['field'] = 'is_product';
$handler->display->display_options['filters']['is_product']['value'] = '1';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'best_sellers');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Best Sellers';
$handler->display->display_options['defaults']['css_class'] = FALSE;
$handler->display->display_options['css_class'] = 'new-product-block';
$handler->display->display_options['block_description'] = 'Best Sellers';
$translatables['best_sellers'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('.'),
  t(','),
  t('Block'),
  t('Best Sellers'),
);

How to

Login to Drupal as an administrator. Go to Structure > Views.
Click “Import View from Code”

Add "Popular Products" view


How do I print the node add form in block.tpl.php? I am using Microblog. How do I print the node add form in a block?

I tried node_add('microblog'), but it doesn't work for me; then, I tried drupal_get_form('microblog_node_form'), but I am still getting nothing.

The drupal_get_form approach is correct. Make sure you use

print drupal_get_form(....

Edit:

Take a look at function node_add().
You also need a $node parameter for this form. So like

<?php
  global user;
  $node = array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'foo', 'language' => '');
  print drupal_get_form('foo_node_form', $node);
?>


How to use hook_entity_presave? I have a product type called package. It is a package of another product type which is called applications; when a user wants to create or update a package , I want to calculate the price of the package by adding the price of all applications in that package . I want to use hook_entity_presave(). but it doesn't work. I have put my function here.

My question: what should I check exactly against the $entity->type? My node type? Or my product type? It doesn't work either way.

function itunesdev_entity_presave(&$entity, $type) {
  if($entity->type == 'package') {
    $product_ids = array();
    foreach($entity->field_products[LANGUAGE_NONE] as $key => $pid)
      $product_ids[] = $pid['target_id'];
    $products = entity_load('commerce_product', $product_ids);
    // reset default price
    $entity->commerce_price[LANGUAGE_NONE][0]['amount'] = 0;
    foreach($products as $pid => $product) {
      $entity->commerce_price[LANGUAGE_NONE][0]['amount'] += $product->commerce_price[LANGUAGE_NONE][0]['amount'];
    }
  }
}

Function hook_entity_presave acts on an entity before it is about to be created or updated

Code:

  function hook_entity_presave($entity, $type) {
    $entity->changed = REQUEST_TIME;
  }

source :  Drupal API


How to allow Infinite Scrolling through "Views Load More" module with waypoints? I am trying to achieve infinite scrolling for my view results in Drupal.

Now It could have been easier if I could use Views Infinite Scroll module but I couldn't use as it doesn't allow Views Ajax. Since I am using filters that heavily rely on AJAX, I am out of luck for using this module.

As I read, there is another option through Views Load More module, but it can only allow infinite scroll through Waypoints. This is where my problem lies as I am unable to understand how to use waypoints with Views Load More module.

I'll be super grateful if you could assist me in this.

This is Waypoints code from their site:-

var waypoint = new Waypoint({
  element: document.getElementById('#waypoint'),
  handler: function(direction) {
    console.log('Scrolled to waypoint!')
  }
})

It's actually really easy to do with standard Views and jQuery.autopager in your theme.

The most important part is using the correct classes, I can't find my working example at the moment, but it should look something like:

$.autopager({
  // where contents would be appended.
  // use "appendTo" or "insertBefore"
  appendTo: '.views-content',

  // a selector that matches a element of next page link
  link: '.pagination .next a:first',

  // a selector that matches page contents
  content: '.views-row',
});


How to use Views with Fields Collection and filter on where used I am using Entity Registrations to handle registrations for a sponsored walk. I have setup a fields collection so that registrants can register more than one person at a time.

At the moment there is only one Registration Entity for the 2013 sponsored walk, but in future there will be more.

So.... In views I want to create a table that allows the admin to view the fields collection related to a specific Entity Registration. i.e. Show only those users registered for the Spring 2013 sponsored  walk or just those registered for the Summer 2013 Walk.

I could duplicate my fields collection to make a new one for each Entity Registration, but I would rather avoid that type of duplication if I can help it.

Any ideas?

I hope you are creating a view of the type Registration in that case you can add a contextual filter of the type Registration: Host entity ID

Now when you add the nid of the main node you would see the registration specific to that node.

Note : To get the Registration: Host entity ID as a contextual filter you need to enable the Registration Views module.


Registration and Webforms I'm using Drupal 7 - is there any way to view and output the users who've registered with site in a similar way to how Webforms displays submissions and allows you to download and import into Excel?

I can export the users table from the database as a CSV file but I was hoping to find something that would be integrated into the Drupal admin ui (similar to the way Webforms is).

Thank you for any guidance you can provide.

There are two modules that you could use, the 'Database Administration' and 'Views Excel Export' These are still in alpha and dev for drupal 7 but might worth a try.


Pre-defined color picking in the node admin in Drupal 7 I want the user to select one of the predefined color for one my Article fields.

I am unable to find a suitable way for the user to do so though. What I want is that there is a color picker of selected colors and user is able to pick on.

Any idea ?

Thanks

Like I said in my comment I'm having trouble understanding the actual question. If you want a user to be able to choose from a set of predefined colors and connect this value to a node of type article you could do like this:

Visit admin/structure/types/manage/article/fields
Add a new field of type List (text)
Set the widget to Selectlist and press save
On the next page under Allowed values list you then enter all your colors in the form key|value for instance Red|Red or Black|Black and then press Save field settings
In the next form you might set if this field is required or not and a default value

Now your users can select a color from a select list on the article edit screen. Not sure this is what you're asking for though.

Here is an example of what the user will see when editing an article:


Adding cherry-picked nodes to a list On a project I'm working on, we'd like to give users the ability to search for nodes via a View with exposed fields, and then have them able to select specific nodes to be added to a list.

We've thought about doing this via taxonomy terms and Views Bulk Operations, but that's not very streamlined (I'd have to set the action to "Modify entity data," selecting the taxonomy field -- but then there'd be a bunch of options on the next page and the default behaviour is to overwrite all the terms attached to a node.).

Any ideas how one can create a simple cherry-picked list, ideally from Views result content?

We have done this using the 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.

Make a flag and add it to your content type.  You may be able to use one of the default flags.

Configure the flag to appear on just teasers.

In your view, configure it for node output, and choose teasers and show links.  I think you can add the flag as a "field" in field-based output, but I don't remember.

Then, your view should show your list of nodes and each will have a flag link with it.  Users can flag their nodes.

You can then make views over the nodes that your users have flagged, either all together or per user.  The Flag module integrates very nicely with Views.


How to change number of item per page in taxonomy page? I have multiple content types. I want to change number of item per page in teaser mode and  it is different for every content type.

In admin/config/system/site-information we can change number of item for all content types. But I want to change number of items for each content type.

What do I do? Please help.

.

Go to Admin > Structure > Views. Enable the Taxonomy Term View :

In views configuration change the pager settings as you want.


How to add HTML tag in Drupal block ? I would appreciate your help in my problem with html tagging or css class in blocks.

I've tried Field Formatter Class and Field Formatter CSS Class modules, but with those I only could add class to Article, Basic page and own types, which doesn't help me as I don't want to add Read more or RSS. When I definied my new content type, I didn't check the RSS box and I did check the full content box, but stil...

So, is there any module to add CSS class or HTML tag to a block. Different tags, of course for every block.

No PHP please.

Thanks,
cs.

You can use the Block class module which adds a field to each block where a class can be added.

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent <div class="block ..."> element of a block.


Create ECK Entity via Ajax I'm trying to create a ECK Entity Content programmatically. I know, because I've used it elsewhere, I have the right code for creating the Entity Content but in my current setup it is not working anymore.
What I have is the following:
.routing.yml
timetracking.ajax_check:
path: '/js/timetracking/ajax/{nid}'
defaults:
    _controller: '\Drupal\timetracking\Controller\TimeTrackingController::timetrackingAjaxCheck'
requirements:
    _csrf_token: 'TRUE'

TimeTrackingControlle.php
<?php

namespace Drupal\timetracking\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Controller routines for user routes.
 */
class TimeTrackingController extends ControllerBase {

  public function timetrackingAjaxCheck($nid) {
    $user = $this->currentUser();
    $timer = (int) $this->timeSpentConfig->get('time_spent_timer');
    /* @    -- Save One Test Entity */
    $test_entity = \Drupal::entityTypeManager()->getStorage('time_tracking')->create([
      'type' => 'time',
      'title' => 'test-2',
      'field_id' => 1,
    ]);
    $test_entity->save();
  }
}

.js
(function ($, Drupal) {
  Drupal.behaviors.timetracking = {
    attach: function(context, settings) {
      // Fetch ajax callback url
      var callbackUrl = '/js/timetracking/ajax/10';

      function timetrackingSendTimer() {
        $.ajax({
          type: 'get',
          url: callbackUrl,
          dataType: 'json',
          data: 'js=1&timer=10'
        });
      }
      timetrackingSendTimer();
    }
  }
})(jQuery, Drupal);

When I put the Save One Test Entity in a .module file it creates an Enitity but when I put it inside the controller it is not. The controller is running as expected when I am debugging it using DPM I get a nice output.
I'm wondering if it is possible to do this inside the Controller? And if not how can I use Ajax to create an ECK Entity?

In your route you require CSRF token and your ajax call is missing the CSRF token.
Get a CSRF token from ur drupal site using url "/session/token" and send it with your Ajax request.
But is it wise to do it this way? i don't know.
For making ECK Entity with ajax Post i would use REST resource or make a custom REST resource with basic_auth or cookie authentication, that way you wont need a CSRF Token.


How to display event's views block inside another content type's content section with only events related to that content alone? I am working on a drupal7 site. The scenario is that, there are 2 content types namely singers and events. When i am adding an event, i need to add an event to a singer, so that when i am viewing a singer's node page, i can see  block containing events related to that singer alone.

I have done the events block inside the singer's content page(Using the views block). But it displays all the events and i want to display the only the events related to that singer alone. I have tried to make it using term reference or some other stuff. But nothing have worked out. Can anyone help me out to get this scenario working. Thanks in advance.

You can use theentity reference and rules modules for this.

First, add entity ref fields to both singers and events. Then, create a rule so that, when an event is created, which refers to a singer, the singer gets updated with a reference back to the event.

Your singer nodes should therefore have references to all the events that refer to that singer. In the display settings for the singer nodes, you can render the referenced nodes as, say teasers.


How to construct database query with conditions that include 'and' and 'or' clauses? I am converting a Drupal 6 module to a Drupal 7 module. I have come across the following database query that I don't know how to convert to the new Drupal 7 format.

$sql = "
  SELECT id
  FROM {room_reservations}
  WHERE (
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
    OR
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
    OR
    (deleted = '%s' AND room = '%s' AND date = '%s' AND time = '%s' AND length > %d)
  )
";

Although the where clauses do repeat itself, each substituted value in there is different. My question is how does one construct such a statement in Drupal 7 using the new database API? Can you mix and and or statements?

Thanks.

Here's an example, taken from statistics.pages.inc

$query = db_select('accesslog', 'a', array('target' => 'slave'))->extend('PagerDefault')->extend('TableSort');
$query->join('users', 'u', 'a.uid = u.uid');

$query
  ->fields('a', array('aid', 'timestamp', 'url', 'uid'))
  ->fields('u', array('name'))
   ->condition(db_or()
    ->condition('a.path', 'node/' . $node->nid)
    ->condition('a.path', 'node/' . $node->nid . '/%', 'LIKE'))
  ->limit(30)
  ->orderByHeader($header);

What you want to notice, is the use of db_or(), which adds an OR to your query. There is also the similar db_and(). You can mix and match the two as much as you want. The db_and() documentation also has comments with examples of the two used together.


Drupal Field API - Settings List I'm trying to create a 'link_field' in Drupal through a module, I've got the following code but I'd like to configure the field settings to do the following:

Not require title
Update the number of values to unlimited

I'm struggling to find any information around what setting key/pair values you can pass through for these, anyone able to offer some guidance on these?

    <?php
/**
 * Implements hook_enable().
 *
 * Create a field. Fields can be created without any needs to attach them to
 * entities.
 */
function youtube_carousel_enable() {
  $field = array(
    'field_name' => 'ytcarousel_field',
    'type' => 'link_field',
  );
  field_create_field($field);

  /**
  * Bind field to a entity bundle.
  */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video'
  );
  field_create_instance($instance);
}

/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */
function youtube_carousel_disable() {
  $instance = array(
    'field_name' => 'ytcarousel_field',
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video'
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}
?>

Cheers

After viewing the HTML source to get key/value pairs I've managed to do something similar to the above with the following code:

<?php
/**
 * Implements hook_enable().
 *
 * Create a field. Fields can be created without any needs to attach them to
 * entities.
 */
function youtube_carousel_enable() {
  $field = array(
    'field_name' => 'ytcarousel_field',
    'type' => 'link_field',
    'cardinality' => -1
  );
  field_create_field($field);

  /**
  * Bind field to a entity bundle.
  */
  $instance = array(
    'field_name' => $field['field_name'],
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_create_instance($instance);
}

/**
 * Implements hook_disable().
 *
 * Remove field from node bundle (content type) and then delete the field.
 */
function youtube_carousel_disable() {
  $instance = array(
    'field_name' => 'ytcarousel_field',
    'entity_type' => 'node',
    'bundle' => 'homepage',
    'label' => 'YouTube Video',
    'settings' => array('title' => 'required')
  );
  field_delete_instance($instance);
  field_delete_field($instance['field_name']);
  print 'Removed ' . $instance['field_name'] . "\n";
}
?>

The cardinality controls have many instances the value can have, "-1" is unlimited.

'cardinality' => -1

The title attribute is controlled via the instance not the field itself, I believe, and it uses text based values rather than numeric.

'settings' => array('title' => 'required')


drupal running really slow on apache mac os x I'm running drupal sites on my localhost with virtual host.
everything was running perfect but then it suddenly stopped working, I tried to restart apache to fix the error but still not working.
It takes about 30 seconds to load the home page, and about the same for other pages.
I'm running mac os x with Apache MySQL "no MAMP".
thats really confusing me more is that it runs only on firefox, on safari it takes forever and never loads.

Install devel module in your drupal site. After enabling devel module, you need to enable query log and page timer in devel configuration page. by doing this you will see how much time each function is taking to load and will able to analyze you site.


defining relationships between terms in a taxonomy Is there a module which allows you to define a relationship between some terms in a taxonomy? Specifically, being adjacent? The taxonomy is flat.
So that Auckland has Northland and Waikato as neighbours (the use case would be to build a view of events in nearby regions)

My searching can't have used the right names for this - I'm not finding anything :-)

The relationship functionality exists in Drupal core - no need for a contributed module.

Go to /admin/structure/taxonomy/YOUR_VOCABULARY/fields and add a new field of type Term reference, click Save.

On the next screen

change Number of values from 1 to Unlimited
choose the same vocabulary you added the field to in the Vocabulary dropdown.

Then edit each term and add the neighbouring regions to it.


First order ID different from 1 I am using Commerce Kickstart, and I want to use as order ID any desire number, where by default the first order ID is 1.

How can I achieve this?

I saw a similar post.

Just a quick behind-the-scenes tidbit here: Drupal Commerce separates out its internal Order ID from what you see on the front end as the Order number. The Order ID is a serial numeric value that increments with each order created (including orders that are still shopping carts). The Order number can be any alphanumeric string, but it initialises to be the same as the Order ID. (Some sites then update orders upon creation to use a special alphanumeric order number format instead of the regular integer format.)

What you want to change is the AUTO_INCREMENT value on the commerce_order table. This will make it so the next created Order ID will start with the increased AUTO_INCREMENT value. By default when you create a new site, this will be set to 1, but feel free to set it as high as you need it to go. This is especially important if you're migrating an old site but using the same payment gateway, as they sometimes don't support the same order number being used twice.

The query to update this is:

ALTER TABLE  `commerce_order` AUTO_INCREMENT = 1000;

Where 1000 is replaced by whatever number you need the next created order to start at. This won't affect any existing order, just the next order to be saved to the database.


Remember add to cart form state Is there a way to remember the chosen product attribute on the add to cart form? I have a product with a couple of options. If the users selects one on the product page and goes to another page, the form will reset and selects the first option again.

You can store it in session

During Add to cart.

$_SESSION['my_module_name']['product_id']['field_name'] = $filter_value

Then set form option value from session

function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    $get_default_value = isset($_SESSION['my_module_name']['product_id']['field_name'])?$_SESSION['my_module_name']['product_id']['field_name']:'';
    $form['field_name']['#default_value'] = $get_default_value;
  }
}


Submitting a form with only a text field I may be missing something obvious, but it appears my form's submit function isn't being run by simply submitting text into my textfield (via. enter).  Do I need to add the submit button to get this behavior?  Is there a workaround so I don't have to?

Yes, for basic forms you need to include a submit button for the submit function to be called.

Read more about the Form API for Drupal 7


PHPUnit test complex method that use drupal service within it I have a method of a class that returns me the list of fields that have been created outside of core Drupal. The method is:

/**
   * @param $contentType
   * @return array $fields
   */
  public function getContentTypeFields($contentType) {
    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $entityManager */
    $entityManager = \Drupal::service('entity_field.manager');
    $fields = array();

    if (!empty($contentType)) {
      $fields = array_filter(
        $entityManager->getFieldDefinitions('node', $contentType),
        function ($fieldDefinition) {
          return $fieldDefinition instanceof FieldConfigInterface;
        }
      );
    }

    return $fields;
  }

So you pass in a content_type name and the method will return an array of fields that have been created by us, so not the default Drupal fields.

I cant figure out how to write a Unit Test for this method, can someone please help?

Resurrecting this.  The first method would be to include the EntityFieldManager as an argument to your function or constructor, so you can send a mock object in.

The second would be to look at some of the tests in core.  Specifically core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php where the container is mocked and dependencies set up.

$container = new ContainerBuilder();
$container->set('entity_type.manager', $entity_type_manager->reveal());
...
\Drupal::setContainer($container);


How to hide comment section present in render array? I have generated an array in Drupal 8 which is created by using viewbuilder in this manner:

 $content = $this->entityManager()->getViewBuilder($entity->getEntityTypeId())>view($entity, 'hardcopy');

And now I want to hide comment section present in this array.

Any idea on how to do this?

The result that you get there is only prepared, the actual rendered content is not set there, you can't remove it there.

The comments are a field, you can hide/show them in the manage view display UI like any other files.

Define a view mode/display for your use case if the default ones don't work for you and then configure it there.

Doing it in code is only possibly in indirect ways. You'd need to set a flag in $content and then implement hook_node_view() alter and remove it there.


Use Drupal as a 'cloud system' frontend, what is your opinion? I'm working on a small project where I need implement some kind of cloud architecture.

I'd like to deploy multiple Drupal installs among multiple servers; one would act as a domain controller and other as nodes. It should be simple to scale; adding nodes to the cluster would be as simple as cloning a node install and changing it's parameters (such as IP address and name). The new node will then announce itself to the controller which would update its nodes-list records.

I also like to be able to manage users in a centralized way; I would add users to the controller and assign them one or many nodes; once created it would sync to the target node(s) (e.g. create the user in the unix list as well as in drupal install on the target node).

Finally, once logged in the controller, the user would be able to do various operations such as:

download/upload files to nodes (on which he's granted to)
execute predefined shell commands such as starting/stopping services (probably as a module that would do all that stuff)

I hear that Drupal 7 has now some interesting file management modules in core; can they help in my case? Also, what would be the best communication protocol for accessing the different nodes from the controller?

Is it possible to have a kind of RPC call to a module (on target node) from the controller and get the result back ?

Any thoughts or starting points?

You might want to look at Aegir.
It will let you manage multiple Drupal sites across multiple servers; you can add new servers via the Aegir master controller and once the servers are known to the controller you can create complex Drupal installs via the UI (Aegir master) with db on one server and code on other, mix and match, etc.

One of the cool stuff is that Aegir can also take a drush make file and assemble a Drupal install for you; it supports Drupal distributions which let you not only install Drupal, but also Open Atrium, Pressflow, Open Publish, etc.

If I were you I would definitely look at Aegir even if it doesn't take care of all my needs as it will be the only logical place to start extending.

For an introduction see An introduction to the Aegir Hosting system.

There are so many Aegir videos online; these are some of my favorites:

http://greenbeedigital.com.au/content/drupaldojo-introduction-aegir-hosting-system
By Miguel: http://greenbeedigital.com.au/content/installing-aegir-04-beta1
Again by Miguel; it's a must watch: http://greenbeedigital.com.au/content/building-drupal-applications-drushmake-provisioning-sites-aegir

If you like looking at code, here is the code for provisioning system which does all the magic: http://git.aegirproject.org/?p=provision.git;a=summary.


How to create node navigation to cycle through nodes of specific content type I would like to add node navigations (prev - next) at the bottom of each node of a specific content type so that I can cycle through all the nodes for that content type.
Here is an example (scroll to the bottom of the article) http://happycog.com/work/blackhills.  You'll notice that there are navigation links that take you to the previous or next article.

I'd appreciate any guidance on how I can accomplish this.  I've looked at various contrib modules but none have given me the result I am looking for.

Thank you,

mario

Have a look at these two modules:

Flippy
Custom Pagers

Custom Pagers is more versatile, but I found it buggy.
Another solution, more custom and flexible, would be creating a custom field in the content type (via hook_field_extra_fields() or Display Suite), and creating a custom query to get the next/previous node ids. If you prefer to go with the custom way but don't want to add a custom field, you can just preprocess the node and add the variable in your .tpl file.
Previous/Next API module could be used to get the node ids without the need to create the query yourself, apparently making the solution more scalable. It's still a -dev version though.


How to load aggregated styles / js in an 'external' script via DRUPAL_BOOTSTRAP_FULL? I have an external script / php application that I now have to implement into a running D7 site. So far DRUPAL_BOOTSTRAP_FULL seems to do the job just fine – I can read the session, check the user etc.

But I am currently stuck trying to load the $styles and $scripts into the head of that external application. I tried drupal_get_css();, also checked the $variables and also tried template_preprocess_html(); to preprocess the  variables –– but D7 won't return anything.

What I have so far:

define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

I hope somebody can direct me in some direction – any pointers appreciated. Thank you!

Update: The solution suggested by oksana-c works quite well if you 'only' need to load the top css and js files. The site I'm working on however caches and aggregates all js and css files into one – including various files provided by different modules… So what I would actually need to find out is how to link to those aggregated js and css files. Anybody?

Update2: I could 'crawl' the folders where the aggregated css and js are stored – however currently I can see 4 different js files and 4 different css files in the head. Also according to the files' timestamps sometimes only 2 files were generated and loaded in the past – so I have basically no indication of how many of the most recent files I should include. Probably some hook would help that would let me list whatever cached/aggregated files are loaded at this time – but I still have no idea where/how to hook into the caching/aggregating functions…

Here's the gist of it (w/ commentary).

<?php
// ... your code
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// get current theme and it's variables
$current_theme = variable_get('theme_default','none');
$themes = list_themes();
$theme_object = $themes[$current_theme];

// uncomment to display structured information about $theme_object
// var_dump($theme_object);

// get current theme path
$theme_path = dirname($theme_object->filename);

    // get path of each stylesheet from current theme
  $final_stylesheets = array();
    if (!empty($theme_object->stylesheets)) {
    foreach ($theme_object->stylesheets as $media => $stylesheets) {
      foreach ($stylesheets as $name => $stylesheet) {
        $final_stylesheets[$media][$name] = $stylesheet;
      }
    }
  }
  foreach ($final_stylesheets as $media => $stylesheets) {
    foreach ($stylesheets as $stylesheet) {
            // will print relative path to the stylesheet
            // here you can wrap each stylesheet in <link type="text/css" ....> tags
            // and compose the output for hte head section of your script
            print $stylesheet;
    }
  }

    // Do same for scripts
  if (!empty($theme_object->scripts)) {
    foreach ($theme_object->scripts as $name => $script) {
      $final_scripts[$name] = $script;
    }
  }
  foreach ($final_scripts as $script) {
    print $script;
  }
?>

all you have left to do is to wrap each $stylesheet and $script in appropriate tags and insert that into the head.


Get a view field in the edit form I have a site that I have a form for users that they write down their personnal info's. I did a view, and then I made a field that has this view. Now what I want to do is to see this view field in the user's edit form. I can see all the fields that I want in the user's form but I cannot see the view field.

Alter the form using [hook_form_alter][1]

<?php print views_embed_view('<Your view id>', $display_id = '<display id>'); ?>

Make that display:none; from CSS.


How to automatically skip intermediate redirects? I've run into the issue where I end up with something like this:

about-us01 --> about-us02 --> about-us

The correct path is "about-us". But due to admins changing things I have ended up in a situation where there are sometimes old redirects lingering in the system. The problem is that these google says it's not good to redirect multiple times. So the above redirect is not very effective.

Is there a way that I can get Drupal 7 to automatically skip the 'middle' redirect if it knows that is only going to result in another redirect? So instead of:

about-us01 --> about-us02 --> about-us

I want:

about-us01 --> about-us
about-us02 --> about-us

In both cases of accessing the links, it must take you directly to the about-us page and not any inbetween links if it knows the true destination?

Use the Rules module with a custom  rule which looks like so (in Rules export format):

{ "rules_redirect_multiple_paths" : {
    "LABEL" : "Disallow multiple paths",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:path" ],
          "match" : "about-us\\d+",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Redirect to path about-us ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "about-us" } }
    ]
  }
}

Some details about how to use read this rule:

Rules Event: use the "Drupal is initializing" event, to ensure that the rule gets triggered BEFORE the actual content (of a path to be redirected) is shown. If you'd use an event like "content is viewed", you'd be too late, the content "would" already be shown.
Rules Condition: verify if the path to be redirected matches any of the paths you want to be redirected, such as about-us01 or about-us02 ( * ).
Rules Actions:

Show a message about the redirect, which is just for QA testing (feel free to remove that Rules Action after you saw it working).
Perform the actual redirect to the desired page.

( * ) Note that the actual Regular Expression I used goes a bit further: it would also perform a similar redirect for paths such as  about-us03 or  about-us456, though it would not trigger such redirect for (eg)  about-us/789. Here is an attempt to translate the various parts used in the regular expression about-us\\d+:

about-us: it must start with about-us.
\: escape character.
\d: it must be followed by a digit (anything from 0 to 9).
+: it may be followed by 1 or more of the preceding token (so one or more extra digits).

PS: If you're struggling with regular expressions, then have a look at RegExr.


How can I allow front end users to add their own custom fields? We have a new project that is going to allow users to add their own nodes of a content type e.g. 'cars'.

There are some existing fields that they need to complete e.g. 'colour' and 'year'. We also need to allow them to add their own custom fields, which only they can use. So one user will add 'mileage' whereas another might want to add 'number of seats'. How would I go about allowing hundreds of users to do this without bloating the content type?

We will be building it in Drupal 7.

Thanks for any help.

Use Field Collection module.

Install Field Collection module

Create a field collection field to a content type and set to unlimited.

Then create a fields with two text fields - "label" (for 'colour' and 'year') and "value" for that field collection

So when the node add form loads user will have two fields, Label and value with add more button there user can click and add another set of "label" and "value" pair.


Unlimited values field - how to hide extra field on node edit When creating a new node, I have this unlimited values field with the "Add new item" button.

That's OK, wonderful.
But when I edit an existing node, I get an UNDESIRED empty extra value added for me:

My real case is with a big compound field, but I thought using this small field as an example would be easier to understand.

I there any way to prevent this "extra" field from being intrusively added?

This would work for all node edit forms:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'field_YOURFIELD';

  if (empty($form[$field_name])) {
    return;
  }

  $field_language = $form[$field_name]['#language'];
  $max_delta = $form[$field_name][$field_language]['#max_delta'];
  unset($form[$field_name][$field_language][$max_delta]);
}


Multiple versions of the same menu, based on associated term? I am trying to create a site with different portals. Each portal displays content filtered to that person's user tag, i.e. Student, Staff, etc. It's easy to create a view that displays nodes with that user tag (taxonomy term), but I am looking to have a user tag-specific menu. Many items in my menu structure apply to multiple user tags, some to only one or the other. How can I have the portal page display a menu that only contains nodes with the appropriate tag?

I know that if I used actual Drupal roles I could give permissions to the pages, and then when someone is logged in with the appropriate role, they only see the pages that they have permission to see. This is the same idea, but I don't want to require users to log in. Only access the menu through a specific portal.

Hopefully I described that well enough, thanks for any suggestions!

I've done this just recently by implementing a single menu that shows different links depending on the context (in your case the context is a portal). The one menu will have all the links for all portals, and is set to rebuild itself on each context containing the relevant links for that context. You can do this as follows.

Implement hook_node_access_records() and hook_node_grants() to create viewing access records on the nodes that only allows for them to be viewed on the portal to which they belong.
Alter the canonical route for nodes to provide a custom access callback. This access callback will include a check on whether the user has viewing access to the node. This will ensure that nodes only show up in the menu when on the portal to which they belong.
Create a custom cache context for your portal, so that the menu can be set to vary by portal.
Set your menu block to have the portal cache context, so that the menu is rebuilt for each portal, showing the correct menu items for the given portal.

1) Implement node grants

Node grants involve two hooks, hook_node_access_records() and hook_node_grants().

First, hook_node_access_records(). This hook is called upon node save. In it you perform calculations to determine upon which portals the node will be accessible. For your setup, you will set a record for each portal the node can be accessed at. Example:

function hook_node_access_records(NodeInterface $node) {
  $grants = [];

  // A grant needs to be added for each portal on which the node should be accessible.
  $grants[] = [
    // This will always be the same.
    'realm' => 'portal',
    // This will be the identifier of the portal.
    'gid' => 'portal_1,
    'grant_view' => 1
    'grant_update' => 0,
    'grant_delete' => 0,
  ];

  return $grants;
}

How you get the GID (the portal ID) of the node will depend on how your system is set up. It sounds like your portals are set up using taxonomy terms. If that's the case, in hook_node_access_records() you can query that field to get the values from the taxonomy field and set your grants accordingly.

Next is hook_node_grants(). This hook is called anytime a node is accessed. This check will check if the user is on a portal, and add a grant for the current portal.

function hook_node_grants(AccountInterface $account, $op) {
  if ($op == 'view') {
    if ($portal = some_function_that_gets_the_current_portal_id()) {
      $grants = [];
      $grants['portal'] = $portal;
      return $grants;
    }
  }
}

This code will return a grant for the current portal. If the node being accessed also belongs to the current portal (by matching a grant set in hook_node_access_records()), viewing permission will be shown.

2) Alter canonical node paths with a custom access callback.

With the above two hooks implemented, viewing access permissions for the node have been taken care of. However, the route is still accessible, as access permissions on the route only check if the user has 'access content' permission, and doesn't include a check on whether user has permission to access the node the route displays. When building menus, route permissions are checked, not access permissions on the node. So the next permission is to override the route, and provide a custom access callback that also checks whether the user has viewing access on the node. This way, due to the node grants set in steps one and two, when the menu is rebuilt, it will only add items to the menu if the user is on the portal the items belong to.

To do this, first an event subscriber is created to alter the routes:

namespace Drupal\my_module\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setRequirement('_custom_access', 'Drupal\my_module\Access\PortalNode::access');
    }
  }

}

The above class will alter the entity.node.canonical route, giving it a custom access callback. The next thing to do is create Drupal\my_module\Access\PortalNode::access() and include the check on viewing permissions for the node. This class will look like:

namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PortalNode implements ContainerInjectionInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a PortalNode instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    AccountProxyInterface $currentUser
  ) {
    $this->currentUser = $currentUser;
  }

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

  /**
   * Custom access callback for node canonical routes.
   *
   * @param \Drupal\node\NodeInterface
   *   The node whose canonical route is being accessed.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   An access result that either provides or denies access.
   */
  public function access(NodeInterface $node) {
    // Allow access if the user has 'access content' permission (the default)
    // as well as viewing permission on the given node.
    return AccessResult::allowedIf(
      $this->currentUser->hasPermission('access content')
      &&
      $node->access('view')
    );
  }

}

Finally, the event subscriber needs to be registered in my_module.service.yml so it is picked up, and the route is altered:

services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

3) Add a custom cache context for portals.

As your menu will need to differ by portal, it must have a cache context set for portal. There may already be a cache context you can use that matches the Drupal functionality behind your portals. You can check existing cache contexts here: https://www.drupal.org/docs/8/api/cache-api/cache-contexts#core-contexts

If the cache context you need does not exist, you'll need to create a custom cache context. Here's an example: https://medium.com/@joshirohit100/cache-context-drupal-8-part-2-10088f67012e

4) Set the menu block to vary by the portal cache context

At this point everything is mostly set up, however, the first time the menu is built, that version of the menu will be shown the same on all portals, as it has not been set to vary by portal cache context. Your system needs to have the menu block vary by portal - ie. variations of the menu must exist for each portal, since each portal will have a different list of links in the menu.

To do this, you'll implement hook_block_alter() in order to add a custom cache context on the menu block. You'll need to get the ID of the menu from your system. Let's assume it's "portal-administration".

/**
 * Implements hook_block_alter().
 */
function my_module_block_alter(array &$definitions) {
  $definitions['system_menu_block:portal-administration']['class'] = 'Drupal\my_module\Plugin\Block\PortalAdministrationMenuBlock';
}

Finally, the class defined in hook_block_alter() is created. It's extends the system default menu class, and adds the portal cache context to the menu block:

namespace Drupal\my_module\Plugin\Block;

use Drupal\system\Plugin\Block\SystemMenuBlock;

class PortalAdministrationMenuBlock extends SystemMenuBlock {

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $cache_contexts = parent::getCacheContexts();
    $cache_contexts[] = 'portal';

    return $cache_contexts;
  }
}


Should the plain text filter convert line breaks into p and div elements? I have a plain text field in a content type. When I hit return between paragraphs the line breaks are there and show inside of firebug when I inspect the code. However, the body on the view page doesn't render any line breaks. I looked at the plain text input filter and the convert line breaks filter is checked. When I change to filtered html in the settings form of the body widget it works fine.

Do have to use the filtered HTML setting to get the line breaks converted?

The answer to your question is no, it should not.

But I always want it to and so do my users. For textareas that do not require "fancy" formatting, we have still always wanted line breaks to carry over into the display.

I use this in my theme's template.php to add them to plain_text textarea fields:

/**
 * Implements template_preprocess_field().
 */
function THEMENAME_preprocess_field(&$vars, $hook) {
  // Add line breaks to plain text textareas.
  if (
    // Make sure this is a text_long field type.
    $vars['element']['#field_type'] == 'text_long'
    // Check that the field's format is set to null, which equates to plain_text.
    && $vars['element']['#items'][0]['format'] == null
  ) {
    $vars['items'][0]['#markup'] = nl2br($vars['items'][0]['#markup']);
  }
}


Composer using old JSON for contrib module? I maintain skilling, a contrib module. This...

composer require drupal/skilling

... reports...

[RuntimeException]
  Could not load package drupal/skilling in https://packages.drupal.org/8: [UnexpectedValueException] Could not parse version constraint ~1.0@alpha2: Invalid version string "~1.0@alpha2"

[UnexpectedValueException]
  Could not parse version constraint ~1.0@alpha2: Invalid version string "~1.0@alpha2"

An older version of composer.json did use the string "~1.0@alpha2", but it was removed a while ago. Download the module's zip from D.O, and there is no such string in the file set once the zip file is expanded.

BTW, use the zip file, or Git the source files into contrib/modules, and Drupal installs everything just fine. It's just the composer install that's the problem.

I tried composer clearcache, but no dice. Using -vvv on 'composer require' didn't give me any info that I could interpret. Looking at composer's cache shows Strange Things. The file $skilling.json refers to the right release, but has '"drupal/token_custom":"~1.0@alpha2"' from long ago.

Help appreciated! The module can't be installed with Composer at the moment.

----- Update ARGH!! ----

@Clive is probably right, but I don't know how to fix it. Tried removing the line with the bad Composer version string in Git history with:

git filter-branch -f --tree-filter 'sed -i "/drupal\/token\_custom/d" composer.json' -- --all

Also tried BFG repo rewrite tool to replace the bad string.

Pushed. Created new releases. Cleared composer cache. composer require generates the same errors.

Afraid I don't understand Clive's suggestion to rebase a fix onto the branch containing the invalid version string. How is that done?

Im the maintainer of packages.drupal.org - I went ahead and deleted the invalid data out of the database, and this will install now.

I've also opened and issue on drupal.org to put more defensive measures in place. https://www.drupal.org/project/project_composer/issues/3076342

I think something must have changed in how permissive composer is with certain bad version constraints.


How to manipulate some fields using Views PHP? I'm trying to manipulate some fields on Views with Views PHP.

I have a (term) field for author(s). It can have one author or more.

Normally it looks like as that:

Book Title | Author

My First Book | Name1 Surname1, Name2 Middle2 Surname2

My Second Book | Name3 Surname3

etc.

What I want to do is to print names as that:

Book Title | Author

My First Book | Surname1, Name1 - Surname2, Name2 Middle2

My Second Book | Surname3, Name3

In order to do that, I used Global: PHP field with Content: Authors.

Value code inside Global: PHP is that:

$names = $row->field_authors;
foreach ($names as $name) {
  $parts = explode(' ', $name);
  if (count($parts) == 1) {
    $wanted = print($name);
    continue;
  }
  $last = array_pop($parts);
  $wanted = print ($last  . implode(' ', $parts));
}
return $wanted;

Output code is:

<?php print $value; ?>

But it doesn't return anything. I tried some other similar code but nothing changed.

Is it about the Content: Authors field (multiple field settings etc.) or am I wrong about the code I used in the Global: PHP field?

You'll want to put that code into a view template. Go into your admin, where you can edit that View, click on Advanced, and then Theme: Information. That will give you suggestions on the file naming conventions for the row style output for your view.

But as for your PHP code, Drupal uses a lot of nested multi-dimensional arrays, so it's not as simple as $row->field_authors being an array of strings of author names (unless you're doing some preprocessing). If field_authors is a term reference, you'll need to load the taxonomy term in order to get the actual author name.

This should get you the $names array:

$names = [];
foreach($row->field_field_authors as $author_tid){
   $term = taxonomy_term_load($author_tid[0]['tid']);
   $names[] = $term->name;
}
(... the rest of your code...)


Change default favicon programmatically I know I can load a favicon though the user interface, but is there a way of setting the default favicon for your theme, so that when someone enables the theme, the default icon is immediately used?

You can place the favicon.ico in your theme folder (at the same level as your_theme.info) and it will be used automatically.

Works for Drupal 6, 7 & 8.

Note: The favicon is heavily cached by some browsers, you may need to go to extra lengths to see the new one.


Meta Tags for viewers to not see Hi Im using D6 do I have to make the meta output so people can see the meta data if I select to not output the meta tags so viewerss will not read my meta data will this affect my search engine optimization (do the robots still read my meta or not?)

If your meta tags aren't in your page source, search engines (and any other robots) won't be able to read them.

You should never have anything sensitive in meta tags anyway so trying to hide them doesn't really make sense.


Test if template files (.tpl.php) are used by theme I've inherited a custom Drupal 7 theme with many template files. I'm sure lots of them aren't actually used by the website, and were part of the testing process.

Is there a method to list which .tpl.php files are being used in the website, or for a particular page?

Just print the theme hook suggestion variable in any preprocess function in template.php

print_r($variables['theme_hook_suggestions']);

If you use the Devel module then

dpm($variables['theme_hook_suggestions']);


translation_node_get_translations() bug? I have a multilingual site and I need to know which nodes are the translation of the current one; I use translation_node_get_translations(), but it seems it doesn't work.

I have 2 nodes (node/17 and node/670) where the latter is the translation of the former.

If I call translation_node_get_translations(17), I get an array with 2 elements referring to the nodes with ID equal to 17 and 670; if I call translation_node_get_translations(670), I get an empty array.

Is that a bug, or do I have to differently retry this information?

I found the solution: Calling translation_node_get_translations(), I have to provide the tnid (the node ID of the original node) as parameter, not nid, as nodes are translated by the node ID of the original node.

function _azzurra_get_translations_nids($node){
  $nodes = translation_node_get_translations($node->tnid);

  $nids = array();
  foreach($nodes as $value){
    $nids[] = $value->nid;
  }

  return $nids;
}

I wrote this function who return a list of all nids related to the argument node [included the nid of the argument node.. ]


How do I alter the page title h1 tag from a module? I miss hook_page_alter()!

I want to create a module that adds some configurable markup to page titles (the H1 tag on the HTML document) for full node pageviews of certain, configurable content types. But according to this change record:

  You no longer can change $page['content'] (or, generally speaking, $page[$region_name]) into something completely different.

I know I can override twig templates to achieve this, but can I do that without creating a theme? I'd like this to be a reusable module.

The page title is now a block, so you can override its template file.


How do I add a node ID as class to the  tag? In Drupal 7, there is a class like path-node-NID (with NID replaced by the node ID of the node being viewed) added to the <body> tag so we can easily add CSS styles to specific nodes. This is missing in Drupal 8.

How can I add the node ID as CSS class to the <body> tag?

In mytheme.theme file: add the below code.
function MYTHEME_preprocess_html(&$variables) {
  // Add node ID to the body class.
  $node = \Drupal::routeMatch()->getParameter('node');
  if (is_object($node)) {
    $variables['attributes']['class'][] = 'node-' . $node->id();
  }
}

This will add "node-{{nid}}" class in body tag.
Another Option
You can try Node Class module as well.

Node Class is a simple module that allows users to add custom CSS
classes to any node through the node/add interface.


Get arguments from a view I have a view object and I'd like to get the contextual filters that were passed to it.

I have this tidbit of code that prints out the arguments field name.

if (!empty($view->argument)) {
  foreach ($view->argument as $id => $arg) {
    print $arg->field;
  }
}

I'm trying to get the values of those fields.

$view->args[0] returns the first argument.


How do I programmatically place a block? From UI you can add a block in a region in that way:

Go to Admin -> Structure -> Block layout (/admin/structure/block).
Click on "Place block" button besides the region name.

I want to do the same thing but programmatically. How do I add an existing block to a region and save it? This block should then be displayed in that region and be  available in the Block layout page.

To provide a plugin block you can build an array of settings and pass it off to \Drupal\block\Entity\Block::create() to create the Block object and save the instance.

For example if you wanted to add a Devel Execute PHP block to the Seven theme:

$values = array(
  // A unique ID for the block instance.
  'id' => 'devel_execute_php_1',
  // The plugin block id as defined in the class.
  'plugin' => 'devel_execute_php',
  // The machine name of the theme region.
  'region' => 'content',
  'settings' => array(
    'label' => 'Execute PHP',
  ),
  // The machine name of the theme.
  'theme' => 'seven',
  'visibility' => array(),
  'weight' => 100,
);
$block = \Drupal\block\Entity\Block::create($values);
$block->save();


How to attach xdebug to drush in docker How can I "attach" xdebug to drush in a docker container?

By that I mean, how can I have xdebug show me a history of an import script? And to look at the single variables that are defined and occupied during the import script?

The whole thing runs on:
Docker version 2.1.05 (40693), Engine: 19.03.5, running on Mac 10.15.1.
Drupal version 8.7.9.
PhpStorm, Version 2019.3

My Config tempter, here the file docker-compose.yml:

version: "3.4"

services:
  mariadb:
    image: wodby/mariadb:$MARIADB_TAG
    container_name: "${PROJECT_NAME}_mariadb"
    stop_grace_period: 30s
    environment:
      MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
      MYSQL_DATABASE: $DB_NAME
      MYSQL_USER: $DB_USER
      MYSQL_PASSWORD: $DB_PASSWORD
    ports:
      - "4306:3306"
  mysql:
    image: wodby/mariadb:$MARIADB_TAG
    container_name: "${PROJECT_NAME}_mariadb_test"
    stop_grace_period: 30s
    environment:
      MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD
      MYSQL_DATABASE: $DB_NAME
      MYSQL_USER: $DB_USER
      MYSQL_PASSWORD: $DB_PASSWORD

  php:
    image: wodby/drupal-php:$PHP_TAG
    container_name: "${PROJECT_NAME}_php"
    environment:
      PHP_SENDMAIL_PATH: /usr/sbin/sendmail -t -i -S mailhog:1025
      DB_HOST: $DB_HOST
      DB_USER: $DB_USER
      DB_PASSWORD: $DB_PASSWORD
      DB_NAME: $DB_NAME
      DB_DRIVER: $DB_DRIVER
      PHP_FPM_USER: wodby
      PHP_FPM_GROUP: wodby
      COLUMNS: 80 # Set 80 columns for docker exec -it.

### From here the config of the Xdebug:
  PHP_XDEBUG: 1
      PHP_XDEBUG_DEFAULT_ENABLE: 1
      PHP_XDEBUG_REMOTE_AUTOSTART: 1
      PHP_XDEBUG_REMOTE_HOST: host.docker.internal # Docker 18.03+ Mac/Win
      PHP_IDE_CONFIG: serverName=Docker
      PHP_XDEBUG_REMOTE_CONNECT_BACK: 1
    volumes:
      - ./:/var/www/html

 nginx:
  image: wodby/nginx:$NGINX_TAG
  container_name: "${PROJECT_NAME}_nginx"
  depends_on:
    - php
  environment:
    NGINX_STATIC_OPEN_FILE_CACHE: "off"
    NGINX_ERROR_LOG_LEVEL: debug
    NGINX_BACKEND_HOST: php
    NGINX_SERVER_ROOT: /var/www/html/docroot
    NGINX_VHOST_PRESET: $NGINX_VHOST_PRESET
  volumes:
    - ./:/var/www/html
  labels:
    - 'traefik.backend=${PROJECT_NAME}_nginx'
    - 'traefik.port=80'
    - 'traefik.frontend.rule=Host:${PROJECT_BASE_URL}'

 selenium-firefox:
  container_name: "${PROJECT_NAME}_firefox"
  image: selenium/standalone-firefox-debug:2.53.1
  volumes:
    # - /dev/shm:/dev/shm
    - ./:/var/www/html
  ports:
    - "5905:5900"
    - "4444:4444"

 mailhog:
  image: mailhog/mailhog
  container_name: "${PROJECT_NAME}_mailhog"
  labels:
    - 'traefik.backend=${PROJECT_NAME}_mailhog'
    - 'traefik.port=8025'
    - 'traefik.frontend.rule=Host:mailhog.${PROJECT_BASE_URL}'

memcached:
  container_name: "${PROJECT_NAME}_memcached"
  image: wodby/memcached:$MEMCACHED_TAG
  command: "sh -c 'memcached -m 1024'"

portainer:
  image: portainer/portainer
  container_name: "${PROJECT_NAME}_portainer"
  command: --no-auth -H unix:///var/run/docker.sock
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock
  labels:
    - 'traefik.backend=${PROJECT_NAME}_portainer'
    - 'traefik.port=9000'
    - 'traefik.frontend.rule=Host:portainer.${PROJECT_BASE_URL}'

traefik:
  image: traefik:v1.7-alpine
  container_name: "${PROJECT_NAME}_traefik"
  command: -c /dev/null --web --docker --logLevel=INFO
  ports:
    - '80:80'
  volumes:
    - /var/run/docker.sock:/var/run/docker.sock

 php_test:
  container_name: "${PROJECT_NAME}_php_test"
  image: registry.my_projekt.de/drupal-test
  volumes:
    - ./:/var/www/html
  environment:
    CI_PROJECT_DIR : "/var/www/html/"
    DATABASE_PATH: "/root/database.sql"
    SELENIUM_PORT: "4444"
    BROWSER: "firefox"
    WEB_DRIVE: ""
    DISPLAY: ":99"
    UPDATE_ALIAS: "myProjekt:update"
    DB_HOST: 'mysql'
  labels:
    - 'traefik.port=80'
    - 'traefik.frontend.rule=Host:test.${PROJECT_BASE_URL}'

 php_quality:
  image: hussainweb/drupal-code-quality:latest
  command: tail -f /dev/null
  volumes:
    - ./:/var/www/html

It can happen if you are using drush launcher (https://github.com/drush-ops/drush-launcher). This tool allows you to type "drush" in your Drupal directory, instead of "./vendor/bin/drush", but it can confuse xdebug.
Using "./vendor/bin/drush" may fix the problem.

Additionally, you may also have to set an environment variable in your PHP container:

export PHP_IDE_CONFIG="serverName=my_server"

... where my_server is the name of the server in

Preferences / Languages & Frameworks / PHP / Servers

where your path mapping is set in PHP storm.

You may also wish to enable the option: "Break at first line in PHP scripts" and then run your drush commands - as often it can be tricky to set breakpoints in the correct place when running drush.


How do you change the default value on a CCK text field that is part of a field group via hook_form_alter()? I'm trying to programmatically set the default value (#default_value) on a textfield added via CCK. This field is in a field group. Here is my code:

/**
 * Implements hook_form_id_form_alter().
 */
function EXAMPLE_form_profile_node_form_alter(&$form, $form_state) {
  // We need to jump into a CCK field, so say we all.
  $form['#after_build'][] = 'EXAMPLE_form_profile_node_form_after_build';
}

function EXAMPLE_form_profile_node_form_after_build($form, &$form_state) {
  $form['group_company_profile']['field_pro_name']['#default_value'][0]['value'] = t('test');

  return $form;
}

I've tried various other points in the array and nothing seems to work. Both CCK and my module are weight 0. I must be missing something super obvious...?

UPDATE: One mistake was the field name. It should be field_pro_name. Updated above. It's still not working. Interestingly, I can use the after build to change the field title with:

$form['group_company_profile']['field_pro_name'][0]['value']['#title'] = 'ttt';

However, none of these changes the default value:

// In form alter:
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';

// In after build:
$form['group_company_profile']['field_pro_name'][0]['value']['#default_value'] = 'ttt';
$form['group_company_profile']['field_pro_name'][0]['#default_value']['value'] = 'ttt';

You should be able to do something like this:

function EXAMPLE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id=='profile_node_form') {
    $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';
  }

  // all other form alters here...

}

or

function EXAMPLE_form_profile_node_form_alter(&$form, &$form_state) {

  $form['group_company_profile']['field_pro_type'][0]['#default_value']['value'] = 'hello world';

}

directly from whichever form_alter() style you like.


Specific node is being attacked by spam comments. What do I do to prevent it? My site is being heavily attacked by spam bots and this is taking place only on one specific node. All other nodes are safe or the spam there is being blocked by Mollom. How do I prevent further spam comments from being posted over there? Do you have any idea?

If you don't care if nobody can comment on that node anymore, you could disable comments for that node. Go to the edit form and below "Comment settings" (assuming D6, slightly different in D7 but basically the same thing) change the value to "Read only" or "Disabled".


How to build links compatible with clean and "dirty" URLs? I have a development site that doesn't support clean URLs, my production site does support them.
If I build a link in the body of a node like:

View something

This shows ok on my production site but gives a 404 while in development site.
How do I build universally good URLs ?

You should be able to define such Links with the menu_hook

http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7

Especially lookt at the Wildcard options i used them recently to define own urls


How to get language specific path in twig? In a twig template you are able to get a relative path by using {{ path('entity.node.edit_form', {'node': nid }) }}. The path will be in current language.

Now I need to get the path in a specfic language. I thought I could use {{ path('entity.node.edit_form', {'node': nid }, {'language': langcode}) }} but this results an error if I set langcode to a string like DE. According to the api docs language has to be a language object. How can I accomplish this in twig?

For a twig only solution you can define a custom twig function path_lang(), which adds the language object to options, if a language code is  provided as additional parameter:

src/TwigExtension.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;

class TwigExtension extends \Twig_Extension {

  protected $languageManager;

  protected $urlGenerator;

  public function __construct(LanguageManagerInterface $language_manager, UrlGeneratorInterface $url_generator) {
    $this->languageManager = $language_manager;
    $this->urlGenerator = $url_generator;
  }

  public function getName() {
    return 'mymodule';
  }

  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('path_lang', [$this, 'getPathLang']),
    ];
  }

  public function getPathLang($name, $parameters = [], $options = [], $langcode = '') {
    if (!empty($langcode)) {
      if ($language = $this->languageManager->getLanguage($langcode)) {
        $options['language'] = $language;
      }
    }
    return $this->urlGenerator->generateFromRoute($name, $parameters, $options);
  }
}

mymodule.services.yml:

services:
  mymodule.twig.extension:
    arguments: ['@language_manager', '@url_generator']
    class: Drupal\mymodule\TwigExtension
    tags:
      - { name: twig.extension }

In twig:

{{  path_lang('entity.node.edit_form', {'node': nid }, {}, 'en') }}


How do I programmatically close a simple_dialog window I'm in D7

I open a simple dialog window with the simple dialog module, and i want to close the dialog programmatically.

I've tried this

// not working !
jQuery('#simple-dialog-container').dialog('close');

and this

jQuery(document).find('div.ui-dialog').remove();
jQuery(document).find('div.ui-widget-overlay').remove();
//This seems to work because the window disappears, but I can not open it again.

The X icon on the top-right do this proprely, but i can't catch the action

Thank you for help

try this code using jquery,

jQuery('#simple-dialog-container').trigger('click');

change id/class to anchor.


How fix an inverted execution order problem? When the order of calling the implementation of a particular hook by different modules matter, you can change the weight of modules by tweaking system database table.

But it looks like I'm in a more difficult situation involving interaction of the field_group, and the clientside_validation modules with my custom module.

I use hook_field_group_build_pre_render_alter() provided by the field_group module to add some '#states' attributes to a field group form element.

The states I add change the '#required' attribute, besides other things. This form relies on a clientside_validation module suite to provide a JavaScript validation.

There is a brand-new module, clientside_validation_states which perfectly fits me, but I ran into the difficulties trying to make use of it. clientside_validation_states uses #after_build, which should be called after my code, but hook_field_group_build_pre_render_alter() is called in field_group by using a '#pre_render' FAPI attribute.

This together results in an inverted calling order. Do you have any idea on how to fix this?

Posted this answer in the issue @attiks mentioned as well:

The easiest thing to do is to add the states in hook_form_alter() or in hook_form_FORM_ID_alter().

I got Clientside Validation to work on fields within a group, within a field collection.

Here's my code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function fgtest_form_article_node_form_alter(&$form, $form_state) {
  $group = 'group_customgroup';
  $collection_bundle = 'field_my_collection';
  $fields = array_keys($form[$collection_bundle]['und'][0]['#group_children'], $group);
  foreach (element_children($form[$collection_bundle]['und']) as $delta) {
    $collection = &$form[$collection_bundle]['und'][$delta];
    foreach ($fields as $field) {
      $collection[$field]['und'][0]['value']['#states'] = array(
        'required' => array(
          "#edit-field-my-collection-und-{$delta}-field-make-required-und" => array('checked' => TRUE),
        ),
      );
    }
  }
}

And here's my setup:

Node Article:

Field Collection field_my_collection:


Setting a date to be empty by default I have an event dates field that allows the user entering content to put in a start and and end date. By default it just shows them the start date. If they check a box it shows an end date and they can fill that out. So far so good.

However, I'm noticing that if they don't check the box and don't put in an end date it auto-sets the end date to be the same as the start date. This is not what I want. I want the result to be empty (mainly for Views so I can set it to not display if its empty).

Any idea how to fix this?

You can change this under the field settings for your date field.  If you edit your date field, you should see a "More Settings and Values" section:

You'll just have to set the default end date to "No default value"


Converting hard-coded menus to using the Menu module I have a site built in Drupal 7 with the navigation hard-coded in template.tpl.php. How do I go about switching this over to use the menu module instead?
I've already have the menu recreated in the site's main menu. How do I make my theme display the Drupal menu rather than my hard-coded one?
Is it correct to copy my current theme, create a new theme from that, swap out the hard-coded menu with some PHP code (where do I get that?), adjust the styles, and then activate the new theme?

One thing particular to my theme is I have menu drop-downs (secondary menus) that display when you mouseover the primary-level nav using JavaScript image swaps. I would have to recreate this menu in CSS.

You only need to create a new theme if the site in question is in production and you are not able to set up a development version of the site make your changes to the existing theme. In that case, you will want to create a copy of your theme with a different theme name and make sure to update the name of your MYTHEME.info file as well as any function names in your theme's template.php file.

Whether or not you do the above, the rest of the process should be the same either way.

Create a backup of the template file where the menu is hardcoded.
Create a block region where the menu currently is. There are two parts to this step: First you will need to add the following line to the MYTHEME.info file to let it know that the region exists:

regions[menu] = Menu

You'll want to make sure that there is not already a region with the same machine name. If there is, you may want to change it to something like:

regions[menu_top] = Top Menu

Next, you'll need to replace the hard-coded HTML for the menu with the code to display the region, something like:

<?php if ($menu): ?>
<?php print $menu ?>
<?php endif; ?>

Clear caches. This forces the theme registry to be rebuilt and your new region will be show up.
Add the menu block to the newly created region. Visit /admin/structure/blocks and find the block that is automatically created for the menu that you have recreated using Drupal's menu system and drag it into the "Menu" region that you just created.
Superfish. This is one of the better drop-down menu solutions, IMO. You'll want to follow the module instructions for getting it set up. This module creates additional blocks that you can assign your menu to. This will alter the previous step because you will add the superfish block and then assign the menu in the superfish block settings.
Profit!


show fields after adding joins in hook_views_query_alter I managed to programmatically add tables/joins in hook_views_query_alter() like this:

$td_join = new views_join();
$td_join->table = 'taxonomy_term_data';
$td_join->field = 'tid';
$td_join->left_table = 'audience_node_og_mvh_ti';
$td_join->left_field = 'tid';
$td_join->type = 'inner';

$query->add_relationship('audience_node_og_mvh_ti_td', $td_join, 'node', 'audience_node_og_mvh_ti');

When I go to edit the view and check the "auto preview" I can see that the generated query is correct:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, audience_node_og_mvh.title AS mvh_title, audience_node_og_mvh_ti_td.name AS field_data_field_cv_node_entity_type
FROM
{node} node
inner JOIN {field_data_group_audience} audience_node ON node.nid = audience_node.entity_id
inner JOIN {og} audience_node_og ON audience_node.group_audience_gid = audience_node_og.gid
inner JOIN {node} audience_node_og_mvh ON audience_node_og.etid = audience_node_og_mvh.nid
inner JOIN {taxonomy_index} audience_node_og_mvh_ti ON audience_node_og_mvh.nid = audience_node_og_mvh_ti.nid
LEFT JOIN {taxonomy_index} audience_node_og_mvh_ti_audience_node_og_mvh_ti ON audience_node_og_mvh_ti.nid = audience_node_og_mvh_ti_audience_node_og_mvh_ti.nid
inner JOIN {taxonomy_term_data} audience_node_og_mvh_ti_td ON audience_node_og_mvh_ti_audience_node_og_mvh_ti.tid = audience_node_og_mvh_ti_td.tid
WHERE (( (node.status = '1') )AND( (node.type IN  ('johndoe')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

But somehow I can't figure out how the new fields in the query (the ones from the joins) can be shown in the view itself.

Does anyone know how to do this?

If you want view to show your fields, you should not use a hook_views_query_alter. instead you should implement hook_views_data() to describe your audience_node_og_mvh_ti table to view and be able to use its columns as fields when building your views using the UI.

You can however access your view's query results in an hook_views_pre_render() implementations to add your additional field to the output.


How to change Zen Grid System Zen is a great theme and comes by 3 columns gris as default and even when i read the documentation i don't know how to change the grid system to 2 columns 30%- 70% for ex..
Can you help me please.

$zen-column-count: 10;

.container {
 @include zen-grid-container;
}
.column1 {
 @include zen-grid-item(3, 1);
}
.column2 {
 @include zen-grid-item(7, 4);
}

You include 10 columns, and use 3 for 30% and 7 for 70%. Reason being that columns are of equal width and if you want to implement two unequal columns you have to use multiples of a common denominator.


Change order status string from "Completed" to "Shipped" I'd like to change the order status string from "Completed" to "Shipped" to allow for better communication between us and the customer.

Commerce Custom Order Status would sidestep this problem by allowing me to create a new status, but that isn't the best way around it, because there might be triggers set for "completed".

The best thing for you to do would be to alter the order status info array to give the "Completed" status a new title. The example in the documentation actually demonstrates specifically how to change the title of the completed status. Look for hook_commerce_order_status_info_alter() in commerce_order.api.php.

There are ways to override strings through the user interface, but this is such a small module change that I'd really recommend directly making it in a site-specific module.


Views Bulk Operations execute php loop over reference values I am trying to finalize migration from d6 content profile to d7. I'd like to execute an arbirary php script using VBO to set a multi value entity reference field(users) based on the authors of a multi value node reference(bio content type) field.

I am looking for proper syntax for looping through each node reference item and populating the entity(user) reference with the uid from that node.

Final working solution:

$containing_node = node_load($entity->nid); //$nid is what node if you get from VBO
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
$references = field_get_items('node', $containing_node, 'field_res_mem');
   foreach($references as $index => $value) {
     $my_index = 0;
     $reference_nid = $value['nid'];
     $rnode = node_load($reference_nid);
    $ruid = $rnode->uid;
    $w_containing_node->field_res_memuser[] = $ruid;
  }
$w_containing_node->save();

For any field that has multiple values you can use field_get_items() to retrieve all values. For your specific case with the entity reference field, you'll need to retrieve the target_id property from each field item.

  $node = node_load($nid); //$nid is the node id you get from VBO
  $references = field_get_items('node', $node, 'field_MY_REFERENCE_FIELD');
  foreach($references as $index => $value) {
    $reference_nid = $value['target_id'];
    //@TODO: use $reference_nid to retrieve anything about referenced node
  }


Null value in DB displays content on page I have a blank category box on the bottom of the following page (http://www.suncorstainless.com/stainless-steel-hardware) and it appears that it's caused by a Null value in a table somewhere in my DB. I'm not the developer of this website and am having a hard time determining where this issue is in the DB.

Are there any tools available to determine the DB table that is displaying content on a page?

Thanks-in-Advance

Use the Devel module and enable it's database query log. See this question.


Is there any hook to multiple total price only in payment method Let think you want show 10000 USD in your site with 10 K$, I did it with hook_commerce_currency_info_alter and work correctly, ( I enter price in scale Thoundans, this mean when my product price is 20000, I enter 20 in price field ),everything in view is fine but my problem is in payment gateways, I want when user go to payment gateways multiple total price to 1000.

Is there any hook or clean to I achieve it in my module?

Or another way is achieve this job only in display, in all displays division to 1000 ( price /1000) and when go to payment gateway use origin price.

Personally I would rather use hook_commerce_price_field_formatter_prepare_view.

  This hook is used by modules like the Product Pricing module that implement ways to alter prices prior to display.

That way you could keep your prices as regular dollars internally, and only display them as kilodollars for your customers. Regular storage will make it easier to interact with gateways.

Other way, although I'm not sure about it's specific implementation, would be to define second currency. You can have a shop that sells in Euro and USD, and internally re-calculates prices to meet client's payment method, right? Maybe you could define kilodollars just he same way, with exchange ratio 1000:1 to regular dollars?


Ubercart: Attributes? I've got an existing cart and the inventory has separate products for different weights and they're separate entries. I want the varying weights to be combined and searched by attributes. What's the best way to do this with ubercart.

I'm using drupal 6 ubercart 2.

Ubercart 2.x has built in support for creating product classes with attributes. See the documentation for more information


force webform to reload or start from page1 with rules If for example a field 'start over' is selected, I would like to reload the webform from page 1.  Wondering the best way to do this.  I already have rules and webform validation enabled.  Do I create a custom rule?  Standard rules do not have a redirect url that I can see. Or is there a function to call to start over.

While adding rule action you can select System > page redirect

This is how you can choose:

Thanks!


Webform updates CCK field, doesn't update in node edit I have a CCK field used to track the number of volunteers needed for a specific position. Once someone signs up to volunteer for that position, the number needed is decreased by one.

The issue is that when I go to edit the original node, the # of volunteers needed is not updated with the new number from the database. I checked the database and I can see that the correct values are being written. They aren't being loaded into the node edit form.

It appears to be a caching issue since when I clear my cache the problem is corrected. Is there a way to fix this apart from turning off caching?

Thanks!

I figured this out: The CCK field was being rewritten by a cached value instead of a value directly from the database. I told the form to query the database directly, and then it began working correctly.


Make a custom date formatter for view Looking for a way to add my own date formatter in view. Actualy have the "default" and "Time ago" one, but I want to had another one to display date has FB do in the notification feed :

For today notification : Today, 09:33

For Yesterday notification : Yesterday, 10:36

For this week notification (except today and yesterday) : Mon. 06:34

All other notification : 09/12/17, 15:59

Is this possible ? Or maybe in an other way than add something in view module ?

Working on Drupal 8.2.0 version.

In Drupal 8, views field output uses the field formatters that entities use (Drupal 7 uses its own plugins for this).

The "Today", "Yesterday", "Monday", other functionality cannot be handled by the standard field formatters.

Drupal 8 makes it easy, though, to make new formatters.  Make a custom module, and extend DateTimeDefaultFormatter.  Inside this class, you would override the formatDate() method (and possible the defaultSettings() one, depending on how fancy you want to be.  The method would look something like this

protected function formatDate() {
  $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();

  if ($date is today) {
    $output = $this->t('Today, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is yesterday) {
    $output = $this->t('Yesterday, @formatted', [
      '@formatted' => $this->dateFormatter->format($date->getTimestamp(), 'custom', 'H:i', $timezone != '' ? $timezone : NULL);
    ]),
  }
  else if ($date is this week) {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'D. H:i', $timezone != '' ? $timezone : NULL);
  }
  else {
    $output = $this->dateFormatter->format($date->getTimestamp(), 'custom', 'm/d/y H:i', $timezone != '' ? $timezone : NULL);
  }

  return $output;
}

You need to work out the logic to choose the proper format.  Set the annotation on the formatter properly, and you can use this formatter in the view (or anywhere else).

This should give you a start.


returning #disabled in ajax callback This is taken from the examples module(http://drupal.org/project/examples). More specifically in the 'Generate textfields' ajax section. The form attempts to demonstrate an ajax call by presenting 2 checkboxes and generating a textfield based on which checkbox was clicked.

This is the ajax callback. We have a textfield with key 'first_name'.

function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#disabled'] = TRUE;
 return $a;
}

The form rendered has value textfield with value 'foobar' as expected, but the textfield is not disabled? How come?

You can accomplish that using ajax_command_invoke.

Here is an example using your own code:

function ajax_example_autotextfields_callback($form, $form_state) {
  // $a = $form['first_name'];
  // $a['first_name']['#value'] = 'foobar';
  // $a['first_name']['#disabled'] = TRUE;
  // return $a;

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      // First we add the disable attribute into the html input tag.
      // which makes the the input field inaccessible.
      ajax_command_invoke('#WRAPPER_SELECTOR input', 'attr', array('disabled','disabled')),
      // Then we grey it out by adding the form-disabled CSS class.
      ajax_command_invoke('#WRAPPER_SELECTOR .form-item', 'addClass', array('form-disabled')),
    ),
  );
}

You can instead grey out using CSS attributes by calling ajax_command_css