Display number of pending messages and friend request on the user menu I'm using Privatemsg & User Relationships and the built-in user menu as a sidebar block. What I want is to display the unread messages count and the pending friends requests beside the links "My messages" & "My friends".

Any ideas of how can I do this? Thanks in advance.

Mock-up:

This will return the unread private messages in Drupal 7.

<?php
global $user; privatemsg_unread_count($user);
?>

Refer this for more discussion

This will return pending relationship request for the loggedin user.

<?php
function _count_pending_relationships($account = NULL) {
  $counts = &drupal_static(__FUNCTION__, array());
  if (!$account || $account->uid == 0) {
    global $user;
    $account = $user;
  }

  if (!isset($counts[$account->uid])) {
    $count = 0;
    $pending_relationships = user_relationships_load(array('requestee_id' => $account->uid, 'approved' => 0), array('count' => TRUE));
    if (!empty($pending_relationships)) {
      foreach($pending_relationships as $requester_uid => $relationship) {
        if($account->uid != $requester_uid) {
          $count++;
        }
      }
    }
    $counts[$account->uid] = $count;
  }

  return $counts[$account->uid];
}
?>

Refer this for detail discussion.

You can create a block and create respective links with the functions shown above.


How can I iterate through all the key and value of configuration object I have an admin setting form (Configuration form) called 'example.settings'. I can load the configuration using below code.

  $config = \Drupal::config('example.settings');

Is there a way to iterate through and get all the configuration values in this config object

You could try the following to get the raw values back:

$config->getRawData()

E.g. the following

$config = \Drupal::config('system.maintenance');
$config->getRawData()

Returns and array of something like:
'message' => string(93) "@site is currently under maintenance. We should be back shortly. Thank you for y…"
'langcode' => "en"
→'_core' => array(1)


How do I access the view block name? How do I access the view block name?

function <theme_name>_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {

 // print_r(array_keys($variables));
  if (isset($variables['view'])) {
    $view_id = $variables['view']->id();
    $view_block = 'testing';
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $view_block);
  }
}

I'm not really sure this is correct, but I guess you are looking for the id for the block:

function THEMENAME_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  if (isset($variables['view'])) {
    $view_id = $variables['view'];
    $id = $view->id();
    $block_id = $view->getDisplay()->display['id'];
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $block_id);
  }
}

You can also print out the contents of the $view->getDisplay()->display array to check for other values that you might use.


Top level directory files like readme.txt are served by apache The content of the top-level server directory is publicly available by the web, e.g. files like example.com/readme.txt are readable.
Is it normal? How can i disable this?

(apache, ubuntu 12.04)

As I understood - you want to hide the txt files on the root direcroty (e.g. Changlog.txt) from prying eyes, therefore you can search Drupal.org for that question (its there..), and you'll see 3 types of solutions:
1. Leave those file as they are ( I don't like that option)
2. Just delete those files
3. Hide them using the site's .htaccess (My favorite option)


Exposed filter checkbox for "has comments" I would like to add a checkbox as an exposed filter to my view. When checked it will show all ndoes with 0 comments.

I looked at BEF but it didn't seem to be able to handle this.
I also have another exposed filter for that view, otherwise I could just hide the filter and use jquery to toggle the url when checking the checkbox.

You can add your own filter trough a custom module. I was in need of the same thing. The following code should work.

<?php
/**
 * Implements hook_views_api()
 */
function my_module_views_api() {
  return array(
    'api' => 3,
  );
}

/**
* Implements hook_views_data().
*/
function mymodule_views_data() {

  // comment_count
  $data['node_comment_statistics']['has_comment'] = array(
    'title' => t('Has comment'),
    'real field' => 'comment_count',
    'help' => t('Filter to see if entity has comments.'),
    'filter' => array(
      'handler' => 'cjsm_ikz_handler_filter_has_comments',
    ),
  );

  return $data;
}

The next thing should be a filter in an include file.

<?php
/**
* @file
* Definition of mymodule_handler_filter_has_comments.
*/

/**
 * Simple filter to see if entity has comments or not.
 *
 * @ingroup views_filter_handlers
 */
class mymodule_handler_filter_has_comments extends views_handler_filter_boolean_operator {
  function query() {
    $this->ensure_my_table();
    $field = "$this->table_alias.$this->real_field";

    if (empty($this->value)) {
      if ($this->accept_null) {
        $or = db_or()
        ->condition($field, 0, '=')
        ->condition($field, NULL, 'IS NULL');
        $this->query->add_where($this->options['group'], $or);
      }
      else {
        $this->query->add_where($this->options['group'], $field, 0, '=');
      }
    }
    else {
      $this->query->add_where($this->options['group'], $field, 0, '<>');
    }
  }
}

For me this is providing a selectbox. Because I also want to be able to see nodes with and without comments at the same time. But it does exactly what you are looking for. If you are having trouble implementing this I suggest you search for the ins and outs of creating custom views filters.


Drupal: User personalization of Taxonomy terms I have a requirement within Drupal to allow registered users to personalise the taxonomy terms that they see and use (leaving the defaults as they are) but haven't found any other information online on the best way to approach this - or if a module exists that does this. Specifically, the requirements are:

Drupal 6 or 7 (7 preferred)
Taxonomy items will be flat lists - not nested trees
The initial items will be the default set
Registered users can each change their default terms to suit their purposes - but the default set is untouched. Other users could have their own set. This would need to work similarly to internationalization (i18n).
Duplicate customizations are allowable.
Using (searching or displaying) duplicate customised terms will concatenate the result set of all the translated terms.

To try to give a simple example. Purely for illustration purposes, lets say the vocabulary is Soldiers.

The terms in the default set is:

Guard
Footman
Swordsman
Archer
Sergeant
Captain

and an orc user wants to reference the same terms with these customisations:

Peon     (Guard)
Grunt    (Footman)
Grunt    (Swordsman)
         (Archer)
         (Sergeant)
Chief    (Captain)

So when using the system the orc user has the following soldier list:

Peon
Grunt
Archer
Sergeant
Chief

Where 'Grunt' references both the Footman and Swordsman terms from the original. Archer and Sergeant use the defaults.

Hope this makes sense.

This sounds like a rather tricky to do.

i18n_taxonomy.module needs to do a lot of hacking and overriding of the taxonomy.module behaviors to always display translated terms. I don't think something like this already exists as a ready to use module.

One option might be to do this using fake translations and building a custom UI which would allow users to create a new personal language and "translate" the terms. However, it won't be able to deal with the merging part. It's also rather hackish...

Another option might be to ditch taxonomy.module completely using either a simple list field (which supports using a callback function for the possible values, but only through the API, see list_field_info()) and then build a UI which allows users to override the default values (and store them somewhere) or maybe even provide custom field widgets and formatters. Depending on your exact requirements, it might be easier to re-implement the features from taxonomy.module you need rather than trying to bend it to your will.


ReferenceError: Drupal is not defined I am working on a production site, moving settings from a development site for a mobile environment. However, I am receiving the above error. I can not figure out what is causing this error. It does not matter what theme I change my jquery mobile environment too. I've checked all the modules and they seem to be the same versions. The only thing I can see that is different is in the development site I can uncheck/check the block cache, on the production environment I can not do this.

Sounds like an issue with the ordering of the javascript files. Drupal is defined in

/misc/Drupal.js

var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };

Check Drupal.js is added to your HTML source, prior to when that variable is requested.


Show either a node or a blocks page at frontpage At the path "/" - the frontpage of my site, I want to show either

For anonymous users, the content of a particular node, which is normally available at "/somepath".
For authenticated users, a series of blocks.

How do I do this?

I think the most elegant answer involves using page manager to take control of the "/" route. With this it is easy to show a series of blocks as one variant, but I don't see how to show a particular node.

I have tried setting the "Default front page" at admin/config/system/site-information to "/somepath". But when I do this my panel page defined in page manager does not show up, either when it targets "/" or "/somepath".

As a fallback, I can probably achieve the same result without page manager at all, by choosing to hide the "content" block on the home page and show only the blocks I want. But I worry this gets messy fast, even using the block visibility groups module to avoid repeating the conditions.

I agree, the block layout gets quite messy when you try to do this. Another option would be a separate twig template for the front page.

Create two new regions frontpage_auth and frontpage_anon and fill them with the blocks you want to show. Don't configure the visibility here. Just place the blocks.

Modify page.html.twig, so that {{ page.content }} is enclosed in a twig block maincontent:

{% block maincontent %}
  {{ page.content }}
{% endblock %}

Then create a new twig file for the front page

page--front.html.twig

{% extends "page.html.twig" %}

{% block maincontent %}

  {% if logged_in %}
    {{ page.frontpage_auth }}
  {% else %}
    {{ page.frontpage_anon }}
  {% endif %}

{% endblock %}

where you display one of the two regions dependent on the variable logged_in.

For the node you can use the Main page content block or you can put the node in a view and use this view as a block.


Access restriction modules block nodes, but not teasers? Please forgive if this is bad form - this is my first post here, and I realise it's very similar to this existing question, although slightly different.

I'd like my site to have a bunch of public info, some members-only info, and some info only for super-users. All of the content-access modules I've tried seem to work when viewing the actual node, but in the taxonomy pages the teasers for these pages are still visible (thus leaking information). In short, you can see which pages you're not allowed to read in full, and that's a problem.

