Repeat view entry for each value of multivalue field I am using commerce module in D7. Each order can have a single line item, but you can have whatever quantity you like in that line item. For each item of this quantity I store a text value that is held in a multivalue text field on the list-item itself.

So you have:

  Product 1  Quantity 1 Price $10  Information: Item1Text

  Product 2          Quantity 3     Price $10 Information: Item1Text, Item2Text, Item3Text

I would like to have a view for each order to display each item of the line item as a separate entry. So for example:

  Product 2           Price $10           Information: Item1Text

  Product 2           Price $10           Information: Item2Text

  Product 2           Price $10           Information: Item3Text

Is this at all possible, because I have tried all the tricks that I know, but cannot produce such a view.
The reason I need something like this is that I can have a separate invoice for each of the items included in the order, besides them being purchased together. So if you buy 3 balls, I would create 3 invoices each describing the purchase of a single ball.

Ok I finally figured out how to do this.

I order for the line item to repeat itself I unchecked the single line representation for multivalue field.

And in order to repeat the whole invoice I call a view from within another view.


Installing demo content via module.install file with Migrate module I'm trying to import content on installation of my feature, but it's not happening.  If I enable the migrate_ui module and go and manually execute the import, then it imports fine.

The code below is from my module.install file, which was originally taken from the restaurant_event feature of the Restaurant Distribution.

/**
 * Implements hook_enable().
 */
function parcel_event_demo_enable() {
  Migration::registerMigration('ParcelEventMigrateEvent');
}

/**
 * Implements hook_disable().
 */
function parcel_event_demo_disable() {
  Migration::deregisterMigration('ParcelEventMigrateEvent');
}

Ok, I now understand that registering a migration is only registering it, not importing it, you still have to process the import.  I now call the _panopoly_core_import_demo_content function which executes $migration->processImport();

<?php

/**
 * @file
 * Installation file for Parcel Event Demo
 */

/**
 * Implements hook_enable().
 */
function parcel_event_demo_enable() {
  Migration::registerMigration('ParcelEventMigrateEvent');
  _panopoly_core_import_demo_content(array('ParcelEventMigrateEvent'));
}

/**
 * Implements hook_disable().
 */
function parcel_event_demo_disable() {
  _panopoly_core_rollback_demo_content(array('ParcelEventMigrateEvent'));
  Migration::deregisterMigration('ParcelEventMigrateEvent');
}


Views - how to filter a result set based on a URL filter that affects an API call? I have a View with a Rest Export display returning entities. I have a custom Normalizer class for it that crafts the object the way I want it in the response.

The node entity in the response has some custom data attached to it coming from an API (think operating hours). I am being asked that if someone clicks on 'Open Now' in the filtering form (not yet created), then anything not open should not be shown in the list.

Is there some way I can add a custom filter or hook into Views and look for this URL parameter and exclude a result from the list if it is not open? hook_views_pre_render and hook_views_post_render don't seem to fire, I assume this is because I am using Serializer format.

So, I am not 100% confident in this approach, but I got a working solution. The base table is Node, I have no join, this data is not stored locally and I use an API call to fetch the operating hours. So I looked at how the Global filter options worked and started from there with hook_views_data:

In mymodule.module:

/**
 * Implements hook_views_data().
 */
function harlib_restful_normalizer_views_data() {
  $data = [];
  $data['libcal']['table']['group'] = t('LibCal');
  $data['libcal']['table']['join'] = [
    '#global' => [],
  ];

  $data['libcal']['open_now'] = [
    'title' => t('Open Now'),
    'filter' => [
      'id' => 'open_now',
      'title' => t('Currently Open'),
      'help' => t('Filter results by "currently_open" value on results from LibCal Hours API.'),
    ],
  ];

  return $data;
}

In my custom OpenNow filter class:

namespace Drupal\harlib_restful_normalizer\Plugin\views\filter;

use Drupal\harlib_libcal_api\Client\HoursTodayClient;
use Drupal\views\Plugin\views\filter\BooleanOperator;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filters nodes based on libcal currently open value.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("open_now")
 */
class OpenNow extends BooleanOperator {

  /**
   * @var \Drupal\harlib_libcal_api\Client\HoursTodayClient
   */
  protected $hoursClient;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, HoursTodayClient $client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->hoursClient = $client;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('harlib_libcal_api.hours_today_client')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function query() {}

  /**
   * {@inheritdoc}
   */
  public function postExecute(&$values) {
    if ($this->value) {
      foreach ($values as $key => $value) {
        $node = $value->_entity;
        $library_id = (int) $node->get('field_library_id')->value;

        if ($library_id === 0) {
          // No times associated with this library.
          unset($values[$key]);
          continue;
        }

        $hours = $this->hoursClient->request($library_id);

        if ($hours['currently_open'] == FALSE) {
          unset($values[$key]);
        }
      }

      $values = array_values($values);
    }

    parent::postExecute($values);
  }

}

If the filter is 'checked' or true, the postExecute method will loop the result set, check the hours returned and unset the result if the location is not currently open. I am not using pagination or anything, so, I did not test if it works in those conditions.

The better scenario is to filter the JSON list on the front end (since the data is already attached to the entity in the response), but I was asked to do it from the backend.


db_fetch_object returning null This is the line:

$row = db_fetch_object($result);

While $result is valid but $row is getting a null value which I've checked with is_null.

As per this function's @return value, it can only return FALSE in failure.

Also mysql_db_object states the same.

What could be the reason it is returning null?

Actually, db_fetch_object() could also return NULL, contrary to what the documentation says. The documentation assumes you aren't passing to the function a value that for PHP is equivalent to FALSE, for example NULL, an empty array, or an uninitialized variable. If the function gets a value that for PHP is equivalent to FALSE, the function will not execute any instruction, and it will return NULL.
function db_fetch_object($result) {
  if ($result) {
    return mysql_fetch_object($result);
  }
}

The same is true for other database engines, for example PostgreSQL, which uses the following function.
function db_fetch_object($result) {
  if ($result) {
    return pg_fetch_object($result);
  }
}

This is usually not a problem, since the function should normally be called as in the following snippets.
 if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
    $block['subject'] = check_plain($category->title);
    $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
    $read_more = theme('more_link', url('aggregator/categories/' . $category->cid), t("View this category's recent news."));
  }

  while ($item = db_fetch_object($result)) {
    $items[] = theme('aggregator_block_item', $item);
  }

In both the cases, the control statements will not be executed, since for them NULL is equivalent to FALSE.


Can I force users to join a group when registering? I would like everyone to be a member of "our Community" by default.
I want everyone to be a member of a site-wide group so that we can have a site-wide wiki, events & all the other usual group stuff.

Do I miss the point? Is this already the case, or do I not really want what I think that I want?

I am not sure, but if Organic Groups has rules integration; you might be able to create a Rule which automatically adds the user to the desired group.


Why is the expire header set to some time in the past ('Sun, 11 Mar 1984 12:00:00 GMT') in Drupal 6/ PressFlow and Drupal 7? I have been trying to understand why the expires header is set to the past. I read the comment  In boostrap.inc drupal 6  but I am still a bit confused about it and the relation between expires and vary headers. I looked into this because I am trying to set the expire header in the hope of controlling varnish object cache expiration regardless of TTL. The code reads:

  // HTTP/1.0 proxies do not support the Vary header, so prevent any caching
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  // 2616, section 14.9.3).
  $default_headers['Expires'] = 'Sun, 11 Mar 1984 12:00:00 GMT';

Would it affect me if I set the caching headers like expire? I want to do this only for anonymous users.

I posted a varnish question related to this here:
https://stackoverflow.com/questions/19121220/how-to-control-how-long-varnish-expire-a-page-from-the-backend

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3.

  If a response includes both an Expires header and a max-age directive,
  the max-age  directive overrides the Expires header, even if the
  Expires header is more restrictive.  This rule allows an origin server
  to provide, for a given response, a longer expiration  time to an
  HTTP/1.1 (or later) cache than to an HTTP/1.0 cache.

And if you look at the following code, you can see that the reason they do that is to prevent caching and allow you to do your own caching. This disables the internal page cache but returns headers allowing downstream caches (such as Squid, Varnish, and other reverse proxies) to cache full pages.

function drupal_page_cache_header_external() {
  // Get headers set in hook_boot(). Keys are lower-case.
  $hook_boot_headers = drupal_get_header();

  $max_age = variable_get('page_cache_max_age', 0);
  drupal_set_header('Cache-Control', 'public, max-age=' . $max_age);
  drupal_set_header('Last-Modified', gmdate(DATE_RFC1123, $_SERVER['REQUEST_TIME']));

  // HTTP/1.0 proxies do not support the Vary header, so prevent any caching
  // by sending an Expires date in the past. HTTP/1.1 clients ignores the
  // Expires header if a Cache-Control: max-age= directive is specified (see RFC
  // 2616, section 14.9.3).
  drupal_set_header('Expires', 'Sun, 11 Mar 1984 12:00:00 GMT');

  // Allow HTTP proxies to cache pages for anonymous users without a session
  // cookie. The Vary header is used to indicates the set of request-header
  // fields that fully determines whether a cache is permitted to use the
  // response to reply to a subsequent request for a given URL without
  // revalidation. If a Vary header has been set in hook_boot(), it is assumed
  // that the module knows how to cache the page.
  if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie', FALSE)) {
    drupal_set_header('Vary', 'Cookie');
  }
}


How to edit a field--field-xxx.tpl file when the content is rendered with Display Suite? I want to show up to 3 images in my teasers. For that I override the field--field-image.tpl file in my theme directory and it works perfectly.

<?php

if ($element['#view_mode'] == 'teaser') {
    $items = array(array_slice($items, 0,3));
    }

    print "
".render($items)."
";
?>