How can I make sure that users only see content --in any way-- that they are permitted to see?

I've implemented my access model by making three distinct roles (well, anonymous, authenticated, and "super user"), and three distinct content types for each user role and then assigning access based on content type, although for a very few nodes I do need to override this with node-level access control (for making a super-user page available in view-only mode to regular members). I'm not interested in per-user access control as such, per-role (with per-node override) is sufficient.

My site runs Drupal v7.2 (but I'm upgrading to 7.4 as I post this), and I've tried the modules named Node Privacy By Role and Content Access. Both of these work very nicely, except for the issue mentioned above.

Uh, okay this is a little embarrassing ... I had my Drupal site update itself and its modules, and lo: it suddenly worked as intended. Whee.


How to mix charts views and table views on the same page? I have a view with data displayed in a table format, and I have created another view formatted as a chart. For the view containing the chart, I used the views display style 'Charts', which was added as an additional views style by enabling the Charts module.

How can I display these two separated views on the same page?

A possible answer to this question for anybody using the charts module is contained in Steps to create charts using the views UI, located within its community documentation.

Here is part of the Bonus Tip included in it:

  You may find it easier to start with a "Table" display and convert it
  to a chart display after setting up the data. It can be easier to
  visualize what the result of the chart will be if it's been laid out
  in a table first.

Refer to "Example 2" in my answer to "How to create a chart from simple data without using the Views aggregation feature?" for an illustration of this approach (which also includes a view in export format to start from).

Another approach is to use module Panels to show charts created with module Charts.

Here are some other (related) documentation pages for the charts module, which may help to get you going with the charts module:

Getting Started.
Create Charts using views.
Charts Howtos.


Drupal Caching and hook_init So I was considering using hook_init() to do stuff but I'm not understanding what it means when it says that "This hook is not run on cached pages." Oh really?

So as an experiment I made sure caching was turned on for anonymous users, and went to the site in a browser window where I was not logged in. So I was definitely getting some cached pages, right? Then I added this to my module

function mymodule_init() {
  $num = rand(0,1000);
  drupal_set_message($num);
}

I figured if the hook wasn't being run, then I shouldn't get a random number each time I viewed the page. I wasn't sure if I should even get a message or not! But I am getting a different random number each time. So what exactly does it mean when it says that the hook isn't being run on cached pages? And when is it NOT ok to use this hook? Sorry if it's something obvious I don't know.

-- edit --

Thanks for the answer. I should have realized the drupal_set_message thing was causing the page not to be cached. So I went back and I also tried adding java script like this:

function mymodule_init() {
  $num = rand(0,1000);
  drupal_add_js(array('mymodule' => array('rand' => $num)), 'setting');

  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js($path . '/js/mymodule.js');

  echo $num;
}

And in my javascript file:

(function ($) {
    Drupal.behaviors.mymodule = {
        attach: function(context,settings) {
            var num = Drupal.settings.mymodule.rand;

            alert(num);
        }
    }
})(jQuery)

It still seems to alert a random number every time. So is drupal_add_js also disabling the cache? I even tried using a simple echo statement in hook_init() and it still seemed to echo a random number. So are all these things causing the page not to be cached or does hook_init() still get run somehow?

A couple things here:

hook_init() will be run on the first hit on the page, eg, if it's not in cache already, it will be run and then the page will be cached.  But...
A page will not be cached if there are any drupal messages, so, when you call drupal_set_message() it sets drupal_page_is_cacheable(FALSE); and the page isn't cached.

ADDITION:

Regarding your additional code with respect to Javascript:  adding this code in verbatim here does not exhibit the random behavior you see on your site; eg; here the same number appears until the cache is refreshed.

Which made me think about this.  Check your cache times:

If the times are set to <none> I see the behavior you seem to experience, but when they are set to anything else, eg:

then I don't.


How do I set an entity base field as NOT NULL? When creating custom entities in Drupal 8, you define a bunch of fields in baseFieldDefinitions() on your entity class, like this:

  <?php
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['postal_code'] = BaseFieldDefinition::create('integer')
      ->setLabel('PLZ')
      ->setDescription(t('Postal code.'))
      ->setSetting('unsigned', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'number',
      ])
      ->setRequired(TRUE);

    return $fields;
  }

However, these fields, despite being marked required, are defined as nullable in the database.

There’s no ->setNullable(FALSE) or similar method on BaseFieldDefinition. So how else do you make Drupal generate the schema correctly?

There is no API for that at the moment, every field that is specified as a key happens to be set to not null, but that's IMHO actually a bug and I would not rely on that.

Instead, the only thing you can do is provide a storage schema handler and customize the schema there.

See \Drupal\node\NodeStorageSchema::getSharedTableFieldSchema() for example.


showing taxonomy (tags) in alphabetical order on nodes I just noticed that my tags are appearing at the bottom of my posts in the order I entered them, not in alphabetical order. I'm sure this is something simple, but I can't figure out how to get them to display on my nodes in alphabetical order.

The first thing that comes to mind, you can try to reorder taxonomy tags in vocabulary in alphabetical order.
Perhaps there is a better solution...


Edit account menu item in user menu I want to add edit account menu item in user menu, I want the URL to be user/{user_id}/edit.
How can I achieve this without menu_token module.
I also tried creating menu item programatically as follow

$items = array();
  global $user;
  $user_id = $user->uid;
  $items['user/' . $user_id . '/edit'] = array(
    'title' => 'Edit account',
    'access callback' => 'user_is_anonymous',
    'menu_name' => 'user-menu',
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;

But newly created menu item only shows at back-end i.e. at structure/menu/user-menu but it doesn't display it on front-end.

function hook_menu() {
  $items = array();
  global $user;
  $user_id = $user->uid;
  $items['user/' . $user_id . '/edit'] = array(
    'title' => 'Edit account',
    'page callback' => 'MYMODULE_user_edit',
    'access callback' => 'MYMODULE_user_edit_access',
    'menu_name' => 'user-menu',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'user.pages.inc',
    'file path' => 'modules/user'
  );

  return $items;
}

function MYMODULE_user_edit() {
  global $user;
  $account = user_load($user->uid);
  return drupal_get_form('user_profile_form', $account);
}

function MYMODULE_user_edit_access(){
  global $user;
  return user_edit_access($user);
}

Try above code. :)


How is the hash for the files calculated? I am taking an HTML snapshot of a node in Drupal 8 every day at 4 am. Every night a Cron job kicks off this process. I have a service that handles the entire process.
Everything works for now, but I am worried that the referenced CSS and JavaScript files will break due to the filenames changed by the aggregation process.
How does Drupal 8 decide the name of the aggregated files? How can I reliably point the references to the right filenames?

The name of the aggregated files is the hash calculated from CssCollectionOptimizer::generateHash().
protected function generateHash(array $css_group) {
  $css_data = [];
  foreach ($css_group['items'] as $css_file) {
    $css_data[] = $css_file['data'];
  }
  return hash('sha256', serialize($css_data));
}

The method is called by CssCollectionOptimizer::optimize().
Without knowing to which group a resource is part of, and what other resources are part of that group, you cannot know the name of the file where the resources are aggregated.
There should not be any need to do that, as Drupal core takes care of removing any reference to aggregate files that don't exist anymore, and invalidate all the necessary cache bins.
The markup produced by Drupal core should never contain a reference to an aggregate file that doesn't exist anymore. If that happens, it's either a bug in Drupal core or in a third-party module.


Contents, Flags, Users and Node views I am in the process of making a social networking web site with Drupal7. Most of the tasks are done. However, i am stuck at this issue big time. I have created custom content type, Challenge. Using the flag module, i have placed a flag, Accept Challenge, on the nodes of this content type. Users click on this flag and accept the challenge. Now to complete the challenge users, have to post a blog about their challenge. So is there any way that when the user goes to node/add/blog and begins blogging, in the title field he or she has a drop down to pick from the nodes he has flagged. The name of the title should be same as that of node which was flagged. Please advice.  I hope i am clear. If not, please tell me and i would try my best to be as clear as i can

As a workaround you could show a list of accepted challenges for each user and link them to node/add/blog with the title prefilled using the prepopulate module.

You could also create a node reference from blog to challenge, use a "select" widget and narrow the option with a view (that's a cool feature of the node reference module). In that view you limit the records to the current user and only the challenges they have flagged.


How can I understand when a node is being edited or viewed? I want to add a class to the body to distinguish the node's view page from the edit page.

In classy you have 'page-node-type-' ~ node_type|clean_class. I'd like to add page-node-type-' ~ node_type|clean_class ~ '-edit' if we're on the edit page, but I can't figure out what that if statement would have in its condition.

Which code should I use to add that class only when a node is being edited?

In this case you'd want to look at parts of the url. The easiest way to do that would be passing in additional classes from a preprocess function in the .theme file, and by looking at the URL path:

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

if ($path_args[0] == 'node' && $path_args[2] == 'edit') {
  // add classes
}

This would be similar to using the arg() function from previous versions.


How can I serve js and css from Drupal 7 I'm very new to Drupal and I have a bunch of sites to manage that are in different cms's like wordpress, sharepoint and others. My goal is to merge all the content into drupal over time.

I want to manage a master menu in Drupal and when items are added or removed generate a html code snippet representing the menu that the other sites can pick up from the local file system or via a url if they are not.

How can I serve content from a url without the themes and drupal html being applied?

eg

have this url serve a css file

http://localhost/css/global.css

or get a js file from

http://localhost/js/app.js

or from a url like this

 http://localhost/globalmenu.html

get this html snippet ONLY

Menu Item 1

Menu Item 2

Menu Item 3

* EDIT *
The answer about the menu hook is really close to what i want, but I think i may have confused things by mentioning menus at all.

So I apologise as I didn't make what I am after very clear. Ill try and reword it.

For an arbitrary url I want to return content of any kind from the drupal 7 cms.

Which 'hook' takes the url, matches it to a pattern, and then allows me to send anything back on the response stream, and how do I change the mime types.

You'll need a custom module for this (see the Module Developer's Guide if you're not already familiar with creating modules, it's pretty straightforward).

Once you've got your custom module set up you need to implement hook_menu() and define a callback function for your URL:

function MYMODULE_menu() {
  $items['globalmenu.html'] = array(
    'title' => 'Global Menu',
    'access callback' => TRUE, // If you want any source to be able to access this page
    'page callback' => 'MYMODULE_deliver_global_menu'
  );

  return $items;
}

function MYMODULE_deliver_global_menu() {
  print '<div class="nav">...';
  drupal_exit();
}

Since Drupal will only actually apply the theme wrappers to a page if something is returned from the page callback, simply printing your HTML and calling drupal_exit() is all you need to do.

Sorry if some of that is stuff you already know, I thought it best to err on the side of caution.


Content Admin Search Tool Drupal 8 As a content admin, are there any feasible ways in Drupal 8 to search the source HTML of certain Text fields across multiple content types. For example, I want to find all nodes that contain <div class='special-list'> in one or more Text fields.

For Drupal 7, it seems that Views Bulk Operations would suffice. Has anyone encountered a similar need in D8?

VBO doesn't search, it only gives you the interface to select items in the Views results and perform actions on them.

To construct the search you want you can use ordinary Views with the Combine fields filter filter, here's one video tutorial: Search across Fields in Views using Combine Fields Filter in Drupal 8, or use Search API for something more advanced.

Once you have the search working you can add the VBO field if you need to do some actions on the found items.


Is there way to export block layout settings? I created a custom theme and I was wondering if there is way to export my block layout settings (location and order of each block). This way will be easier to apply my theme in a different site.

I'm using the Features module to keep on track of my custom blocks and block types.

This question is about D8, for which you can use an approach as suggested in the comment from Ivan Jaros, i.e.:

  ... enable config core module and export the blocks (they are basically just instances of blocks) via admin/config/development/configuration/single/export and put them into your theme's config/install directory.

What not everybody may know, is that this kind of block related facilities that are new in D8, is actually because of the Bean module which has been included with Drupal 8 core (refer to this issue for more information).

This implies that a similar question for D7 can be resolved also by using the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

This module only started as of D7 (because of the "entities" of course that were only introduced in D7), and already has over 22K reported installs. Those who don't use it yet (in D7) should definitely start looking at it in preparation of some day upgrading to D8.


Can I use I18N or another module to house regional variations of a site in a single installation? I have a large build coming up and am planning to attack it in Drupal 8.

The client will have three regional variations of their site, a .com, a .co.uk, and a .es. The goal is for them to look like one site. The sitemap will be 98% symmetrical between the three sites, only a handful of pages may exist in one menu and not in another. The .es will be in spanish, the .co.uk will be in UK English, .com in US English.