I would like to use a Display Suite layout instead for the teaser, but the field--field-image.tpl has no effect anymore. Where should I put this code to achieve the same effect (up to 3 thumbnails) using a Display Suite layout?

I am a little bit ashamed, but if the issue occurs to someone else, it is not even necessary to write code. There is a dedicated field in the manage display interface.


Where do extra parameters come from? Not a real issue but more of an informative question.

Concrete case:

system.routing.yml integrates system.entity_autocomplete that uses controller::method

\Drupal\system\Controller\EntityAutocompleteController::handleAutocomplete. First parameter in handleAutocomplete() is $request and the rest are the ones we could explect from url.

Where did $request come from?

This is a feature provided by Symfony:

  The Request object as a Controller Argument

  What if you need to read query parameters, grab a request header or get access to an uploaded file? All of that information is stored in Symfony's Request object. To get it in your controller, just add it as an argument and type-hint it with the Request class:

use Symfony\Component\HttpFoundation\Request;

public function indexAction(Request $request, $firstName, $lastName)
{
  $page = $request->query->get('page', 1);

  // ...
}


Is Drupal scalable across multiple geographical locations? I'm investigating how a Drupal site can be scaled across multiple geographical locations. The primary requirement for this is high availability. The site should be able to run despite some sort of outage on a single location.
The site is a "heavy read, low write" site, meaning that users will never create accounts and edit content. All content is edited by moderators only.
The following two options pop into my mind. I'd be interested in hearing if anyone else have experiences with similar setups - or just general feedback on how viable these options are.
1 WAN-wide cluster
A WAN-wide cluster could be achieved using a database cluster and a storage cluster. However, the immediate implications - as far as I see it - is latency. If we choose to go with a MariaDB/Galera cluster (which is synchronous replication), performance will be very dependent on network latency. For storage, something like GlusterFS (separate storage tier) could solve our needs. However, this again is latency dependent and I'm not so sure replication across an entire WAN is a good idea. The idea of a synchronous cluster (Galera/GlusterFS) is compelling as it removes a few timing issues (replication lag) which you need to take into account otherwise.
The other option for a WAN-wide cluster would be a "regular" master-slave database cluster, where we would have a single master database where all content editing is made. The master database will be located in one location, and the other geographical location(s) will have slave databases only. However, you can never guarantee that some Drupal node not will attempt to write to a database - so all Drupal nodes regardless of location will need to have the possibility to get in touch with the master database to execute write queries. This could be achieved using the AutoSlave module. However, this design makes the other geographical locations dependent on the single master node. If some sort of outage happens here, the master node will no longer be available and all other sites will possibly fail. This defeats the entire idea of high availability. With regards to storage, something simple like lsyncd/csync2 or BitTorrent sync could solve file replication. This would be asynchronous file replication, but I don't think that would be a problem as the site is "heavy read, low write". Only a couple of images a day gets uploaded. Cached JS/CSS and thumbnails would possible be excluded from synchronization, which would put a little more load on all frontends - but that would be a question of testing how much load that would be.
2 Content sharing between locations
I'm not sure how this one could be done, and I'm afraid complexity grows. However, separate - but identical - Drupal installations could be set up at multiple locations. All content editing could be made at one of the sites (master), which would publish content to the other sites. There would be no database or storage dependencies between the sites. However, I'm not sure if this is all that easy to to - especially when content gets complex with multiple fields, media types, images etc.

I'll address your two points one by one and then discuss suggestions. This is a massive question in scope so I'm doing the best I can with what we've been provided.

WAN-wide cluster

Galera would be your best option if you wish to do an Active/Active setup. It's a tricky setup though and only the best hosts have figured it out (platform.sh comes to mind). Your other option is, by far, the most common. i.e. Master-Slave replication. You may find support for that in the Drupal community is more prevalent and that is worth its weight in database queries. :)

Content sharing between locations

You have some options when it comes to this. If your editors are to be collocated into a single geographical space, then sharing content isn't a problem. If you have a need to allow editors access from many geographical locations, you can do this in a two primary ways:

Active/Active using a Galera cluster as you indicated.
Active/Passive sites using a content deployment model using the Deploy module, Migrate module, Feeds module, or some combination of those.

Suggestions

Start thinking in terms of a single site, not sites. Ultimately, you'll employ a CDN of some kind to deliver content across regions. You had mentioned a concern with freshness of content but there are many ways to achieve the balance. i.e. Look to the Drupal modules Purge, Cache Actions, and Rules.
Consider Edge Side Includes which will allow the static serving of some content on a page but assets served from the edge for others.
I can't stress the importance of dedicated Memcache servers enough.
CDNs, Varnish and a module such as Boost are not mutually exclusive concepts. They can all be employed to keep things fast on the anonymous side. Bear in mind, however, the more layers you add; the greater the possible complexity.

Hope this is helpful.


Can a group of fields be added to $form in buildForm()? I am defining a custom form to be added to the $build array of a specific node, using form elements as defined here.

Is it possible to add a field collection to the $form array, like '#type' => 'field_collection' or something similar?

It turns out fieldset is what I was looking for:

  Provides a render element for a group of form elements.


Grouping Content by Date in Views I'm trying to group content by date in views but instead of utilizing 'Fields' to stylize it, I'm trying to style using 'Content'

Here is an example of what I see right now:

Note Post Title

  This is a test comment 1
  John Doe
  Posted Date October 7, 2013 - 11:15 AM

  This is a test comment 2
  John Appleseed
  Posted Date October 7, 2013 - 11:20 AM

Here is what I'm trying to achieve:

October 7, 2013

   Note Post Title 1
     This is a test comment 1
     John Doe
     11:15 AM

     This is a test comment 2
     John Appleseed
     11:20 AM

For grouping the content by date field, you may try the following:

Add one extra date field in the fields section. (This field will be used for grouping)
In Format -> settings, select that date  field for grouping


Are all custom entities Content types? I'm getting mixed up in my terminology.  If I created an Entity named "Students," via .yml that has its own table.  Is that a Content type but a Custom Content Type?

You define an entity type in a class. Either a content or a config entity. Content entities can have bundles. These are defined in config entities (you need a separate class for this). Like all config entities bundles
can be exported and imported in yaml files.

An example for a content entity type is Node. The node bundle is called Content Type. Internally Drupal uses node_type as machine name, which makes it clear that this is only used for nodes.


Removing user points using rules module? I've made a rule to add userpoints by

Add user points rule

Events
1.A node has been flagged, under "MyFlag"

Actions

1.flagged-node:author
 2.Value 1
 3.Point Category General

How do you remove user points using rules?

Just make the value of the "Points" field a negative number.

Let's say you want to remove 100 points when the flag event occurs.

Make the value for Points equal to -100.

Hope that helps.


custom module page -- i need it to use a predefined panels page layout I've got this:

function foo_menu() {
    $items = array();
    $items['facadmin/directory'] = array(
        'title' => 'Faculty & Staff Directory',
        'page callback' => 'foo_facstaff_directory',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

Which then does this:

function foo_facstaff_directory() {
    $content = foo-make-html();
    $page = array();
    $page['#markup'] = $content;
    return $page;
}

I'd like this page to use a predefined panels template, but when I set 'facadmin/directory' as a selection rule, it doesn't do the smart thing automatically and just dumps the html into the content region -- no panels.

Help?!?

I made a custom block and put that into a standard layout instead.


How to set or change path to Drupal 8 contact form? Drupal 8 provides two default contact forms: "Personal contact form" and "Website feedback."

While "Personal contact form" is added to each user's profile by default, to "Website feedback" Drupal automatically provides a link to this form from the footer. The path of this link is "contact" by default.
How can I change the path to this contact form, where are those paths generally set and configured?

And by the way, is it possible to change the labels?

I also needed a page at /contact path. With a simple custom module you can change the default routing for the contact forms.

Let's assume custom module is called: example and the new default for the contact forms will be /contactform instead of /contact:

example.services.yml

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

src/Routing/RouteSubscriber.php

<?php
// Save this file as `src/Routing/RouteSubscriber.php` in your module directory.

namespace Drupal\example\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Change the core's default path for `/contact` so that we can use it as an alias.
    if ($route = $collection->get('contact.site_page')) {
      $route->setPath('/contactform');
    }
    if ($route = $collection->get('entity.contact_form.canonical')) {
      $route->setPath('/contactform/{contact_form}');
    }
  }
}


Do any comment modules play well with revisioning? I'm faced with a situation where we need to keep track of which node revision a comment was made for, so that we can display whether the comment was made for a newer/older revision, or for the one currently being looked at. Do any comment modules allow this in D7?

Use cases

Not the actual use case, but a decent, easy-to-follow approximation of the idea: imagine a bookstore, where users can post comments about books. Typically, when a user asks to see a book's page, he sees the page about the book's newest edition, but in some cases a page for an older edition of the book is presented. In the list of comments for the book, comments are annotated with whether they were made about a different edition than the one being currently looked at, since the comment might not be applicable for other editions.
The actual use case is: teacher A creates learning material LM.v1 and then revises it to LM.v2; teacher B starts using LM.v2 with her class; when A revises LM.v2 to LM.v3, we still need to allow B and her class to use LM.v2, because LM.v3 might not work for B's needs at all (and changing a learning material mid-project is a big no-no); so, when looking at LM.v2, we want to be able to see all comments made about it, but with an annotation if the comment was about LM.v1 or LM.v3, since these may or may not be applicable in the LM.v2 case.

I'm thinking out loud here... to simplify some aspects, I would probably try something like this first:

set up each 'revision' as it's own content
add a field that will follow each revision (ie. an internal product code that doesn't change even with revisions)
add a Views block to the bottom of the content page for that content type which includes a filter of ALL comments where those comments share the same internal product code but not from the current content - that way direct comments show normally, and then there's a view showing comments from the other revisions


Hiding nodes based on geographical location I am setting up a ecommerce site for a client using drupal and ubercart. They have a number of products on the site that are not available in certain countries. We have discussed solutions using subdomains, but ideally they want to be able to control whether or not a product visible in any giving country.

So my question. Is there a module that allows a person to block the visibility of a node based on the user's geographical location? Ideally, this would block everything including any views the node might appear in. Any ideas?

I'm going to assume that you wouldn't mind writing a custom module for this. Lets call it say, my_mod. The use-case you have mentioned is perfectly suited to take advantage of the Drupal Node Access system.

A few assumptions:

You have a vocabulary, Locations that houses a growing list of locations with which either a user or a piece of content on your site can be tagged with.
Attach a Taxonomy Term Reference field field_location with this vocabulary to both products and users.
Say for a given user, based on his access, you "guess" his location from his IP and set/append this field for him.

Then all you need to do is let Drupal know that users can only see products that have been tagged with the locations that they are a part of using the Node Access hooks as shown below.

/**
 * Access realm that defines access control to content by user location
 */
 define('USER_GEOGRAPHY_REALM', 'user_geography');
 /**
  * Taxonomy term reference field. Allows tagging a user/node with a
  * a given term from the "Locations" vocabulary.
  */
 define('LOCATION_FIELD', 'field_location');

/**
 * Implements hook_node_access_records().
 */
function my_mod_node_access_records($node) {
  $grants = array();
  $items = field_get_items('node', $node, LOCATION_FIELD);
  // In the USER_GEOGRAPHY_REALM access realm, we say that a user
  // who has the grant ID equivalent to the {taxonomy_term_data}.tid of
  // a term with which the node was tagged is allowed to see it.
  foreach ($items as $item) {
    $grants[] = array(
      'realm' => USER_GEOGRAPHY_REALM,
      'gid' => $item['tid'],
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0
    );
  }
  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function my_mod_node_grants($account, $op) {
  if ($op == 'view') {
    // Reload to make sure fields have been attached.
    $account = user_load($account->uid);
    $gids = array(USER_GEOGRAPHY_REALM => array());
    $items = field_get_items('user', $account, LOCATION_FIELD);
    // In the USER_GEOGRAPHY_REALM, a user's grants are the different
    // locations that he is a part of.
    foreach ($items as $item) {
      $gids[USER_GEOGRAPHY_REALM][] = $item['gid']
    }
    return $gids;
  }
}

You are free to extend the logic to include per-location limits for a user if you'd like.

You may have to remember to disallow the user from editing his own Location field and can use hook_field_access() for this purpose.


Which hook to use to detect new members added to group? What is the best way to make a hook that only fires when new members are added to a group?
I have a function that exports group memberships to moodle course enrolments. Right now I have it bound to _user_presave:
function mymodule_user_presave (User $user) {

  // Gather data.
  $userid = $user->id();
  $group_memberships = \Drupal::service('group.membership_loader')->loadByUser($user);
  foreach ($group_memberships as $group_membership) {
    $group = $group_membership->getGroup();
    $groupid = $group->id->value;
    $roles = $group_membership->getRoles();
    // Get roles.
    foreach ($roles as $rolename => $value) {

I bound it to user_presave after I realized that adding members to a group also calls this hook. But this seems unnecessarily inefficient, since it always returns all group memberships of the user, instead of just the latest one.
Is there a way to detect a new GroupMembership directly and hook into that?

this works:
function tm_mymodule_group_content_presave(Drupal\group\Entity\GroupContent $entity) {
  $group_content_type = $entity->getGroupContentType();
  if ($group_content_type->get('content_plugin') == 'group_membership') {
    $groupid = $entity->gid->getValue()[0]['target_id'];
    $userid = $entity->entity_id->getValue()[0]['target_id'];
    $group = \Drupal::entityTypeManager()->getStorage('group')->load($groupid);
    $user = \Drupal::entityTypeManager()->getStorage('user')->load($userid);
    $membership = $group->getMember($user);
    $roles = $membership->getRoles();

     // Do something
   }
}


How can I add alphanumeric, numeric and email validate validation in my custom form? function form_example_form($form, &$form_state) {

$form['empcode'] = array(
  '#weight' => '0',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Code'),
);
$form['empname'] = array(
  '#weight' => '1',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Name'),
);
$form['empemail'] = array(
  '#weight' => '2',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Employee Email'),
);
$form['empdesignation'] = array(
  '#weight' => '3',
  '#required' => '1',
  '#type' => 'textfield',
  '#title' => t('Employee Designation'),
);
$form['mobile'] = array(
  '#weight' => '4',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Mobile No.'),
);
$form['ipphone'] = array(
  '#weight' => '5',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('IP Phone'),
);
$form['qualifications'] = array(
  '#weight' => '6',
  '#required' => '0',
  '#type' => 'textfield',
  '#title' => t('Qualifications'),
);
$form['profile'] = array(
  '#weight' => '7',
  '#required' => '0',
  '#type' => 'textarea',
  '#title' => t('Profile'),
);
$form['file'] = array(
  '#weight' => '8',
  '#type' => 'file',
  '#size' => '30',
  '#title' => t('Employee Photo'),
);
$form['captcha'] = array(
  '#weight' => '9',
  '#type' => 'captcha',
  '#captcha_type' => 'captcha/Math',
);
 $form['submit'] = array(
     '#weight' => '10',
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

return $form;

}

function form_example_form_validate($form, &$form_state) {
  /*if (!($form_state['values']['price'] > 0)){
    form_set_error('price', t('Price must be a positive number.'));
  }*/
 // print('<pre>'.print_r($form_state['values'],1).'</pre>');
  //die();
 $file = file_save_upload('file', array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('png gif jpg jpeg'),
  ));
  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $form_state['values']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }
}

i want to add advance level validations so that no one enter special characters to these form fields. Currently required is working.

You can use Form API Validation module for this.

It has Available Validators like "alpha_numeric" which accept only Alpha Numeric characters and for more see below image.

Just install the module and enable it in admin and then

For alphanumeric use:

'#rules' => array('alpha_numeric'),

For numeric use:

'#rules' => array('numeric'),

For email use:

'#rules' => array('email'),


How to insert a link in a private message by code? I am sending a message to some users when a specific function is created. However, the content of the message that I send is always in plain text, meaning that it does not render links. What can I do?

This is the function that I use:

$message="A user has requested to join your group ".$group->title.". You can go to the group's page now to approve or decline their request.";

privatemsg_new_thread(array($user), 'New membership request for '.$group->title, $message);

I would this to work:

$message="A user has requested to join your group ".l($group->title,'group/'.$group->gid).". You can go to the group's page now to approve or decline their request.";

Any suggestions?

This is how I do it:

function _send_notifications($entity, $recipient) {
    $params = set_params($recipient, $entity);
    $sent = privatemsg_new_thread(array($recipient), $params['message_subject'], trim(token_replace($params['message_body'])));
}

function set_params($account, $entity) {
    if (isset($entity->nid) && $entity->type == 'entity_type') {
        $author = user_load($entity->uid); // Load the node author.
        $params = array(
            '!first_name' => $account->field_first_name[LANGUAGE_NONE][0]['value'],
            '!last_name' => $account->field_last_name[LANGUAGE_NONE][0]['value'],
            '!node_type' => drupal_ucfirst(str_replace('_', ' ', $entity->type)),
            '!node_title' => $entity->title,
            '!node_url' => url(drupal_get_path_alias('node/' . $entity->nid), array('absolute' => TRUE)),
        );
        $data['message_subject'] = t('New node type has been created');
        $data['message_body'] = t(
            "Dear !first_name !last_name,\na new !node_type has been posted with the title \"!node_title\".\n\nYou can view the post here:\n!node_url\n\n--  [site:name] team", $params
        );

    return $data;
}


Symlinked folder not recognized by file_exists? A module I'm working on maintains a list of files in the private file system folder in Drupal. I use hook_file_download to control access to these files.

I generate links to these files, which end up like: http://sample.com/system/files/my_folder/file.pdf

My website path is /var/www/sample.com/www and the private folder path is configured to be /var/www/sample.com/private.

Now, if the file is placed is /var/www/sample.com/private/my_folder/file.pdf, everything works fine and I can properly control access to the file and deliver it. However, if my_folder is located elsewhere and symlinked in, then things break. I've tracked part of it down to the PHP function file_exists returning false, which is called in file_download.

I'm not sure where to go from here. Everything I've searched for thusfar indicates that symlinks should work just fine. The permissions on the symlinked directory are OK - the directory is 755 and the files are 644.

What else could this be?

I've tried this on the latest PHP 5.3 and PHP 5.4 with no difference.

EDIT: It's worth mentioning that I can get file_exists to return true if I pass the absolute path to the symlinked file. Drupal is passing a stream wrapper though (private://my_folder/file.pdf). So looks like it could be related to the streamwrapper somehow?

I kept digging and found it was related to Drupal's stream wrapper implementation, specifically the getLocalPath method. There's already a large Drupal issue for this, which I wouldn't have found with my previous search terms.


Select options not loading when using callback function I am creating the select box form element as following

$form['select-user-group'] = array(
       '#type' => 'select',
       '#title' => t('Select a group'),
       '#options' => select_user_dropdown_options(),
       '#description' => t('Select a group to send the mail.'))

and am trying load the options for select box like follwing

function select_user_dropdown_options(){
    db_set_active('drupal');
    $result = db_query("select * from {content_type_usergroup}");
    $record = db_fetch_object($result);
    $str = '<select><option>-- Select a user group--</option>';
    while ($obj = db_fetch_object($result)) {
        $str .= '<option>'+$obj->field_p_group_name_value+'</option>';
     }
     $str .='</select>';
     return $str;
}

  But its not loading options to the select box , please help

Your select_user_dropdown_options() function needs to return an array of options, not a block of HTML. See the #options section of the Form API documentation -- you should find yourself re-reading that Form API page a lot.

Your array will be in the form

array(
  'group_1' => 'Group 1',
  'group_2' => 'Group 2',
);

A pedantic note -- I believe that's really a function call as opposed to a callback. That's fine; I mention it mostly because you don't include the parentheses when providing the names of callback functions.


is there a way to use preprocess_page only for certain page templates? I have a preprocess_page function in template.php that I need to use to pass a variable into a page (not node) template. The code works where I need it to, but it's also trying to run on EVERY page, which I don't want.

Is there a way to make a hook_preprocess_page() function run only on certain page templates, or a different function name (e.g. mytheme_preprocess_page_speaker())?

The preprocess function I am using is the following one.

function bluemasters_preprocess_page(&$vars) {

  if ($vars['node']->type == 'session') {
      $sess_type = field_get_items('node', $vars['node'], 'field_session_type');
      $sess_type_name = $sess_type[0]['taxonomy_term']->name;
      $vars['session_type_name'] = $sess_type_name;
  }

}

This works on nodes that are of the content type "session", but when I view other pages that use other content types, I get an error message telling me there's an undefined index of 0 on the line that's defining $sess_type_name. I need to make it so that the function ONLY runs on nodes of type session.

updated it appears the error is only occurring on a view with a page display that displays content type=session. So how can I avoid that?

I made a test using the following code, in my test site.

function code_testing_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    watchdog('code_testing', var_export($variables['node'], TRUE), array(), WATCHDOG_DEBUG);
  }
}

I then created a view showing the nodes of a specific content type (in my case, it was snippet). When I visited the view page, and checked the output from watchdog(), I have not found any information about $variables['node'].
Effectively, that is what I would expect, as $variables['node'] is set in template_preprocess_page() using the following code.

  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

Probably, if the view uses a URL like http://example.com/node/1, and there is a node with that node ID, $variables['node'] could be initialized. Differently, if the view is using a different URL, I would not expect $variables['node'] to be set.

To notice that views_preprocess_node() uses the following code.

  if (!empty($vars['node']->view) && !empty($vars['node']->view->name)) {
    $vars['view'] = $vars['node']->view;
    $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name;
    if (!empty($vars['node']->view->current_display)) {
      $vars['theme_hook_suggestions'][] = 'node__view__' . $vars['node']->view->name . '__' . $vars['node']->view->current_display;

      // If a node is being rendered in a view, and the view does not have a path,
      // prevent drupal from accidentally setting the $page variable:
      if ($vars['page'] && $vars['view_mode'] == 'full' && !$vars['view']->display_handler->has_path()) {
        $vars['page'] = FALSE;
      }
    }
  }

Probably the first control statement can be used in hook_preprocess_node() to check if a view is being served.


Redirect user on specified route I know we can easily redirect a path to another path with Redirect module, but what I want to do is more complicated,  my condition is when the user has a specified IP and the route is matched with to a specified path redirect it.

Pseudo code what I'm looking for is

if $path='xxxxx' and $user_ip = 'yyy.yyy.yyy.yyy' redirect to 'zzzzz'

how I can implement this, what I need is where is the best place to implement this?

You can alter the routes (conditionally based on IP) by creating an event subscriber or by using a RouteSubscriber.  You should also look at altering existing routes.


How can I create an excerpt for each of a node's taxonomy terms? Rather than create a single node excerpt/ preview used across all Views for a taxonomy term, how can I create individual excerpts for a selection of taxonomy terms used to describe a node?

For example, if I have a node about a hotel that is family-friendly and has business facilities (both of which are also taxonomy terms), when I display a list of 'family-friendly' nodes I would like to display an excerpt with a short description of the family-friendly features of that hotel, whilst when displaying a list of nodes for hotels with 'business facilities', I would like to display excerpts with short descriptions of the business facilities at those hotels.

I've found the Excerpt module, but this only appears to provide a minor modification to how Drupal's existing excerpt feature works.

This is an interesting feature. I have never seen a  module which does it.

If you look at the Open Calais module, you can see some custom extensions to the way taxonomy works. While it doesn't do what you want precisely it may be a  good guide for you.

In short, you can assign meta data to a node-term relationship which contains your excerpt. It would require a custom module and a fair amount of coding.


what is the hook to preprocess a view? What or is there a hook that you can utilize right before rendering results to the php template?

Also, is this means of altering view results bad practice? I'm trying to avoid using the views php field.

You can use something along the lines of this:

MYMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    foreach($view->result as $r => $result) {
      // do whatever you want with each "row"
    }

  }

  // other views might go here

}

and this is certainly NOT a bad practice at all, and, at least IMHO, far superior to php fields in the view itself.


How to put a date token at the start of Backup and Migrate file name pattems? Because Backup and Migrate sorts files by age, when you untar or copy some files to a destination, they will be more or less the same date and it may be hard to tell which ones are the latest etc. This makes it necessary to create a file pattern with the backup date at the start and make sorting by file name easier.

PS. Getting the date of the files restored from the archive correctly can be accomplished by some of the tar options.

On the Advanced Backup options page below the Backup filename there is a link Replacement patterns which expands to display another link Current date which displays some of the tokens available. None of the existing ones suits my preference which is a numeric date.

Using the PHP date options a good date prefix would be [current-date:custom:Ymd-Gi] or [current-date:custom:Y-m-d-Gi] the latter resulting in a string like '2013-11-17-1924' for 17th November 7:24 pm.

As an example I have a Backup filename token [current-date:custom:Ymd-Gi]_[site:name]-PMU, the PMU meaning Pre Module Update, something to use just before upgrading modules so you can revert the configuration if something goes wrong


Filter menu parent dropdown by language for multilingual site? I am working on a multilingual site that has about 60+ pages per language. When an admin user wants to add a page to the navigation menu its becoming quite the task because literally every single link (from all languages) is listed in Main Menu. Its even more confusing because the site has some cases where French and German are in the menu twice because the site has Canada-French and France-French as a language.

Is there any way to manage the navigation menu better? Like if I select German for the language could the menu dropdown automatically filter itself to just show the German nav items? Right now we have a list of about 300+ items in the dropdown :(

This seems to be the issue page for this problem: https://www.drupal.org/node/1242288. There are patches but as Jose Reyero points out, it would be only a partial solution.

There is a https://www.drupal.org/project/content_menu which enables you to first deal with the menu and then with the content instead of vice versa. Haven't tried but seems nice. This combined with Fixed language menus (provided by Menu Translation at admin/structure/menu/manage/menu-mymenu/edit, Multilingual options - Translation mode) could clean up the menu interface nicely.

Personally, I usually just don't bother dealing with the Parent item, I just head to the menu interface after creating a node, and drag my item, which will be at the bottom, to its place.


Need help with Drupal javascript behaviors I'm a bit lost with this and could do with some help from a Drupal JS veteran.

In my module I'm dynamically generating a settings form based on a CSS file, part of which provides a font select list with real-time updated preview text underneath. There can be any number of these font select lists + preview depending on the contents of the CSS file. The relevant (simplified) markup is something like:

  Font
  <select id="font-select-1" class="font-select" name="font-select-1">
    <option value="arial">Arial</option>
    <option value="verdana">Verdana</option>
    <option value="helvetica">Helvetica</option>
  </select>

Preview: The quick brown fox jumped etc ...

  Font
  <select id="font-select-2" class="font-select" name="font-select-2">
    <option value="arial">Arial</option>
    <option value="verdana">Verdana</option>
    <option value="helvetica">Helvetica</option>
  </select>

Preview: The quick brown fox jumped etc ...

In addition to styling (applying the correct font to) each font option I also want to change the class of #font-preview-x span to the selected option value from the relevant #font-select-x (i.e. "arial", "verdana" etc), thus showing a real-time preview of what the font will look like.

At present I have all this working OK using something like the following in my form array to change the preview text's class to the correct font class:

'#attributes' => array(
  'onchange' => "jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val());",
),

This mostly works onchange but not on page load, but on reading up further I gather there is probably a cleaner and better way i.e. using '#attached' to attach a Drupal behaviour, and I also shouldn't need to pass in the specific id. With jQuery I should be able to attach event handlers to each font select that update their respective preview text.

Any direction or advice would be much appreciated, as this aspect of Drupal is relatively new to me. Have read the docs and googled around but still am a little lost.

In drupal 7, If you need to add JavaScript or CSS to your page where a form may be rendered, there is already a rendered array variable available from the Form API for just that. drupal_add_js() will not always add the JS to the form as the hook does not always run when the form will be displayed, in certain scenarios like if the page is cached. You should use the #attached array on any form element, if you want to add JavaScript or CSS, because this array will rendered in all certain scenarios.

$form['#attached']['js']["jQuery('#font-preview-" . $i . " span').removeClass().addClass(jQuery('select[name=\"font-select-" . $i ."\"]').val())"] = array( 'type' => 'inline');

For More details you can visit: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached


Meta Tags on Frontpage It doesn't seem I can get my meta tags to appear on the page--front.tpl.php on a Drupal 7 site.

I feel like I have all the correct settings in the Meta tags module configuration, and I have cleared all caches. It works perfectly fine for all pages, just not the front page. This is driving me bonkers.

Any ideas?

Below are the steps without touching the files and using the drupal admin interface.

Go to admin/config/search/metatags/config/global:frontpage/edit
Add the Page title, Description etc and Save
Refresh the front page and check. Done !!


How do I override the default page.tpl.php? I have one page in my D7 website with significant deviation from the rest of my pages. In this page I will only display a limited number of regions and in a different layout.

What is the best way to override the default page.tpl.php? Can I create something like "mycustom-page.tpl.php" that gets called ONLY on a specific url within my site?

Depending for what exact content you want to make a special template there are diffrent solutions for that. Look at Drupal 7 Template Suggestions. Example for a single node: page--node--1.tpl.php.

In case the core template suggestions do not offer the flexibility you need, you can add more suggestions based on your own criteria. This is done in a preprocess function in your theme's template.php. For more information, see Working with template suggestions.


CSS in IE doesnt load CSS styles don't load in Internet Explorer (checked on version 9 and 7). They work locally, but not on the remote server. Do you have any idea?

Edit: It seems that compressing CSS inside "configuration >> performance" causes this problem. Is there a way to turn this feature for all browsers except IE?

Does turning on CSS aggregation make your CSS work in IE?

If so, you may be coming up against the 31 CSS file limit in Internet Explorer.

Someone has made a module that deals with this - IE Unlimited CSS Loader.


Is there a "best practice" for overriding a contributed module's controller in Drupal 8? I'm still relatively new to Drupal 8 and recently I came across an occasion to override the WebFormSubmissionListBuilder Controller.

I eventually found another project which had exactly the same need and they did it as below:

<?php
/**
 * Implements hook_entity_type_alter().
 *
 * @todo This alters all webform_submission entites but should alter only the ones in configured workflows.
 */
function academic_applications_entity_type_alter(array &$entity_types) {
  /* @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['webform_submission']->setListBuilderClass('Drupal\academic_applications\WebFormSubmissionListBuilderOverride');
}

While this works I can see it being a real problem if more than one module tried to override another module's controller this way. However, I couldn't find a better way so I ended up using their method for now.

Is there a known or "best practices" for doing this? I don't see any obvious plugin points in the WebFormSubmissionListBuilder controller's code so taking it over seems to be the only way to extend it as far as I can tell.

To avoid conflicts with other modules you could alter the controller content in a kernel VIEW event similar to a form alter hook:

src/EventSubscriber/ControllerAlterSubscriber.php:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class ControllerAlterSubscriber.
 */
class ControllerAlterSubscriber implements EventSubscriberInterface {

  /**
   * Alters the controller output.
   */
  public function onView(GetResponseForControllerResultEvent $event) {
    $request = $event->getRequest();
    $route = $request->attributes->get('_route');

    if ($route == 'entity.webform_submission.collection') {
      $build = $event->getControllerResult();
      if (is_array($build)) {
        // alter controller build array
        $build['added_content'] = ['#markup' => '
Added by ControllerAlterSubscriber.
'];

        $event->setControllerResult($build);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    // priority > 0 so that it runs before the controller output
    // is rendered by \Drupal\Core\EventSubscriber\MainContentViewSubscriber
    $events[KernelEvents::VIEW][] = ['onView', 50];
    return $events;
  }

}

mymodule.services.yml:

services:
  mymodule.controller_alter:
    class: Drupal\mymodule\EventSubscriber\ControllerAlterSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }


How to activate empty user profile? I am struggling with this for a while. In my setup, every user gets to have the main profile. However if there are all fields empty, the profile is not created.
Problem: It is not possible to access fields in user profile, for example using rules or php. Rules gives error - The variable or parameter is empty.

After editing any of profile fields, the profile is created and available for extracting data.
So is this any sort of bug or is it somehow possible to save/enable even empty profile, to be able to work with fields?

Thank you

A quick fix is to use a bit of custom code to save the profile fields in the time of user creation as empty. Say you have a profile of type of "main". This have to be done while creating the users, find the appropriate hooks here.

Now just create the user's profile with empty values.

// create profile object
  $profile = profile_create(array('user' => $account, 'type' => 'main'));
  // populate profile fields
  $profile->field_firstname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_lastname[LANGUAGE_NONE][0]['value'] = '';
  $profile->field_gender[LANGUAGE_NONE][0]['value'] = '';
  // save profile
  profile2_save($profile);

Ref: here and here

This may solve your problem. if now then let me know.


How to create modal windows (pop-ups)? I am trying to use Drupal 8's core function to open a page in a modal window. Unfortunately it is very hard to find some official documentation about it, and most of the blogs covering this topic seem to be outdated. But as far as I know, it should be possible to create a modal dialog by adding the following attributes to an a-element:

class="use-ajax” data-dialog-type="modal"

So that a full example would look like:

Where in my case /impressum/lizenzen/43 is a path to a views page.

This seems to work, but only when I am logged in as admin. As this does not seem to be an permission problem, I assume it is related to the admin theme (Seven), that might include some core libraries that Bootstrap (the which I use for my site) might not.
But oddly enough, in the title bar of the modal appeared, instead of the page title, the string ´Array´, what makes me assume, that an unexpected array to string conversation took place:

Could somebody

lead me to the official documentation of cores modal API,
explain to me, what could be the reason that it works as admin only.
And finally tell me, why on earth an array to string conversation takes place calling a modal?

This the official documentation for the API change you've mentioned:

Modal/dialog/ajax is using query parameters instead of accept headers

The most important detail is to attach this library:

$build['#attached']['library'][] = 'core/drupal.dialog.ajax';

You ask about why this works on admin pages without this. The reason is, admin pages already have dependencies on most Drupal jQuery libraries, while non admin pages are loaded without any jQuery out of the box (which is a great performance improvement in D8).

Bootstrap Theme

If enabled in the theme settings of the Bootstrap theme, "jQuery Modal" is replaced by
"Bootstrap Modal", see this code snippet:

LibraryInfo::alter()

elseif ($extension === 'core') {
  // Replace core dialog/jQuery UI implementations with Bootstrap Modals.
  if ($this->theme->getSetting('modal_enabled')) {
    $libraries['drupal.dialog']['override'] = 'bootstrap/drupal.dialog';
    $libraries['drupal.dialog.ajax']['override'] = 'bootstrap/drupal.dialog.ajax';
  }

For this to work you attach the same core library as above, so that the Bootstrap theme can find these core libraries to override them.


How do I set a dynamic variable in the menu links yml file for route_parameters? I'd like to create a menu item that has a dynamic variable in it, specifically the user's id.

In my example.routing.yml I have this:

example.test:
  path: '/user/{user}/example'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::test'
    _title: 'Test'
  requirements:
    _permission: 'access content'
    user: ^[0-9]+

In my example.links.menu.yml, I have:

example.testlink:
  title: Test Link
  parent: example.parent
  description: 'Test Link'
  route_name: example.test
  weight: 3
  route_parameters: {user: 5}

That "5" is my user id, I'd like to have it pull dynamically from my logged in user.  Is that possible?

Create a second route that has no user parameter and when accessed redirects to the first route with the current user parameter inserted.


Modify Commerce Product before saving How do I modify a commerce product before saving or alter the validation?

Specific use case: SKU field of commerce product is required but I want users to be able to leave this blank and have a SKU field auto generated and filled into the field automatically before saving the product.

If you want to alter the validation you can use hook_form_alter to add/alter the validation handlers used for the form.

To change the product you can use one of the entity hooks: hook_entity_insert is probably the one you want to use, but there also is one for update, presave and delete, and they also exist in a variant specific for commerce products: hook_commerce_product_insert


How to create sub menu in Drupal 8 using views result for specific item of the menu? I have one menu link available in the Main Menu. It is called as "Video".

In my system, there is vocabulary called as "Video Taxonomies". It have following taxonomies entries.

Entertainment
Comedy
Friction

I have created one block for listing all this category.

Now, I want this block result would appear under "Video" link of the Main Menu.

So, I want following output when we will hover on the Video Link of the Main menu.

Video Link

Entertainment
Comedy
Friction

I have used https://www.drupal.org/project/menu_views for Drupal 7.

Please suggest.

We have implemented using the

MODULE_NAME_menu_links_discovered_alter(&$links).

In which, We have accessed the result of the block by using the following code.

 $result = views_get_view_result("view_name", "display_id");
    foreach($result as $result) {
      $title = "Entertainment"; // we have took as static
      $tid = 10;
      $slug = str_replace(' ', '_', strtolower($title));
      $links[$slug] = array(
        'title' => $title,
        'route_name' => 'view.VIEW_NAME.DISPLAY_ID'
        'route_parameters' => array('arg_0' => $tid),
        'description' => 'Dynamic',
        'provider' => 'MODULE_NAME',
        'parent' => 'menu_link_content:DATABASE_UUID_OF_SELECTED_CATEGORY',
        'id' => $slug
      );
    }

We have used route_name for assigning the url, this url should be the existing url of the drupal site.

We need route_parameters for passing the arguments.

For accessing the Video Link : reference in parent of $links. I have got it from the

SELECT uuid as DATABASE_UUID_OF_SELECTED_CATEGORY FROM `menu_link_content` where id = "TID_Video_Link_of_Main_menu"

After that, We have used that id in parent as 'menu_link_content:04c479c9-7234-4de2-a4f0-e03b0a3003b6' so all links will be added below the Video Link of the main menu.

After doing all the code and we need to clear the cache. And we are able to see the sub menu from the views of texonomy to Video Link of the main menu.

Please suggest me if there is any better way than this.

For Reference: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Menu!menu.api.php/function/hook_menu_links_discovered_alter/8.2.x


Using #states in a form with checkboxes I would like when a client check one of the checkboxes, a text field appeares. Example: if he clicks on 3 checkboxes, all the textfields of the 3 show off.
My #checkboxes :

$form['input']['livraison'] = [
      '#title' => t('Options de livraison (à la charge de l’acheteur)'),
      '#type' => 'checkboxes',
      '#description' => t(''),
      '#options' => [
        'home' => $this->t('Retrait chez moi (gratuit)'),
        'hand' => $this->t('Remise en main propre (gratuit)'),
        'myself' => $this->t('Je livre moi-même le produit'),
        'colissimo' => $this->t('Colissimo'),
        'custom' => $this->t('Livraison personnalisée'),
      ],
      '#attributes' => [
        //define static name and id so we can easier select it
        'id' => 'select-shipping',
        'name' => 'field_select_shipping',
      ],
    ];

and my textfield :

$form['input']['adresse_home'] = [
      '#type' => 'textfield',
      '#title' => 'Adresse',
      '#required' => false,
      '#states' => [
        //show this textfield only if the radio 'other' is selected above
        'visible' => [
          ':input[name^="field_select_shipping"]' => [['checked' => 'false'], ['value' => 'home']],
          ':input[name^="field_select_shipping"]' => [['checked' => 'false'], ['value' => 'hand']],
          ':input[name^="field_select_shipping"]' => [['checked' => 'false'], ['value' => 'myself']],
          ':input[name^="field_select_shipping"]' => [['checked' => 'false'], ['value' => 'colissimo']],
          ':input[name^="field_select_shipping"]' => [['checked' => 'true'], ['value' => 'custom']],
],
      ],
    ];

**Solution : **

As berramou sent, this way is the one that works the best with checkboxes.  If you have any issues with it look if a plugin couldn't block states, that what happened to me with iCheck.
If you need to show all the input's checked, just put the TRUE condition in your 'visible', this way you can select 2 options and get both display correctly.

To use state for checkboxes element, you should target the specific element by JQuery selector, all elements they have the name="field_select_shipping" with value attribute different so try to target the input with both attributes try with the following to show adresse_home only if home and colissimo checkbox checked:

$form['input']['adresse_home'] = [
      '#type'     => 'textfield',
      '#title'    => 'Adresse',
      '#required' => FALSE,
      '#states'   => [
        'visible' => [
         ':input[name="field_select_shipping"][value="home"]' => ['checked'   => TRUE],
         // This like AND so the input show if home and colissimo checked
        ':input[name="field_select_shipping"][value="colissimo"]' => ['checked'   => TRUE],
        ],
      ]
    ];


Does node_save create all fields associated with a custom content type automatically? I have a custom content type and want to create new nodes in code.  The content type contains fields, some will be set with values and others left empty.  Is it necessary to define all the fields using $node->field_custom_name[$node->language][0]['value'] = 'field value'; or just the ones with values to complete the node definition?

You can happily omit the empty ones, there's no problem. When consulting the newly created node, node_load() will retrieve all the attached field and build the correct object.


How can I see what variables are available on the loaded page via the devel PHP Execute block? How can I see what variables are available to me on the page i am viewing via the PHP Execute block? I'm trying to do a dsm($node) but that doesnt seem to work. Neither does dsm($page).

Drupal loads all variables into $variables.

So in the PHP block just load: <?php dsm($variables); ?>.

For dsm to work you need the Devel module installed.


How do I increase the number of characters accepted by MySQL? This is how I've defined the content_body in my FieldWidget:

$widget['content_body'] = array(
  '#title' => $this->t('Body text'),
  '#type' => 'textarea',
  '#default_value' => isset($items[$delta]) ? $items[$delta]->content_body : '',
);

which allows me to enter more than 255 characters when editing/creating the content. However, I get an error when more than 255 characters are entered and the content is created/updated.

This is the schema in my FieldType class:

$schema['columns']['content_body'] = array(
  'type' => 'text',
  'size' => 'tiny',
  'not null' => FALSE,
);

Use field type as  Text (formatted, long) or Text (formatted, long, with summary)


Display the username in a custom block I'm using D7 and I have a custom content type (Client) and I have a custom select list field for the User entity displayed in a custom block.

I have a custom display layout for the Client content type, wherein all fields are displayed in different blocks using Display Suite. The user's name is displayed only when the user field is enabled in the node main content, else it remains blank.

How do I display the username in the block without the need to keep the field enabled in another part of the node view?

try with arguments or use views module and configure your block view CONTEXTUAL FILTERS


How can I trigger custom code when some other module is being installed/uninstalled? I am using a third-party module. Whenever it is installed or un-installed, I want to programmatically create/delete some menus.

How can I detect that a module is installed or un-installed?

You can use hook_modules_installed() to react to modules being installed, e.g.

function hook_modules_installed($modules) {
  if (in_array('lousy_module', $modules)) {
    variable_set('lousy_module_conflicting_variable', FALSE);
  }
}

and hook_modules_uninstalled() to react to the opposite, e.g.

function hook_modules_uninstalled($modules) {
  foreach ($modules as $module) {
    db_delete('mymodule_table')
      ->condition('module', $module)
      ->execute();
  }
  mymodule_cache_rebuild();
}


Why is the output from getDefinition($type) different from getStorage($type)->getEntityType()? In a Controller, when calling: $this->entityTypeManager()->getStorage($type)->getEntityType(), I do not have the exact same return value as: $this->entityTypeManager()->getDefinition($type).
They both return the same class (in my tests, it was ContentEntityType), but the only difference is in the entity_keys definition. Here is a diff of var export highlighting the diff between the two calls:
--- a/fromStorage.txt
+++ b/fromStorage.txt
@@ -19,6 +19,7 @@ Drupal\Core\Entity\ContentEntityType::__set_state(array(
     'uuid' => 'uuid',
     'langcode' => 'langcode',
     'published' => 'status',
+    'test' => 'entity_key_value',
     'revision' => '',
     'bundle' => '',
     'default_langcode' => 'default_langcode',

The test entity key was added after the module was installed (a custom entity). Only the $this->entityTypeManager()->getDefinition($type) call returns this entity key. The remaining of the entity definition is 100% the same.
At first, I thought that an entity update was needed, but the entity update manager detects no update to apply. Clearing the caches did not help either. Why the inconsistency? Am I missing an update call somewhere?

After digging into the internals of the entity type / storage management, I am fairly confident that I have found the answer: $this->entityTypeManager()->getStorage($type)->getEntityType() uses the result of EntityManager::getActiveDefinition which loads a sort of cached representation of the entity type. This was introduced by https://www.drupal.org/project/drupal/issues/2554235 which added the concept of last installed definition, which is meant to mitigate problems during update processes.
The difference between codebase and database means that the entity may need an update, like the following:
$codefieldstoragedef = $this->entityTypeManager->getDefinition($this->entityType->id());
\Drupal::entityDefinitionUpdateManager()->updateEntityType($codefieldstoragedef);

As $this->entityTypeManager->getDefinition() returns the codebase representation, this will tell Drupal to update the database representation with it. After doing this (preferably in a hook update), the entity keys will match.

This answer is also meant to fix some entity definition mismatch as shown in the status report page, especially regarding base fields to update which are used as entity keys.


Drupal multilingual monthly archive using views I have multilingual website in Drupal 7 and I am trying to implement news and monthly archive by using views. I am facing some problems with the monthly archive (I am cloning the default Archive).

For each language I have created news pages - f.ex. www.mywebsite.com/news (in English) and www.mywebsite.com/da/nyheder (in Danish). I also have created different views ("news", "monthly archive") for each language. The switch between the news including the views "news" works fine. But the switch between the monthly archives does not work in the way that I would like to. For example when I am on the page www.mywebsite.com/news/201301 and switch to Danish I am going to the page www.mywebsite.com/da/news/201301 but I would like to go www.mywebsite.com/da/nyheder/201301.

In every view I am specifying the language (content language and field language) to English or Danish. Any idea how I can solve the path problem?

I have also tried to use one view for news and one view for monthly archive (using current user's language) but then the problem is the title page. I can not translate the title for the different languages (accessibility issue).

Can somebody explane which is the right way for implementation of news monthly archive for multilingual website please.

Does the following similar question - How can I have a multilingual URL for a views result page depending on the language? help? It suggests the use of path translations and translations sets (part of i18n which I assume you already have installed and configured)?


hook_image_effect_info_alter() doesn't change effect callback I'm trying to patch the image effect from the Kraken module.
I'm doing so by using hook_image_effect_info_alter() to point the 'effect callback' to my patched function, like this:

function patch_image_effect_info_alter(&$effects) {
  $effects['kraken_optimize']['effect callback'] = 'patch_kraken_optimize';
  watchdog('patch_kraken', print_r($effects, TRUE)); // logging for debug
}

The problem is that this the hook doesn't seem to really change the effect defined on the Kraken module. Even though I'm getting the log message I defined in the hook with the updated effect callback, the original Kraken module effect is still being applied.

Am I using this hook the right way?

I found the issue.

It turns out there was another custom module "restoring" the original callback.


Enabling aggregate and compress CSS files resuls in vanishing theme I used this module for more compression on css and js files but it does not work for me! so I disable and remove it entirely.
After that when I enable aggregation of css and js files, my site's theme will disappear! even my administration theme! what should I do now?

Do following steps:

Again place advagg module's folder in your module's directory. Usually (sites/all/modules)
Go to database and truncate all cache tables starting with "cache". Do with caution.
See if site works.
Otherwise if you are having drush installed, check command "drush status" if it works. And clear the cache throudh drush again by command "drush cc all".

Hope this will help you. If not reply in comment I'll assist you to make your site work again.


Extending form validation functions How do I pass additional values to #element_validate so they can be used for validation?

I'm using hook_form_alter() and Drupal 7.

//Example 1
function my_validation_function($form, &$form_state) {
    //Validation Code
}

I would like to use:

//Example 2
function my_validation_function($form, &$form_state, $additional_values) {
    //Validation Code with access to $additional_values
}

This works for example 1:

$form['field']['#element_validate'] = array('my_validation_function');

How do I pass $additional_values to example 2 using $form['field']['#element_validate']

function where_ever_extra_data_originates_from() {
  $extra_data_to_pass_on_stored_here = &drupal_static(__FUNCTION__);
  $extra_data_to_pass_on_stored_here = $actual_extra_data
}

function my_validation_function($form, &$form_state) {
  //Here's our extra stuff now
  $extra_data = &drupal_static(where_ever_extra_data_originates_from);
}


Removing the dash/hyphen character from site search queries I use Custom Search module 7.x dev.

When my visitors put a dash/hyphen into search keywords, Drupal can't find the results.

For example if they search for Station1 Station2, everything is OK, but if the keywords are Station1-Station2 nothing can be found as result.
(Putting a "dash" makes sense for my visitors because they want to search for timetables from Station1 to Station2.)

String Overrides removes characters but I suppose that module doesn't solve this issue.

What solution can I adopt?

You can probably do it with hook_form_alter() and str_replace(). I'm not familiar with the Custom Search module, but seems like it's just altering Drupal's default search so you could make use of this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'search_form':
    case 'search_block_form':
      array_unshift($form['#validate'], 'mymodule_search_validation');
      break;
  }
}

function mymodule_search_validation($form, &$form_state) {
  if (isset($form_state['values']['keys'])) {
    $form_state['values']['keys'] = str_replace('-', ' ', $form_state['values']['keys']);
  }
  elseif (isset($form_state['values']['search_block_form'])) {
    $form_state['values']['search_block_form'] = str_replace('-', ' ', $form_state['values']['search_block_form']);
  }
}

The above code adds a custom validation function to the search and search block forms where any existing dashes will be replaced by a space. The reason for using array_unshift() and the form validation handler is to replace values early on for avoiding potential issues that could arise at later stages.


how to change language After a full day of searching, I can't find a way to make the multilingual to work on my site.

I want to create a temporary site to host privacy policies in many different languages (6) but with the skin of our corporate site which is only in English and French. In fact we could have created those pages in the corporate site but we don't want to translate the site in all those languages for now.

I created a new folder to host my new site in multisite mode. I also copy pasted many modules and a theme that was made (by an external firm and where the multilingual works) in my new site's folder to customize/handle them seperatly.

I tried to match all the modules of the original site with my new sites.

I didn't work... All my aliases answers with a

"The requested page "/fr/myalias" could not be found.".

Only the English aliases seems to work.

I followed the solutions found on these web site. Nothing worked.

https://www.drupal.org/node/1069310
https://stackoverflow.com/questions/13648789/drupal-7-url-alias-is-getting-ignored-on-pages-when-provide-a-menu-link-is-un
https://www.drupal.org/taxonomy/term/34344?page=7
https://www.drupal.org/node/1216132

At the beginning I though that it was the path alias that wasn't working but after a few hours I realized that the site never quit the English language (default).

I added 5 more languages (fr, nl, es, pt, de).

For a start, I just don't know why/how to change the language. I try calling "/fr" but that also answers with

  "The requested page "/fr"

could not be found."

Edit: also I realize that all the (working) pages are called with "/?q=node/somthing" instead of "/node/something"... if that helps...

About

  I realize that all the (working) pages are called with "/?q=node/somthing" instead of "/node/something"

To make your path aliases be human readable, pls check if Path module is enabled and then go to Administration » Configuration » Search and metadata  » Clean URLs and check "Enable clean URLs" checkbox. If it is not editable, you should ensure that PHP Rewrite mod is enabled.

To have your content displayed in diffrerent languages correctly you need:
1) Have Locale and Content transpation modules enabled. Both of them are Core modules.
2) Goto Home » Administration » Configuration » Regional and language » Languages and add the languages you need. Ensure that all required langs have ENABLE checkbox chacked. Also ensure that you have the correct Path prefix language codes (can change is edit Language) for each lanf, like "en" (without quotes) for English, "fr" for French etc.
3) Goto Administration » Structure » Content types » Your_content_type (that one you're using for creatinf translatable content) and ensure that in *Publishing options" tab "Multilingual support" is set for "Enabled, with translation".
4) Now create your piece of content and in creating content form set Language select box as "English" and set the URL alias as "policy-1" for example. Save it. Now you should see a "Translate" tab (near View/Edit tabs). Press it, select the lang you need and follow add translation link.

Tip: I don't know how your theme looks, so i'm not sure if you have a lang switcher for users or lang links displayed when viewing transled content. But if you use the same alias for all your translation, you can easily check if it works or not. For example if you set "policy-test" as Path alias for all transleted versions of your test node, you should be able to visit it via [yoursite]/[lang-prefix]/policy-test, i.e. via [yoursite]/en/policy-test or [yoursite]/fr/policy-test etc.

P.S. you don't need to use your lang prefix in path aliases for any language. Drupal will do it itself.


How to add an external image to node with a module? I have created a form through my module in which the user(anonymous) can enter an image URL and some title for the image.
The link needs to be, like with remote stream wrapper, shown as an actual image.
So this means, the image should be used from an external sources and not be download on my local server.

$node = new stdClass(); // Create a new node object
$node->type = "article"; // Or page, or whatever content type you like
node_object_prepare($node);

$node->title    = filter_xss($_GET['title']);
$node->language = en; // Or e.g. 'en' if locale is enabled

$file_path = $_GET['link'];

$file = (object) array(
        'uid' => 1,
        'uri' => $file_path,
        'filemime' => file_get_mimetype($file_path),
        'status' => 1,
);

$node->field_image[$node->language][0] = (array)$file;

$node->uid = 1; // UID of the author of the node; or use $node->name

node_save($node);

I have this code and it doesn't save the image URL. I'm sending the 'link' and 'title' properties through AJAX.

File field references are made on the fid column in the file_managed table -  you haven't saved the file object so it doesn't have a fid, and thus nothing to relate the field data to.

Just add a call to file_save after you've prepared the file object, but before you add it to the field on the node object:

file_save($file);


How can I get flag count of a flag? I see extensive Drupal 7 documentation for the Flags module, but very little for Drupal 8.
I have a Signup flag on a Drupal 8 node (which is an event). I need to suppress the Signup link when a number of signups (flags) have been added to this node.

I'm trying with hook_preprocess_flag() using the following code.

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById('signup');

What call gets the flag_count of that flag?

For flag count on entities use:

$flag_service = Drupal::service('flag.count');
$counts = $flag_service->getEntityFlagCounts($node);

For flag count on flag entity use:

$flag_service->getFlagFlaggingCount($flag);

You can find all functions from the Service here:

/modules/contrib/flag/src/FlagCountManager.php


"Ghost" pending update (backup_migrate) Working on a project on localhost, for which I installed the backup_migrate module, it seems one update procedure for this module had some problem (can't really remember what). And now every time I update any module (even totally unrelated), when performing the "update.php" script, Drupal states that there's the following pending update for the backup_migrate module:

7303 - Add a serial id field to all tables to allow them to be ctools exportable.

If I click apply, I get the usual progress bar, then the following error message:

backup_migrate module
Update #7303

Failed: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key: ALTER TABLE {backup_migrate_sources} DROP PRIMARY KEY; Array ( ) in db_drop_primary_key() (line 2904 of C:\xampp\htdocs\my_site\includes\database\database.inc).

So it seems to me that the update job #7303 has already been applied successfully, but for some reason Drupal hasn't registered that and thinks it still needs to be done.

How can I correct that?

OK I think I found it, although I haven't yet been able to confirm that the problem has been corrected, since all my modules are up to date.

Based on this question, here's what I did:

find the ID number for the pending update. In my case it was stated plainly in Drupal's update.php messages, so it's 7303. This information can also be found in the .install file in the module folder (e.g. function backup_migrate_update_7303).
access the database (e.g. via phpmyadmin) and go to the system table.
in this table, find the entry corresponding to the module whose update is still pending (in my case: backup_migrate)
edit the schema_version column for this row and give it the value of the update ID found in step 1 (e.g. 7303).

And that's it.


Error in db_query statement - d7 The below query is giving error:

PDOException: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound in webform_options_submit()

What am I missing? Any suggestions/ideas will be helpful.

And, How should I use the LIKE command in this query?

  $args = array(':entities' => $_REQUEST['entities'], ':countries'=>$_REQUEST['countries']);
  $query = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid", $args);
  $results = $query->execute();

Try it without the $query->execute(); as according to the docs for db_query the function already executes the query and returns a result.

Try this:

$args = array(':entities' => $_REQUEST['entities'], ':countries'=>$_REQUEST['countries']);
$result = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid", $args);

I would say the error is from trying to execute a result.


How to get the parameter value from an ajax call in the page controller? I have the following js code according to es6.
(($, Drupal) => {
  Drupal.behaviors.mymodule = {
    attach: () => {
      document.querySelectorAll("a").forEach(element => {
        element.addEventListener("click", e => {
            fetch("/mypath", {
              method: "POST",
              body: JSON.stringify({
                path: $(this).attr("href")
              }),
            });
        });
      });
    }
  };
})(jQuery, Drupal);

and in the page controller:
public function content(\Symfony\Component\HttpFoundation\Request $request) {
  $path = $request->request->get('path');
}

But I am not getting the path. Can someone tell me how to get the path in my page controller?

Why do you want to use fetch() when your code is based on jQuery? There a plenty of examples using $.ajax() for POST requests:
/core/modules/quickedit/js/quickedit.es6.js
  $.ajax({
    url: Drupal.url('quickedit/metadata'),
    type: 'POST',
    data: {
      'fields[]': fieldIDs,
      'entities[]': entityIDs,
    },
    dataType: 'json',
    success(results) {
      // Store the metadata.
      _.each(results, (fieldMetadata, fieldID) => {
        Drupal.quickedit.metadata.add(fieldID, fieldMetadata);
      });

      callback(fieldElementsWithoutMetadata);
    },
  });

/core/modules/quickedit/src/QuickEditController.php
  public function metadata(Request $request) {
    $fields = $request->request->get('fields');
    ...

To make PHP accept POST parameters you need to specify the correct request headers. Default in $.ajax() is the contentType application/x-www-form-urlencoded
So when using fetch() start with this:
fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },

To get on par with $.ajax() you might need to tweak fetch() a little more or wait until core decides to change the Ajax libraries from jQuery to pure Javascript.


How can I pass parameters to a Services endpoint? I have installed Drupal 7 and enabled Services in it. I have also created an endpoint /api/v2/ and in resources, I have allowed nodes to be listed as JSON.

I have sent a GET request using browser or POSTMAN to /api/v2/node then I am getting following results.

 [
 {
 nid: "3143",
 vid: "3932",
 type: "event_calendar",
 language: "en",
 title: "EVENTS STILL APPEAR ON FRONT PAGE WHEN EVENT HAS ENDED - with or w     ithout an END DATE ",
 uid: "139",
 status: "1",
 created: "1560282811",
 changed: "1560282922",
 comment: "1",
 promote: "0",
 sticky: "0",
 tnid: "0",
 translate: "0",
 uuid: "",
 uri: "http://..../api/v2/node/3143"
 },
...
 ]`

If I send a request to http://..../api/v2/node/[nid] then I am getting an individual record of that node.
Now I want to get post parameters to the endpoint. For example, I want to get all nodes with type = event_calendar.

I have tried posting parameters like http://..../api/v2/node?type=event_calendar but unfortunately, It is still showing list of all nodes. I have tried thing using POSTMAN and browser.

You need to use http://domain/api/v2/node?parameters[type]=event_calendar

any of the identifiers need to use inside parameters[]

Also, you can use services views module to expose the data and create new identifiers like type on your own.


Custom 404 page in a theme doesn't work as expected, I want to use a custom 404 page, I also have a theme installed.

This is what I did:

Go to Content, create a Node, I got path: node/28
Go to System->Site Information->Error Pages-> 404 page, I enter node/28

Then I type some pages that are not exists, it doesn't link me to the node/28, instead, it still use the themes' 404 page.

Some hint here?

BTW, I am using Drupal 7 and the theme called MD magnum.

Do what @jdu said and check the theme's template files for an error page template.  It will probably have the name page--error.tpl.php and probably be in /sites/all/themes/md_magnum/templates/

After that set your new error page URL in admin/config/site-information to the node you created.

To verify it is set you can check in your database under the variables table for site_404 to be set to that URL.

Make sure after you make these changes you clear cache completely and refresh your page.  If you are in Chrome, you may have to clear browser cache as well if you are using the same URL.


Depending on the argument passed in url go to specific content type I have a link "Add Details". suppose when I click on the Add Details, I will send arguments to the urls. such as in url "http://localhost/drupal/video" video will be my argument. When I click on "Add Details" link if argument is video then I want to go to "Video content type".

When I click on "Add Details", if argument passed is "image" in url("https://localhost/drupal/image), Then I want to go to "image content type".

When I click on "Add Details" link depending on the argument passed in URL I want to go to specific Content type.

How to achieve this.

Any help is appreciated.

Use hook_menu in custom module to achieve this using below code !
Change the links of Add Details to "goto/video" means full url will be localhost/drupal/goto/video

function yourmodule_menu() {
    $menus['goto/%'] = array(
        'title' => 'Just Redirect',
        'page callback' => 'drupal_redirect_to_content_type',
        'page arguments' => array(1),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $menus;
}

function drupal_redirect_to_content_type($type) {
  drupal_goto("admin/structure/types/manage/" . $type);
}

Otherwise,

Instead of above what you can do it directly give Add Details link to admin/structure/types/manage/ . $type instead of drupal/$type


How do I update modules with security release only using composer? On a Drupal 8 site, using the drupal-composer/drupal-project template, how would I go about updating only those modules which have a security release?

Our policy is to not update any module in our monthly maintenance routine unless it has a security update.

Ideally I'd like to find a solution which could be automated.

(I am using Drupal 7 modules as example, but just because there are more examples of security updates for Drupal 7 modules.)

Without custom coding, it's not possible. Drupal.org doesn't use a different name schema for security updates. From the version number you cannot know that version 7.x-3.14 of the Views module was a security update, while version 7.x-3.13 was not a security update.

That information is kept in https://updates.drupal.org/release-history/views/7.x, for the Drupal 7 version of the Views module, or in general in https://updates.drupal.org/release-history/<project short name>/<Drupal version>.
In the list of terms associated with a release, a Release type term whose value is Security update means the release is a security update.

<release>
  <name>views 7.x-3.14</name>
  <version>7.x-3.14</version>
  <tag>7.x-3.14</tag>
  <version_major>3</version_major>
  <version_patch>14</version_patch>
  <status>published</status>
  <release_link>
    https://www.drupal.org/project/views/releases/7.x-3.14
  </release_link>
  <download_link>
    https://ftp.drupal.org/files/projects/views-7.x-3.14.tar.gz
  </download_link>
  <date>1466019539</date>
  <mdhash>168bb684c8f34297be94b03c797841e5</mdhash>
  <filesize>1656594</filesize>
  <files>...</files>
  <terms>
    <term>
      <name>Release type</name>
      <value>Security update</value>
    </term>
    <term>
      <name>Release type</name>
      <value>Bug fixes</value>
    </term>
  </terms>
</release>

The classes under the \Drupal\update namespace can help in writing the required code. UpdateProcessor::parseXml() is the method used to parse the XML data for a single project, but you would probably need to access one of the services Drupal implements.


Get taxonomy term ID in node I have the following content types: hotels, and taxonomy terms; in hotels I have a taxonomy field.

How do I retrieve the taxonomy term ID in a node? Is it possible to retrieve the self and parent taxonomy term ID and name?

I have also tried this, but it does not work.

You can use field_get_items(), which returns you the value of a field in the language they would be displayed, or in the language whose code is passed as argument to the function. Generally, you are interested to the field's value in the language that would be used to show the field, and you don't pass any language code to the function.

$items = field_get_items('node', $node, $field_name);

$node contains the node object, and $field_name the name of the taxonomy term field.

What returned in $items is an array containing (possibly) multiple values; each value is an array containing the "tid" index, and the term ID. For a taxonomy term for which users can enter more than a value, this is what the function returns.


Is it necessary to "activate" a file input field after a jQuery insertion? I've got a Bootstrap modal that I use to present a form through which I can create and edit an node on my site.  This object has an uploaded file associated with it, so things work in the usual way: when I create the object, I get the "Browse..." field for selecting the file; when I edit the object, I get a little rendering of the file and a "Remove" button that is meant to let me get rid of the old file and pick a new one.

I haven't been able to get/figure out the Drupal ajax mechanism to work with my modal form, and, without it, clicking the Remove button refreshes the whole page, which blows my modal away and is clearly the wrong thing.  So I wrote some jQuery code for the Remove button: when the button is clicked, it removes the file's little rendering and inserts the same sort of file input field as when a node is created.  This works; the code I get on the page is the same as what's there when I'm creating a new node.

The problem (finally!) is that, after this file field is inserted into the modal, clicking the "Browse..." button doesn't do anything -- it doesn't bring up the system file selection panel that will let me choose the file.  I'm not seeing any error messages show up in the system log or the javascript console; I just get nothing (in several different browsers).  Any clues on what's going wrong?  Is there some initialization thing I have to do to get the system to pay attention to the newly-arrived input field?

False alarm -- a bit more hacking showed that I was putting the field into a part of the page where it didn't want to be.  Why this resulted in the "Browse..." button not working is still a mystery, but all is currently well.


Weird node edit form behavior with feeds imported nodes got a weird situation going on. I imported a bunch of nodes from a csv file using the feeds module to a particular content type. This conent type have different type of field like address field, entity reference, and a lot of long text.

All records from the file are imported and I can see all the nodes properly. But when I go in edit mode, All the text fields are empty. Title, address, dates and links fields are ok, but all text are empty. The data is in the database as well as showing on the node, but not in the edit mode.

This is of course causing me problems as when you have to edit, you"loose" all the text. I have a multilingual site...but all those node are set to english...and it's working. The only thing I saw was the fields table didn't seem to get the language value from the node set by the feeds. But I updated it manually in the table and it's not helping anyway.

Th encoding of the csv is utf-8..and I use \n as line break....it's an export of mysql.

Any idea why it's doing this? What I am doing something wrong? Is there a special trick to apply to prevent this...it's driving me crazy..

Thanks

Ok,I found the problem. Seems like feeds does not support languages. So in order to make it work, you need to manually update the language of the field in both the data and the revision table for the node you imported using feeds. Once both table are done, the data appears in the edit form.


Block View Relationship between two content types I have a Program content type which has a Paragraphs field which uses an Entity reference to a Course content type. Basically, when adding a program, I'm able to add a listing of what courses are available each semester. The semester is the paragraph field which includes a title (Ex. Semester 1) and then unlimited items to add the courses per semester. The courses are then shown on the program page by name and code and you're then able to click on the program name which takes you to the course page. This page has a description of the course and all the other info about it.

I have everything working how I need so far but what I'd like is to create a block view on each Course page that pretty much lists all the programs which this course is being taught in. I'm assuming I have to create some sort of Contextual Filter and perhaps a Relationships filter but everything I've tried has been a failure.

To sum this up: If a course is used by a program, display this program title on the course page in a block view.

Edit: Some images for reference

This is how the add courses paragraph looks on the Program content type

This is how the course page looks at the moment. I'd like an aside to the right showing the programs this course is taught in.

Edit 2: My relationships available

Here are the relationships that have the field courses:

I ended up figuring out what was needed for my issue. A Contextual Filter and a Relationship needed to be set.

For relationship, I needed to select Paragraph referenced from field_courses.
Then the contextual filter needed to be Courses (field_courses) Paragraph (category) Appears in: semester_courses (Description).

Now when I go to each course, it displays what program that course is taught in.