Is there any better way to approach the three sites that would make it easier to manage? For instance, using I18N? Having translations of each region is not a requirement, and almost every page will be shared between all three, with language variations (in .co.uk probably changes for SEO sake so we don't look like duplicate content).

Thank you for any input!

Af far as building and configuring such a project relying on Drupal multilingual features is a no-brainer, you should definitely go that way. Entering content in different languages has to be done either way, but with the multilingual setup, you don't have to repeat the work you do around the structure.

There probably is a very small number of special cases where not using multi-lingual features would be faster. Cases where you build one site, polish it, then just clone and do tiny adjustments for the other two languages. But the reality of web projects doesn't make it very probable that your project specs and necessary ongoing work will be so clearly defined to justify avoiding the multilingual setup.

Detection and Selection of Languages will allow you to choose URL as the detection method, and further in that configuration, you choose Domain (instead of the Path prefix) as the Part of the URL that determines language.

You'll have to do some planning around the menus, which ones you can share and translate, and whether you'll need to create some language-specific menus.

You'll be able to have language-specific paths, dates, other configuration... I found multilingual projects always take a lot more time to build than it seems, so don't underestimate it. It's not simply entering all the translated expressions into some interface and you're done. You have to learn about different places where to setup the structure for different languages etc. But in the end, it is faster to setup and maintain one site with multilingual features and translate it, than it is to build and maintain 3 separate ones.

Definitely learn about Hreflang for multilingual SEO, there's a link to Google support page explaining it there.


Views regex: exclude alphabetical strings as well as those with spaces I used the following regular expression on the Taxonomy term name field to exclude strings consisting solely of alphabetical names:

[^a-zA-Z]

Now I want to exclude those strings plus any string with a space.

What I want to do:

Hello (no)
Hi how are you (no)
ハロー (ok)

I tried this:

[^a-zA-Z\s]

This excludes alphabetical strings but not alphabetical strings with a space:

Hello (no)
Hi how are you (yes-> should be no)
ハロー(ok)

What am I doing wrong?

The Views module uses MySQL regular expressions, and \s is not recognized in those regular expressions.

You should try with [^a-zA-Z[:blank:]], or [^a-zA-Z[:space:]]. The first excludes any whitespace character, while the second excludes any space, tab, newline, and carriage return.

In the views_handler_filter_string class, the method associated with the regular expression is the following one.

  function op_regex($field) {
    $this->query->add_where($this->options['group'], $field, $this->value, 'RLIKE');
  }

// Add regexp support for MySQL.
if (Database::getConnection()->databaseType() == 'mysql') {
  $operators += array(
    'regular_expression' => array(
      'title' => t('Regular expression'),
      'short' => t('regex'),
      'method' => 'op_regex',
      'values' => 1,
    ),
  );
}


Dynamic Form Field Submit Handler This form creates dynamic fields. I am trying to build a submit handler for each of the dynamic field values.  So for each of the $form['items_fieldset'][$i]['serial'], (amount, and description) I could have many fields.  How would I pass those to my database?

Here's what I have thusfar:

Form excerpt:

$form['#tree'] = TRUE;

$form['items_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Shippment Inventory Items:'),
'#prefix' => '
',
'#suffix' => '
',
);

 if (empty($form_state['num_items'])) {
$form_state['num_items'] = 1;
}

 for ($i = 0; $i < $form_state['num_items']; $i++) {

$form['items_fieldset'][$i] = array(
'#prefix' => '
',
'#suffix' => '
'
);

$form['items_fieldset'][$i]['amount'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Amount:'),
  '#required' => FALSE,
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['items_fieldset'][$i]['description'] = array(
  '#type' => 'textfield',
  '#size' => 50,
  '#title' => t('Description:'),
  '#required' => FALSE,
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['items_fieldset'][$i]['serial'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Serial Number:'),
  '#required' => FALSE,
  '#prefix' => '
',
  '#suffix' => '

',
);
}

$form['items_fieldset']['add_items'] = array(
'#type' => 'submit',
'#value' => t('Add more'),
'#submit' => array('_nnreport_shipping_new_add_one'),
'#ajax' => array(
    'callback' => '_nnreport_shipping_new_callback',
    'wrapper' => 'items-fieldset-wrapper',
    ),
);

Handler to pass to database (not including all the static form values):

 function _nnreport_shipping_new_submit($form, &$form_state) {
    $submission = new stdClass();
    //This doesnt work, but I think it's kinda what I'm after...??
     for ($i = 0; $i < $form_state['num_items']; $i++) {
          $submission=>amount.$i = $form_state['values']['$i']['amount'];

          };
          _nnreport_shipping_new_update($submission); }

After that I submit the values of $submission to the database, like this:

function _nnreport_shipping_new_update(&$submission){

     db_insert('nnj_shipment')
        ->fields(array(
            'hotshotId' => $submission->carrier,
            'driver' => $submission->driver,
            'driverPhone' => $submission->driverPhone,
             //lots more of those...
              ))
             ->execute();

I've unsuccessfully tried a few variations to get the dynamic fields into the object...I would be very grateful for someone to point me in the correct direction.

Well after ignoring this problem for a while it was time to find an answer.

The issue was with using $form['#tree'] = TRUE;
I didn't use the full array references after that...eg:
$form_state[$i]['description'] needed to be
$form_state['values']['items_fieldset'][$i]['description'] = 'foo';
(

After that I just used a foreach to grab my values from the dynamic field values...like:
foreach ($form_state['values']['items_fieldset'] as $v){
$submission->description[] = $v['description'];
}

And last was to dump them into my DB, and life is good.


VBO custom action: get the list of selected items I need to create an vbo action to produce a document (pdf) with a page for every item selected in the list.

Using im using hook_action_info but the callback get called once for every item selected; I need to have a function that get called with the list of selected items.

I've seen the Pass ids as arguments to a page action, that can fit my needs, but hey I'll love to avoid having such kind of urls (if possible, of course)

Is possible?

You don't do it at once, you generate the document page by page (item by item).
The document gets created on first run, and on the last run you do whatever cleanup you need.

See archive.action.inc that ships with VBO for an example of this approach.

You can mark your action as "aggregate", and get all rows, but that's going to significantly limit the number of items you can add to the document (depending on your memory limit). VBO is designed to work item-by-item.


Workbench Moderation - intermittent save / autosave without new revision I'm stuck with a problem while using workbench moderation. while working on a node, my client wants to save / auto save his work but if he hits the default save button then it is creating a revision (which is unwanted, since his work is not finished yet).

how is it possible for admin to save their content while they are still working on it, something like "save as draft", which they can continue later?

is there a way in workbench moderation to have it create a revision only when the moderation state is changed? If not, is there any other module which works with workbench to auto save / save the work without creating a new revision.

I also need the admin to stay on the same edit page when he hits this save button. I tested "save & edit" module, which does what I need but it also creates a new revision, which is not required.

please help!

You can do it by using these modules :

Save Draft

  Save Draft adds a 'Save as Draft' Button to the node_form for content
  types, allowing the user to click the 'Save as Draft' button to save
  the node as a draft.

Draft

  The Draft module provides the ability too create drafts of existing
  nodes as well as new nodes before you have saved them.

  The module utilizes the jquery.fields plugin to serialize all of the
  information and then the information is stored in a database row
  serialized.

  The module provides the ability to autosave the content without
  the user having to hit the Save as Draft button on the form.


Remove default installation profiles with drupal core Is there a way to remove the core installation profiles that come with drupal without the need of hacking core? i.e. is there a hook that can run to alter this list?

The reason why this is required is that we are making a custom install profile for use with aegir, and do not want the default core drupal 'minimal' and 'standard' install profiles as options for the users to create new sites.

Perhaps this could be a hook in aegir?

Has anyone found an elegant solution to this?

You need to add exclusive = 1 line in the .info file of your profile.


How to change layout of node add/edit form with Display Suite? Is there a way to use Display Suites to change a Layout for a Node Edit/Add form?
i.e. form at: .../node/add/

That is possible yes. Display Suite contains a submodule called 'Display Suite Forms' which allows you then to select a layout and move the fields around in that layout.

Note that it's impossible though to move the individual elements in the vertical tabs. That will always remain the same and will rendered at the bottom of the layout.


How I can get nodes of type basic page of current month only in drupal views I want to create a view which display result of current month only. If I will add post date field in filter then what operator I will choose and how i can get results.

Add 'Filter criteria' with the next settings


get the list of menu items that are valid possible parents for the given menu item using menu_parent_options() I want to get the list of parents for a given menu item. As described at api.drupal.org  https://api.drupal.org/api/drupal/modules%21menu%21menu.module/function/menu_parent_options/7
I tried but i am not able to get all the parent of a menu item. As the second argument $item to this function should be menu item i tried this code. For example

<?php
$menu_name = array('management' => 'Management');
var_dump(menu_parent_options($menu_name, menu_link_load(23)));
?>

I want to get the parent list of menu /admin/appearance/list which have mlid = 23.
But this code give output

  array (size=1)   'management:0' => string '' (length=12)

but output should give /admin/ and /admin/appearance also in output in the form of

  menuname:mlid

Try this and see if it helps

<?php
$menu_arr = menu_get_menus();
echo '<pre>';print_r((menu_parent_options($menu_arr, 23)));
?>


How to remove a specific term page link? I have taxonomy term list page..

Apple
Banana
Sweets
Cake

These are the terms listed with links to default term page.

suppose I want to remove the link for Apple only but listed how do I go about it?

I have tried this

  function mytheme_node_view($node, $view_mode, $langcode) {
    if (isset($node->content['field_fruit_name'])) {
      foreach ($node->content['field_fruit_name']['#items'] as $delta => $item) {
         if (count(taxonomy_select_nodes($item['taxonomy_term']->tid)) < 2) {
           $title = $node->content['field_fruit_name'][$delta]['#title'];
           $node->content['field_fruit_name'][$delta] = array();
           $node->content['field_fruit_name'][$delta]['#markup'] = $title;
         }
      }
    }
  }

its not working... so if i can remove the link for each term individually it would be great.

Little bit tricky but you can achieve without code.

Add a new boolean field to taxonomy term.(eg: show link(field name))

Save for each term show link value either true or false. Depend you wants to show the link or hide the link for that term.

Add three fields like shown in the image in your views.

Taxonomy term: Name [hidden] -- Exclude from display and deselect link to taxonomy term

Taxonomy term: Term ID [hidden]  -- Exclude from display

Taxonomy term: show link


Share and update the structure (content types, vocabularies/tags, views, rules, …) for several sites I want to start a Drupal 7 site, and it’s likely that in the future I need to run several other sites that should share the same modules, theme, configuration, content types, vocabularies and tags, views, rules, …. Apart from created nodes and things like the site name, they should be 100% copies, i.e., all changes should be applied to all current as well as all future sites.

It doesn’t matter if the userbase is shared or not. If it matters, all sites share the same second-level domain, i.e., every site has a subdomain.

As I start with only one site, I could make all changes to the structure (e.g., to node types or tags) right at this place. But as soon as there are two sites, I don’t want to have to replicate all changes for all sites.

How could I achieve this?

As far as I understand, the multi-site functionality would help with modules, but not with configuration or content types or vocabularies/tags, correct?

Should I create a custom distribution? Whenever I want to change something, I can change it in the distribution first and then automagically update it on all sites (without losing the already created content)?

Or should I use one site and, somehow (how?), divide the content into areas/sections so that it only appears on specific sub domains?

Or is there another way?

We use the domain access module, https://drupal.org/project/domain

Everything is or can be shared on the multiple sites ... we choose to have different themes for each domain and we only have a few nodes that are common to multiple sites, most of our nodes are only on one site, but the content types and taxonomies and blocks and views are shared.

There are some current domain views filters that allow exactly the same view to be used on multiple sites but show different content on each.

It is working really well for us, our only issues are that

There are some reports that combine all domains when we would like to have them separate (e.g. ubercart)
Users have to login to each site separately
All relative path links are rewritten to the correct domain automatically but if someone for some reason requests a path on the wrong domain they are not redirected and they see an access denied message.


hook_menu URL giving 404 error on running site randomly I have a hook_menu URL exposed as a URL and I am also calling the same callback function separately in code
The URL returns 404 at error at sometimes and starts working fine after a cache clear.
What could be the possible issue ?
hook_menu Implementation

  $items['test_link/get-response'] = array(
    'title' => t('Get Response'),
    'page callback' => 'get_response',
    'page arguments' => null,
    'access callback'   => true, // available to all
    'type' => MENU_CALLBACK,
  ); // end

function get_response($funParams=array(),$res='json'){
  $allParams = drupal_get_query_parameters($_GET);
  if(isset($funParams['pincode']))
  $allParams=$funParams;

  $result = array();
  $result["status"] = TRUE;

  // Processing on allParams and builds the response array
  return displayJSONResponse($result,$res);
}

function displayJSONResponse($response,$res='json'){
    if($res=='nojson')
        return $response;
    $res = '';
    if(defined('JSON_PRETTY_PRINT'))
    $res = json_encode($response, JSON_PRETTY_PRINT);
    else
    $res = json_encode($response);
    $json = str_replace('\\/', '/', $res);
    echo $json;
    exit;
}

Page arguments, if specified, should always be an array. If you do not want to pass any arguments to your callback you should either code an empty array or omit the parameter. From experience I am fairly confident that this is your problem.

Also, the correct way to return a JSON response is to return NULL from your callback after printing the JSON, rather than exiting. This ensures that cleanup tasks can be run.

Your code does not comply with Drupal standards, and I would strongly advise you to follow them. It's a major part of learning to work with the framework. https://www.drupal.org/docs/develop/standards


Drupal 7 views: Get NID in views using contextual filters Does anybody know how to get the nid from a node using contextual filters or filter criteria in views

WITHOUT using "Get id from url"? I was thinking about using PHP or getting it from a node-field.

My view is a block of comments that is to be placed together with a node. The comments needs to belong to the node and linked by node ID. In this case the "Get ID from url" wont work since the node itself is listed in another view.

It is a view-block (containing comments) inside of a node that is listed in a view.

If you are loading and displaying your view in the node.tpl or node--<content-type>.tpl file, you could supply the current node nid as an argument to your block view, then you can setup a contextual filter for Content: Nid. I would do something like this:

// get view
$view = views_get_view('YOUR_VIEW_NAME');
// set display for view
$view->set_display('YOUR_VIEW_BLOCK_NAME');
// set current node nid as argument to view
$view->set_arguments(array($node->nid));
// execute view
$view->execute();
// render view
print $view->render();


What do I set GUID to in Feeds Import? I was told I should use GUID and tick Unique setting for best method of filtering out duplicate content each time cron runs. But what do I set GUID to? My XML sources has like only ,  etc.

Now I am using Title as unique for duplicates. But I get lots of random issues, Feeds Import doesn't import all feeds after each cron, or even better, it gets stuck e.g. 'Importing 48%' and etc.

I got 4 feed imports that parse XML from external site, all from same site (also Drupal). Also I use custom module to trigger them when running cron, because by default Feed Import doesn't even react to hourly cron.

So trying various solutions, maybe this GUID thing will solve this.

I also use XPath XML parser.

You can use a the node or article URL as it's Unique and a lot of feeds use it with no issues at all


Submenu tree problem I have a website build with Drupal 7 CMS and I am using the Submenu tree module. Everything was working fine for months, but few weeks ago I have received a feedback from the client that all the links of sub and sublink content was disappeared. I have checked my local version of the website, and there are no any links also.

I have tried to use the same module on another local Drupal 7 website and the result is the same - no matter how I try to set it up - it does not show any sub or sublink content links.

Does anyone has the same problem? Anybody using the same module - can you confirm that it works fine with your website ?

I have managed to fix this issue by reverting the module to an older version.As I see in the release notes

  Issue #3037177 by itcrowd72, omrmankar, troybthompson: PHP 7.2 each() function is deprecated

The php version I am still using is 5.6. It looks like the new module version is not ok with 5.6, or at least with my setup.


How to find the user avatar filename in Drupal 7 In my custom module for Drupal 7 I've been using the following 2 SQL queries to find the user's avatar picture and the city (a custom text field):

function pref_block_view($block_name = '') {
  global $user;
  $viewer_id = $user->uid;

  if ($block_name == 'pref_main') {

    $result = db_query('select field_city_value from {field_data_field_city} where entity_id=:uid', array(':uid' => array($viewer_id)));
    $city   = $result->fetchField();

    $result = db_query('select filename from {file_managed} where uid=:uid', array(':uid' => array($viewer_id)));
    $avatar = $result->fetchField();

and at first this worked well (probably because each user hat just 1 picture - namely the avatar).

But then users attached pictures to blogs and books and now this query doesn't really work:

 # select * from drupal_file_managed where uid=1;
 fid  | uid |           filename           |                      uri                       |  filemime  | filesize | status | timestamp
------+-----+------------------------------+------------------------------------------------+------------+----------+--------+------------
  631 |   1 | 111.png                      | public://111_0.png                             | image/png  |   289191 |      1 | 1303376737
  843 |   1 | etud18.png                   | public://etud18.png                            | image/png  |   893838 |      1 | 1305905585
  527 |   1 | yaro-3.jpg                   | public://yaro-3.jpg                            | image/jpeg |    89814 |      1 | 1302367745
  529 |   1 | yaro-4.jpg                   | public://yaro-4_0.jpg                          | image/jpeg |   122129 |      1 | 1302367789
  638 |   1 | etud015.jpg                  | public://etud015_0.jpg                         | image/jpeg |   116956 |      1 | 1303459359
  835 |   1 | pref.jpg                     | public://pref_0.jpg                            | image/jpeg |    95079 |      1 | 1305838610

So I'm obviously using wrong query. Any help please?

Check the table "users", column "picture". Join that on the fid from the file_managed table.


empty optional fields: saved node contains the token name instead of an empty section I have created a content type that has some tokens within the read-only body section so that other custom fields that the user enters when they create content based on this content type are mapped to its associated token within the body section.  If the user enters information within a optional field then that entered information replaces the token when the node is saved.  The problem is for optional fields when they don't enter a anything within it then the saved node contains the token name instead of an empty section which is what we want.

I have figured it out with my own custom module:

function mymodule_tokens_alter(&$replacements, $context) {
    if ($context['type'] == 'node') {
        $keys = array_keys($context['tokens']);
        foreach ($keys as $key) {
            if (isset($context['tokens'][$key]) && !isset($replacements[$context['tokens'][$key]])) {
                $replacements[$context['tokens'][$key]] = '';
            }
        }
    }
}


Programmatically format integer field display I am trying to programmatically format how an integer field displays. So far I have only been able to produce "1.00", and I am trying to get it like so: x.xx.x. The content type is "Project" and the field is "Drupal version".

Here is my code:

<!-- Display the drupal version with decimals -->
      <?php if (isset($node) && $node->type == 'project'): ?>
          <?php $drupal_version = field_view_field('node', $node, 'field_drupal_version', array('label'=>'default')); ?>

          <?php $formatted_drupal_version = number_format((float)$drupal_version, 2); ?>
          <?php echo "Drupal version: " . render($formatted_drupal_version); ?></span>
      <?php endif; ?>

output: Drupal version: 1.00

Does anyone know why this is the output, and how I can extend this function number_format to produce something in this format x.xx.x, for example "Drupal version: 7.41.1" ?

Thanks!

You can do this using the following code:

$drupal_version = (int)$drupal_version; // make sure this is an int
$parts = array();
preg_match('/^(\d{1})(\d{2})(\d+)$/', "$drupal_version", $parts);
array_shift($parts); // get rid of the first element in $parts which is the whole matched string
$formatted_drupal_version = implode($parts, '.');
echo "Drupal version: " . $formatted_drupal_version;

As examples, these integers will turn into the following strings:
7411 => 7.41.1
74110 => 7.41.10

Which means, that this code, will work parsing the provided integer from left to right, and collecting, 1 digit for the major version, 2 digits for the medium version, and all the remaining digits for the minor version.

Hope this helps!

P.S.: You question is a bit misleading, as @No Sssweat says, you cannot format an integer like that. That is why string parsing is the only way to provide you with the desired result.


Force profile2 field display based on current user's role I am using the profile2 and the profile2 page modules. I have 2 profiles called user and advanced_user and corresponding roles associated to them. The advanced_user has more fields available in his profile.

The problem: when I strip an advanced_user of his role (aka demote him to user), the extra fields that he previously filled in his profile form remain in his profile page and so is the "Advanced User" title. How can I remove the additional information that was added in the advanced profile?

Note: I wouldn't mind if the extra fields' information was kept stored (so that if I ever "promote" her again she would have the fields already populated) but I definitely want to keep them from showing in the user's profile page.

Try implementing hook_profile2_view_alter(). Below is a sample code:

/**
 * Implements hook_profile2_view_alter().
 */
function example_profile2_view_alter(&$build) {
  global $user;
  $rid = <advance_user_role_id>;

  if (!array_key_exists($rid, $user->roles)) {

    $advance_fields = array(); // List of field ID's that should only be displayed
                               // for advance users.

    foreach (element_children($build) as $id) {
      if (in_array($id, $advance_fields)) {
        $build[$id]['#access'] = FALSE;
      }
    }
  }
}


use drupal's hashing in an external php fil we are making a few web services for a Drupal 7 based websites.
in that webservice, one task is to sign up new users on that website.

the only main issue at the moment for this task is to access the drupal hash function in a php code file that is not inside the drupal's installation directory.

any guidance on how to achieve this will be highly appreciated.

What you'll need is Drupal's password.inc file, located at: /includes/password.inc

Just copy this file to your project and include it in your custom php file. This way you can use the user_check_password() function (and many others).

here is a good example of something like you are trying to do in Laravel 4. http://www.goodbytes.be/blog/article/create-a-custom-drupal-7-authentication-driver-provider-in-laravel-4


Unexpected session reset when making authenticated user REST requests I am using Drupal 7 and Services module
To create endpoints for login and subsequent functionality exposed for logged in users
As noted here and here, the ideal workflow should be -- Make a POST request with username and password > to end point /user/login (the end point is already enabled) > return data contains Session name and Session id > you join both of them with an '=' in between to form the cookie > you send that cookie in subsequent requests in the request header > these requests automatically get treated as authenticated user requests > All is good
But in my case when I do the last step (send cookie in request header) something weird happens. The uid associated with that particular session in the sessions table is set to 0. (In effect the session is authenticated user session anymore, it is not destroyed either, it just goes anonymous)

I am really puzzled by this. I have replicated the behavior on multiple setups, and hoping that this is just a case of me missing something obvious here.

Any help would be much appreciated? Super many thanks in advance.

Well. I found what was causing the error (unexpected behavior) reported above. There are chances that others might get stuck in a similar fashion, so I am answering my own question -

The above resetting of Session was taking place because my service end point was not configured to work with 'authenticated sessions'. When creating a new service endpoint there is an optional checkbox labeled Session authentication with description Choose which authentication schemes that should be used with your endpoint. If no authentication method is selected all requests will be done by an anonymous user. which one needs to check so that web service resources created under that end point and allow authenticated sessions.

If you fail to check this checkbox at the time of creating the endpoint, you could do so later too, by editing the particular endpoint and clicking on the EDIT tab.


Using drush into remote host is showing me local data I have an alias setup for my remote host with the following in the script:

<?php
$aliases['lws'] = array(
    'root' => 'domain.com:/home/user/public_html',
    'uri' => 'domain.com',
    'remote-user' => 'user',
);
?>

But when I drush using (for example): drush @lws status

I get information back about my local machine and not about the remote machine. I know this is the case because my remote machine is Linux and my local machine is windows...and when I run drush from the remote machine itself it shows me different results than what drush on my local machine is giving me. Also the command above run locally shows me all the alias files I have setup on my local machine (for other drupal installs).

Any idea what might be going on here?

It'd be interesting to see what results you'd get if you modify your script above by removing the domain.com: (in 'root'), to make it look like so:

<?php
$aliases['lws'] = array(
    'root' => '/home/user/public_html',
    'uri' => 'domain.com',
    'remote-user' => 'user',
);
?>

At least that would make it look more like the samples for 'dev' and 'prod' as documented in https://www.drupal.org/node/1401522 .

Curious to hear if this helps somehow ...


How to setup "drush @mysite.env ssh" command? I am trying to create a custom drush command in which I have to access another remote environment and run some drush commands there. The problem is I am unable to ssh to another environment e.g, "dev" etc.
I am able to run

drush @mysite.env status

but when I try

drush @mysite.env ssh

then I get this error

PTY allocation request failed on channel 0
Command not supported as typed.
An error 255 occurred while running the command `ssh -p 2222 -o AddressFamily inet"

"pantheon.aliases.drushrc.php" is placed in "~/.drush" folder.

Please let me know what's missing.

Thanks

Pantheon does not support ssh access to your server. Write your own Drush command, place it in the drush folder at your repository root, and call it with drush @mysite.env mycommand.


I can't uninstall modules with Drush master-branch and almost no data on Google When navigating to my sites' folder and typing drush pmu admin_menu or otherwise drush pm-uninstall admin_menu in drush master branch I get:

  Command pm-uninstall needs a higher bootstrap level to run - you will
  need to invoke drush from a more functional Drupal environment to run
  this command.

I found only 3 discussions in Google, touching this in relation to Drupal 7 (dev or fresh).

I should note that another command, drush cr (cache-rebuild) works
just fine.

Drush status:

C:\wamp\www\sname>drush status
 Drupal version         :  8.0.0
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  sname
 Database name          :  sname
 PHP executable         :  php.exe
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\drush-master\drush.php
 Drush version          :  8.1-dev
 Drush temp directory   :  C:\Users\Beni\AppData\Local\Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\sname
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_mkuaR5uFQ7VCjh1_FFBuZzWXkUsz-sA7Klv4HO_2yLJG33wfJJabdavO7QKzyIRWiQoWA3IJbg/sync

C:\wamp\www\sname>

Drush sql-conf

C:\wamp\www\sname>drush sql-conf
Array
(
[database] => sname
[username] => sname
[prefix] => Array
    (
        [default] =>
    )

[host] => localhost
[port] => 3306
[namespace] => Drupal\Core\Database\Driver\mysql
[driver] => mysql

The problem is not with Drush is with admin_menu. This is a bug on admin_menu not been ready. See more about this - admin_menu has broken d8-beta11 and i cant pm-uninstall

How to solve it ?

  (note, deleting the module rm -r modules/admin_menu and rebuilding
  cache brings the site back)

Source

Steps by Step Instructions

Open your terminal
Change directory to you root Drupal 8 core
Then remove the admin_menu project and then clear the cache.
rm -rf modules/admin_menu # Remove the directory.
drush cr # This will clear the cache

admin_menu is not ready, I will recommend you to use admin_toolbar for now.


Cannot set form #default_value when altering Views Exposed Filter forms function mymodule_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);

  if ($form_id == 'views_exposed_form') {
    $options = array(
      'All' => t('All'),
      '$' => '$',
      '€' => '€',
      'тг' => 'тг',
    );

    $form['field_price_second']['#type'] = 'select';
    $form['field_price_second']['#options'] = $options;
    $form['field_price_second']['#default_value'] = '$';
    $form['field_price_second']['#size'] = 1;
    $form['field_price_second']['#validated'] = TRUE;

    dpm($form);
  }
}

However, the default value isn't working, i see instead 'All' value as default in my views exposed form's select list. What's wrong?

DPM output:

Try overriding the whole element, like this:

...
if ($form_id == 'views_exposed_form') {
    $options = array(
      'All' => t('All'),
      '$' => '$',
      '€' => '€',
      'тг' => 'тг',
    );

  $form['field_price_second'] = array(
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => '$',
    '#size' => 1,
    '#validated' => TRUE,
  );

    dpm($form);
  }
 ....


Where to add custom theme function that generates HTML? I am making a theme for Drupal 7 that includes an HTML5/CSS3 animation in the header. The animation works fine, but I want to generate the HTML for it dynamically so there is an element of randomness.

At the moment I am doing this via a pair of simple for loops in page.tpl.php but I am aware this isn't really the best place to put the code. I have spent a little while searching and most answers seem to deal with modifying variables or code that Drupal puts out, whereas this is generating some completely new HTML.

What is the "Drupal way" to handle this? Just add a custom function to template.php that I call (themename_mycustomfunction) or do it in the preprocessor function (themename_preprocess_page) to add the generated HTML as a variable?
Thanks

EDIT: This is the code I've currently got located at the top of my page.tpl.php. Nothing fancy, just generates some divs with the classes that the CSS3 animation will use. Where is the best place to put it though?

    <?php
    for ($i = 1; $i <= 10; $i++) {
        ?>
        <div class="block o<?php print rand(1,3); ?> w<?php print rand(1,6); ?> x<?php print rand(1,9); ?> start">

        <?php
    }
    ?>
    <?php
    for ($i = 1; $i <= 20; $i++) {
        ?>
        <div class="block o<?php print rand(1,3); ?> w<?php print rand(1,6); ?> x<?php print rand(1,9); ?>">

        <?php
    }
    ?>

Your nearly there...

If your going to do this on the theme layer then create the custom function and call it in a process function assigning to a variable that can be passed to the template.

Thats typically the "Drupal way".

template.php

function THEME_customFunction() {
   // blah blah...
}

template.php

function THEME_preprocess_page(&$vars) {
   // blah blah...

   $vars['animation'] = THEME_customFunction();

}

page.tpl.php

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


Entities, bundles and fields I've created entities and bundles through Entity Construction Kit UI, and now I'm trying to re-create everything with code, in a module.
I managed to generate entity with Drupal console, added fields, and everything works well.

The problem is when I try to create bundles for an entity, with different fields.
In ECK, I can create an entity, then bundles, and add different fields to each bundle.
However, I can't understand how to do it in the code, and after reading tons of documentation, it feels like bundles are only configuration entities and can't have fields.

So my questions are :

Is there something I don't understand ?
How can I mimic ECK "bundles with fields" in code ? My goal is to create profiles, like the profile module can do for users, but referenced from an other entity, and with specific behavior, so I'd prefer create my own entities.

Yes, the bundle entities themself are not fieldable.

But bundle config entities in the end only exist to manage bundles for the content entity type, and as far as content entities are concerned, bundles are basically just a string (and a bit of metadata like a title). It's even possible to have bundles based on plugins or other things.

Per-bundle fields (usually configurable fields defined only in config, but it would be possible to define them in code as well, currently not trivial) are then attached to a content entity type + specific bundle. Fields actually consist of two definitions: field storage, which is tied to the entity type and defines name and storage-level settings, and the field, which is for a bundle and has bundle-level settings, label and so on. Base field definitions defined in the baseFieldDefinitions() method are exposed as both the field storage and field definition.

Haven't yet read it in detail, but http://www.daggerhart.com/drupal-8-custom-entities-bundles/ is a recent (as in, ~1h old) extensive resource on how to build entity types with bundles.


How to validate allowed file types in custom module I want to validate a field with accepted file type as PDF, XLS, JPEG, JPG, GIF, ZIP, RAR and PNG.

I'm getting file types as PDF, XLS etc. here is part of my code.

if ($fi_name!='') {

  if ($p_filefilename[1] != 'pdf'
    ||$p_filefilename[1] != 'xls'
    ||$p_filefilename[1] != 'jpeg'
    ||$p_filefilename[1] != 'jpg'
    ||$p_filefilename[1] != 'zip'
    ||$p_filefilename[1] != 'rar'
    ||$p_filefilename[1] != 'png') {

    $form_state->setErrorByName('document', $this->t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
  }
}

Even when I'm uploading PDF files it's going to error part and showing my message as "Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file."

What am I doing wrong?

That's basic logic. Change your ORs to ANDs.

if ($p_filefilename[1] != 'pdf'
  && $p_filefilename[1] != 'xls'
  && $p_filefilename[1] != 'jpeg'
  && $p_filefilename[1] != 'jpg'
  && $p_filefilename[1] != 'zip'
  && $p_filefilename[1] != 'rar'
  && $p_filefilename[1] != 'png') {

  $form_state->setErrorByName('document', $this->t('Please upload document  in pdf, xls, jpeg, jpg, gif, zip, rar and png file.'));
}

Anyway, you should use in_array() for that check. For example:

$allowed_types = array('pdf','xls','jpeg','jpg', 'zip','rar','png');
if (!in_array($p_filefilename[1], $allowed_types) {
  // ...
}


(Un-) formatting each form element When we declare something like

$form['textfield'] = array(
  '#type' => 'textfield',
  '#title' => 'textfield title',
  '#maxlength' => 8,
  '#required' => true,
);

The output will be something like:

  textfield title: *
  <input type="text" class="form-text required" value="" size="60" id="edit-textfield" name="textfield" maxlength="8">

However, I am willing to remove the container div and label from some of my fields, something like this:

<input type="text" class="form-text required" value="" size="60" id="edit-textfield" name="textfield" maxlength="8">

Is it possible? Are there any examples somewhere?

You just need to implement hook_theme_registry_alter() to change the theme function that is called when theme('form_element') is invoked; normally the invoked theme function is theme_form_element().

function theme_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  $output = '
\n";
  $required = !empty($element['#required']) ? '*' : '';

  if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= ' ' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
    else {
      $output .= ' ' . $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) . "\n";
    }
  }

  $output .= " $value\n";

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . "
\n";
  }

  $output .= "
\n";

  return $output;
}

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['form_element']) {
    $theme_registry['form_element']['function'] = "theme_mymodule_form_element";
  }
}

Using the code of theme_form_element(), you can write your own theme function, and remove the HTML tags you don't want. Take in mind that theme('form_element') is invoked for every form element output with the form API; if you want to change the HTML output of just a form element, then you need to check the #type value.
theme_textfield() is the theme function that themes a text field, but it doesn't output the label, or the wrapping
, which is already output by theme_form_element().

Alternatively, this can be done in a theme that overrides theme_form_element().
Which approach you should use depends on if you need to alter the output in a specific theme, or for all the themes enabled in your Drupal site; in the latter case, you need to implement the hooks I reported in a module.


Running node creation from another url? I have a node called "survey". To create one, you go to:

/node/add/survey

I want to make a new url at: /make-survey, which must show exactly what you would see at /node/add/survey

What is the easiest way to do this in Drupal 7?

Follow up question:

Once I got the paths right, I now need to change the title. Currently it is "Create Survey" ... i would prefer if it's just "Survey"

Use the built-in aliasing built into the path module:

Navigate to /admin/config/search/path/add
Add /node/add/survey to Existing system path
Add /make-survey to Path alias
Click Save

The new /make-survey alias will now map to your survey add form.


URL alias not working in Contextual filters using node reference field I have a node reference field in views contextual filter and need to filter the list of contents. Url path in views like "node/%/foo " working for me, but the node alias like "/alias/foo" not returning any results . Anyone please suggest for this.

"node/%" is a system path, not an alias. When you use the path "node/%/foo", Drupal looks for an alias of "node/%/foo", and doesn't find one. Next, Drupal will "bubble" your request up to the system menu handler at "node/%" with the path argument of "foo".

When you use the path "alias/foo", Drupal looks for an alias of "alias/foo" but doesn't find one. Drupal does not bubble up your request to "alias".

This is a long-winded way of saying that if you want an alias like "alias/foo", you need to add it yourself. There are many ways to do this, e.g. use rules.


Ajax webform: refresh page on a successful submission I am using the ajax webform, because I don't want the page to be reloaded when the user doesn't enter everything correctly because my form slides in and reloading just causes it to disappear and you would have to navigate back there. When I have ajax-mode enabled, the redirect part works differently, and since the site has only 1 page, it doesn't really do anything, the form doesn't close.

What I want to do it actually refresh the page when the form is submitted with ajax-mode on.

Thus topic has its own issue in the module's issue queue:
Need to get the redirect message of successful webform submission via ajax with ajax_disable_redirect.module

There's a patch but nobody tested it. Maintainer is waitinig for some confirmation. If you need it go for it.


How to customize pager I have a code, that outputs a standard pager:

print theme('pager');

it outputs this:

Pages

1

2

3

next ›

last »

How can I change the HTML to something like this:

&lt;

1

2

3

&gt;

I looked into this thread: https://www.drupal.org/node/387786, created a function bartik_preprocess_custom_pager and a file custom-pager.tpl.php inside my Bartic theme templates, but I can't make it work.

print theme('custom_pager');

outputs nothing. Does anybody know, how can I customize the HTML output for a pager, creating one just for 1 page?

As pointed out in my comment above, most of the details are wrong in your implementation above. Fortunately in Drupal 7, there are six theming functions for the pager:

theme_pager()
theme_pager_first()
theme_pager_link()
theme_pager_last()
theme_pager_previous()
theme_pager_next()

These should allow you to make most of the customizations that you need. There's a good stackexchange answer about how to override Drupal theme functions() that you can refer to for the details.

Finally, you mentioned that you want to override the pager just for one page. I still think this might be worth doing with CSS alone, but in case it's not, you may be able to just override parts of the $variables array in whichever preprocess function contains the pager (I don't know off the top of my head if it's preprocess_page or preprocess_node or if it's accessible from any of the preprocess functions at all).


"Locking" a node after a certain period of time I'd like to be able to have nodes of a certain type "lock" after fifteen minutes, so that for the first fifteen minutes after a node of that type has been created its creator can edit that node, but after that fifteen minutes has passed only users with a specific permission can edit that node.

What's the best way to achieve this result?

You could do something like this:

/**
 * Implements hook_menu_alter
 */
function MY_MODULE_menu_alter(&$items){
  $items['node/%node/edit']['access callback'] = 'MY_MODULE_check_node_access';
}

/**
 * Custom menu access callback for node/%node/edit
 */
function MY_MODULE_check_node_access($op, $node){
  global $user;
  // Note $op and $node are passed in default node_menu access arguments
  // Allow bypass by users with administer nodes permission
  if (($op == 'update') && (!user_access('administer nodes'))) {
    // Allow edit access to node author if within time limit
    if ($user->uid == $node->uid) {
      $limit = variable_get('node_edit_limit', (15 * 60));
      if ((REQUEST_TIME - $node->created) > $limit) {
        drupal_set_message(t('Edit time limit exceeded'));
        return FALSE;
      } else {
        return TRUE;
      }
    }
  }
  // Fallback to regular node_access checks
  return node_access($op, $node);
}


Get the TID from taxonomy view I am using one of the packaged views that comes with the Views module titled 'Taxonomy term' to handle what product looks like when someone searches the taxonomy. Is there a way to grab the tid of the term being viewed from the theme page or node template file?

Edit: Maybe I should explain what I am trying to do. I have a couple of selectmenu (also created by views) that get the terms from a certain taxonomy grouping. When a user selects an option, it takes them to the Taxonomy term view. I need to be able to grab the tid so that I can make a new select menu out of the choice they made.

Application: Let's say a I have a bunch of products in a number of brands. Someone picks a brand. I need a new select menu created for all the product in that brand.

If there is a way to do this in views, that's fine, but if i had the tid, I could just make a module or a function that creates the select menu.

It seems you are looking for Hierarchical Select module.


Weighting Javascript in .info files Drupal 7 adds a new 'weight' option to drupal_add_js so that you can control the order in which Javascript files are added to the page. Is there any way to do this when adding Javascript in .info files?

Despite its instructions to not use it for adding JS to every page, hook_init() will allow you to add JS in an more sophisticated way with drupal_add_js().

That said, it is rare that a JS file must be loaded on EVERY page, so there is likely more optimization you can do. Also see the FAPI property #attached for adding JS to a form.


Override node template depending on menu settings How do I override the template of a node based on where it is in the menu?

For example, I create a node, and within the "Menu settings" I put it under some "parent item". I wish to use a specific template for nodes of a particular content type that fall under a particular parent item.

I believe it is possible to achieve this in hook_preprocess_node by calling menu_get_item, checking whether it is the item you are looking for (checking the parent etc.) and then assigning the appropriate template like this: $vars['template_file'] = 'your_template_file';


Check if translation is new I am working on a module that needs to send push notification through FCM, I use Firebase Push Notification (FCM) for this purpose and it works well.

So what I need to do is to send a push notification when a node of specific content type is created, and it's solved through hook_entity_insert, but problem is that I have multiple languages on site, and it works only when the node is created the first time.

So my question is how to know when translation is created for the first time for a specific node?

For example:

node is created on English (in hook_entity_insert I check if the node
belong to specific content type and call a function to send the notification to all users that have English as user language).
now when we add the translation for other languages, how I can know that it's the first time translation is created, and not updated one?

You can try using hook_entity_translation_insert and use a common logic with hook_entity_insert


Easiest & most efficient way to embed vimeo code into blog post All of my videos are hosted on Vimeo and I would like to create a way to embed videos into my blog posts.

Ideally I'd like to create a field in my content type where all I have to do is input the Vimeo video ID and then the embed code is wrapped around it. This way I don't have to always paste the entire iframe. Or is there a better way?

For example if my Vimeo embed URL is the following, I'd like to only have to input the ID of "60771416"

<iframe src="http://player.vimeo.com/video/60771416?title=0&amp;byline=0&amp;portrait=0&amp;color=ff9933" width="896" height="504" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

I guess I could have a field and have the embed code be in there by default, but I'd like to have it be cleaner then that.

I'm using Drupal 7 and Panels.

I would create a field to input just 60771416 instead of the whole iFrame. Then use the theme_field to wrap with iFrame and set attributes accordingly. Gives me more flexibility for the output. As well as its modular. The Google Analytic module do similar stuff.


Executing a Rule on a user(s) selected from a list I have created a user reference field on a node which lists (via Views) all the users the node author is related to in some way. If there is a better way to list users on node forms then I'm open to suggestions. In my particular case the field uses the autocomplete widget with the Views list, but a select list widget could also be used.

I would like to be able to execute a Rule on the user that is selected in the autocomplete/list by the node author. At the moment I am using the Button Field to trigger the Rule execution but I'm not sure how to get the Rule to apply to the specific chosen user. Some ideas are flagging the user when they are selected or doing a textual comparison between the autocomplete text and existing usernames. I have also tried the Relation module but still can't figure out how to get the selection recognized in Rules.

It sounds to me like you need to fetch the user as an entity in Rules, if you have multiple users use a loop. After this you should be able to apply the relevant action. Here is a stab at the Rule (note, this is untested but should point you in the right direction):

Event
- (Whatever trigger/s you want here)

Condition
- Entity is of type: Node
- Entity has field: (pick the user reference field here)

Action
- Loop(for multiple users)
- (Final action you want to take place. Add the new variable here)

Hope that makes sense. See how you go with this and let me know.


How to turn field_label into an h1 tag I have a content type containing many fields. I want to attach H1, h2, h3, tags to the field_labels of the fields.

Is this possible?
How can I do this?

I am relatively new to Drupal. Thanks.

Yep! This is entirely possible and a very common use case.

If you check out the field.html.twig file in the classy base theme of core, it has the following contents:

{#
/**
 * @file
 * Theme override for a field.
 *
 * To override output, copy the "field.html.twig" from the templates directory
 * to your theme's directory and customize it, just like customizing other
 * Drupal templates such as page.html.twig or node.html.twig.
 *
 * Instead of overriding the theming for all fields, you can also just override
 * theming for a subset of fields using
 * @link themeable Theme hook suggestions. @endlink For example,
 * here are some theme hook suggestions that can be used for a field_foo field
 * on an article node type:
 * - field--node--field-foo--article.html.twig
 * - field--node--field-foo.html.twig
 * - field--node--article.html.twig
 * - field--field-foo.html.twig
 * - field--text-with-summary.html.twig
 * - field.html.twig
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Most themes extend classy as a base. If not, they extend stable by default. Both have a field.html.twig file in their theme folder. Every field in your site will render with this template by default, unless a more specific template is provided by creating a new file and giving it a specific theme name suggestions, which are mentioned in the comments of the file above.

If you copy this file to your theme, you can then override this markup for your theme.

If you enable twig debugging, it will inject template suggestion names into the source as you view the page. These will allow more granular control over field level markup and help figure out what filenames and their order of specificity are in order to override template output.

Let's say you have a field called Company. For this field, you want the label to be an H3. One of the possible template suggestions would be field--field-company.html.twig. If you create that file and place it in your theme, you can do:

{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Note where I changed the label div to an h3. The top part of the if statement is only if you set the label to Hidden in the Display settings of the content type.

Suppose you always want a label to display for Company, you can simplify the template further:

{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{{ label }}

   {% if multiple %}

   {% endif %}
   {% for item in items %}

{{ item.content }}

   {% endfor %}
   {% if multiple %}

   {% endif %}

After clearing the site cache, Drupal should pick up on this new template file, and render any instance of the Company field with it, getting your new label markup. But note, now that you do this change, setting the Company label to hidden in the future will have no effect! We removed the logic - just to illustrate.

That's the nuts and bolts of whats going on and how you can adapt and theme field output, or nodes, taxonomy, user, paragraphs, views, etc.

If you have a lot of fields and this seems overwhelming right now, there is a module called Display Suite that places a lot of this into the admin UI on the field display settings form. If you are new to Drupal 8, twig, etc - Display Suite is a fine starting point because it will accomplish the same thing, just without much, if any, coding.

For Display Suite check the documentation here about fields and labels.

Furthermore, I recommend Drupalize.me's excellent series on theming in Drupal 8. It will help accelerate your knowledge of theming much faster.


Generate automatic URL alias removing words I'm trying to create a topic page for "internet of things", but each time I create the page I notice the URL slug removes the word "of" in it. By default Generate automatic URL alias is checked. The only solution I have found is to uncheck the Generate automatic URL alias option and giving custom url alias. This is a problem since we have alot pages and it's difficult to update it manually. (Some people who make these pages don't have permission to open drupal and push changes from our website). We also run into an issue with symbols # or + or character 'a'.This is restricting the SEO for pages like C#

With just the Path module you can only edit each alias one by one manually.

If you want more control than the Path module allows you can use the Pathauto module. That module has a setting listing all words to exclude from the generated paths. Delete the of and a from that list if that is what you need. There are also options about how to deal with many special characters under Punctuation settings.

Be very careful with the # since it has meaning in URLs, it denotes an ID of an anchor on that page.


How do I customize Display Suite? I know that Display Suite change its features due to limitation of PHP script within DS in Drupal 8.

What I want is customize the uploaded file which display something like this:

Code File: sample_file.zip

Into:

Download Code

In which, Download Code is a link the same with the original output as sample_file.zip.

I created a token field in Display Suite and put the following code to no avail:

Download Code

The output of this is a plain text:

Download Code

Instead of Download Code.

So, how can I link the downloadable File as shown in the image below into something like Download Code with the original link of the file?

The File output (Generic File) is rendered from "file-link.html.twig" template file. To update the Link Text, you can override template_preprocess_file_link() in your theme's themename.theme file. So suppose if my theme name is bartik then function name will be bartik_preprocess_file_link(). Check example below:

use Drupal\Core\Template\Attribute;
use Drupal\file\Entity\File;
use Drupal\Core\Url;

/**
 * Implements hook_preprocess_HOOK() for file-link.html.twig.
 */
function [THEME_NAME]_preprocess_file_link(&$variables) {
  $file = $variables['file'];
  $options = array();

  $file_entity = ($file instanceof File) ? $file : File::load($file->fid);
  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity->getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';

  $mime_type = $file->getMimeType();
  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file->getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    // Add new Link text here.
    $link_text = 'Download Code';
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity->getFilename();
  }

  // Classes to add to the file field for icons.
  $classes = array(
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, array('/' => '-', '.' => '-')),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  );

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']->addClass($classes);

  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}

Or, you can create a custom field formatter which can be selected on Managed Display Page. as per example provided here, Create a custom field formatter.


Google shows node links instead of Custom URL I have got a serious problem. My drupal website was going well. All Links crawled and indexed by Google were custom(natural), But some days ago my website went down because of bandwidth problem. After then, all my links in Google started appearing in /node/number form. e.g I had a link like http://www.myexamplee.com/all-good and now its appearing as http://www.myexamplee.com/node/234 . Can any body help? (I have done autopath tricks, robot.txt node exclusion and clean url like stuff but did not get any results in one week of time). Any expert any paid service any idea will be welcomed.
Many thanks to all readers and experts.

Not sure how google got to index the node/123 URLs. Do you use a sitemap?
I would install the Global Redirect module to make sure those URLs get redirected to the SEO optimized URLs.
Select the "canonical" tag option in the config for that module.

I wouldn't worry to much about the SEO impact, especially if it's a new site.


How to add another filter to TVI default page view? I have the TVI module installed but I wanted to add one more contextual filter
currently: mysite.com/taxonomy/term/[term of tags vocabulary]

what I want: mysite.com/taxonomy/term/[term of tags vocabulary]/[other term of another vocabulary]
How to do this?

You're most of the way there by the look of things, change your page settings -> path to taxonomy/term/%/%

The second % will provide your second contextual filter.


Getting specific property from node_load I have an article that I've set to a variable like this:

$this_node = node_load($nid);

I've done a print_r on $this_node and this is what I get - it's pretty long, sorry:

stdClass Object
(
    [nid] => 67572
    [type] => imagevault
    [language] =>
    [uid] => 3
    [status] => 1
    [created] => 1303347600
    [changed] => 1305662899
    [comment] => 0
    [promote] => 0
    [moderate] => 0
    [sticky] => 1
    [tnid] => 0
    [translate] => 0
    [vid] => 67572
    [revision_uid] => 1
    [title] => Anne Jones
    [body] =>
    [teaser] =>
    [log] =>
    [revision_timestamp] => 1305662899
    [format] => 2
    [name] => pbreen
    [picture] =>
    [data] => a:0:{}
    [field_pub_date] => Array
        (
            [0] => Array
                (
                    [value] =>
                    [timezone] => America/Chicago
                    [timezone_db] => America/Chicago
                    [date_type] => date
                )

        )

    [field_att_file] => Array
        (
            [0] => Array
                (
                    [fid] => 59327
                    [uid] => 3
                    [filename] => KCJones.jpg
                    [filepath] => sites/default/files/images/KCJones.jpg
                    [filemime] => image/jpeg
                    [filesize] => 54806
                    [status] => 1
                    [timestamp] => 1304023490
                    [list] => 1
                    [data] => Array
                        (
                            [description] =>
                        )

                )

        )

    [path] => imagevault/67572

    [0] =>
    [taxonomy] => Array
        (
            [264] => stdClass Object
                (
                    [tid] => 264
                    [vid] => 15
                    [name] => Kimberly-Clark
                    [description] =>
                    [weight] => 0
                )

            [137] => stdClass Object
                (
                    [tid] => 137
                    [vid] => 10
                    [name] => People
                    [description] =>
                    [weight] => 0
                )

        )

)

I know I can get certain values from the node like this:

$imagefile = array();
$imagefile['name'] = $this_node->field_att_file[0]['filename'];

Here's what I need to do, though (and I'm very new to Drupal so forgive me if this is really simple.) The article can, as shown, have multiple taxonomy terms. I need to treat a chunk of display code differently if the article has 137 as one of the taxonomy terms. How would I go about this?

Something like this, or is there a better way? (Don't even know if this way works yet; it probably won't since each tax term is an object, not an array.)

$this_tax = $this_node->taxonomy;
if (array_key_exists('137', $this_tax)) {
   // Do stuff
}

Something like that should actually work.

The only issue might be that you are looking for the string '127' but want the integer 127, so remove the '. But I'm not 100% sure right now how PHP handles that.

Also note that you can use isset() instead of array_key_exists() here, so just

if (isset($this_node->taxonomy[137])) {
}

should work too. The difference between isset and array_key_exists() is that isset() returns FALSE if they key exists but the value of it is NULL, while array_key_exists() returns TRUE in that case.