Inserting submenu to main menu using jquery - good idea? I have main menu showing only first level links (3 items).

**Home**
**Themes**
-green
-blue
-red
**Jokes**
-long
-short
-medium

I am using Menu block module (to show second level items) + Power menu (to make menu items active if current node has certain term).
So when a node with taxonomy "theme" is displayed, the items under "themes" shows up in block menu.

What I would like to do is to somehow inject the block menu items inside primary menu. The main reason is to be able to use responsive menu, that immediately shows user menu options based on node term. (It is more of a usability idea for mobile users - not having to click through full menu).

Question: Do you think it is a good idea to inject such menu using jquery? Or is there a better drupal way of doing this? Thank you

What I would like to do is to somehow inject the block menu items
inside primary menu.
Or is there a better drupal way of doing this?

TB Mega Menu allows you to put blocks and view blocks inside your menus. Perhaps you should consider using this module instead.


How to create a custom resource with Services-3.x Drupal 7.9

I have installed Services 3.x module and can successfully access nodes etc using the rest server e.g. http://api.domain.com/api/rest/node/6.xml. I now wish to create a custom resource and am having difficulty understanding how to do that correctly. I have followed the much-quoted tutorials on this which all seem to be based on the same example: http://drupal.org/node/783460 and am struggling to understand hook_services_resources. For example:

   'note' => array(
     'retrieve' => array(
       'help' => 'Retrieves a note',
       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_noteresource_retrieve',
       'access callback' => '_noteresource_access',
       'access arguments' => array('view'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the note to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         ),
       ),
     ),

Where are the available values for these arrays? For example what are the valid options for source in the args array? I've seen the following: array('path' => '0'), 'data', array('param' => 'page'), 'param'. Where can I find a reference for how this needs to be defined?

To give a bit more information about what I want to achieve, we have a custom form that accepts a series of parameters and returns a set of html-formatted data. The form calls this function:
  return account_manager_search_accounts($billing_party, $other_party, $date_from, $date_to, $billing_id);
}

My idea is to allow users to retrieve the appropriately formatted data (e.g. json, xml) RESTfully and it seemed Services was the right way to do that.

Something like:

function account_manager_services_resources() {
  return array(
   'records' => array(
     'retrieve' => array(
       'help' => 'Retrieves records',
       'file' => array('file' => 'inc', 'module' => 'account_manager'),
       'callback' => '_account_manager_records_retrieve',
       'access callback' => 'user_access',
       'access arguments' => array('view records'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'billing_party',
           'type' => 'varchar',
           'description' => 'The billing party',
           'source' => what should go here,
           'optional' => FALSE,
         ),
         array(
           'name' => 'other_party',
           'type' => 'int',
           'description' => 'The other party',
           'source' => what should go here,
           'optional' => FALSE,
         ),
       ),
     ),
   ),
  );
}

Then I'm not even sure what the URL would be for this. Would it be something like: ./api/rest/account_manager/records

Any suggestions or advice appreciated.

All the documentation for the hook is in the services.services.api.php file included with the module. The args array is:

  an array describing the arguments which should be passed to this resource when it is called. Each element in the array is an associative array containing the following keys:

  name: The name of this argument.
  type: The data type of this argument (int, string, array)
  description: Text describing this argument's usage.
  optional: A boolean indicating whether or not this argument is optional.
  source: Where this argument should be retrieved from. This can be 'data' (indicating the POST data), 'param' (indicating the query string) or 'path' (indicating the url path). In the case of path, an additional parameter must be passed indicating the index to be used.
  default value: this is a value that will be passed to the method for this particular argument if no argument value is passed

There are a fair few examples in that file it might be worth giving them a read through, although the API documentation does actually specifically refer to the link you posted above as a detailed example of creating a new resource.


Best way of having Pathauto based off node title, but not tied to it? Sorry for the poorly worded question, I'll try to better explain myself.

I'm swapping (not migrating) from WP to Drupal and I'm trying to replicate WP's URL feature. I want it to initially be based off the title of the node ("My First Blog Post" => "my-first-blog-post")

What I'm not wanting is Pathauto to be directly linked to the title, so I can update the title to something like "My First Blog Post (Updated 5/4/2017)" without having to worry about the URL changing. I want the URL to be easily editable if the need rises, I just don't want it tied to the title.

Would the best way just be to add an extra field, and manually enter a 'URL title' in there?

The contributed module Pathauto will provide you a setting to set your own alias urls in the add content page.

Suppose you are adding a content of type basic page (using node/add/page), at the bottom there will be an url path settings tab where you can uncheck the 'Generate automatic URL alias' option and set your own path alias for the page.


AJAX form blocks getting internal server error I am trying to add a subscribe button as a block.

I added a form as

class SubscribeTag extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['actions'] = [
      '#type' => 'actions',
    ];

    $form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'wrapper' => 'message-wrapper',
      ],
    ];

    $form['messages'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'message-wrapper'],
    ];

    return $form;
  }

  public function getFormId() {
    return 'skb_subscription';
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message('Thank you for subscribing');
  }

}

It works correctly when a route is defined. When i go to the page /skb_subscribe_form the callback works correctly.

skb_subscription.subscribe:
  path: 'skb_subscribe_form'
  defaults:
    _form:  '\Drupal\skb_subscription\Form\SubscribeTag'
    _title: 'SKB Subscription'
  requirements:
    _permission: 'access content'

But when i try add the form to a block using the code

class SubscribeBlock extends BlockBase {
  public function build() {
    return \Drupal::formBuilder()->getForm("\Drupal\skb_subscription\Form\SubscribeTag");
  }
}

i get the following error "A fatal error occurred: The specified #ajax callback is empty or not callable."

I tried changing the callback with

$form['actions']['ajaxsubmit'] = [
      '#type' => 'submit',
      '#value' => 'Subsscribe',
      '#ajax' => [
        'callback' => '\Drupal\skb_subscription\Form\SubscribeTag::ajaxSubmit ',
        'wrapper' => 'message-wrapper',
      ],
    ];

but still getting the same error.

Try this

$build['form'] = \Drupal::formBuilder()->getForm('\Drupal\skb_subscription\Form\SubscribeTag');
 return $build;


Template conditional based on a list field I have a 'List (text)' field set up with five options displayed as a series of checkboxes.

I would like the last of these checkboxes to control the visibility of a button in the node template.

<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'): ?>
    // do stuff
<?php endif; ?>

The problem with the above is that it only works when this checkbox is the only one selected, otherwise it is no longer the '[0]' result.

How could I go about checking all of the potential five checkboxes for my result?

Thanks!

EDIT

I thought I'd found a horribly verbose workaround by checking every offset one by one like so:

<?php if($node->field_the_checkbox_field['und'][0]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][1]['value'] == 'key_of_checkbox'
    || $node->field_the_checkbox_field['und'][2]['value'] == 'key_of_checkbox'): ?>
        // do stuff
<?php endif; ?>

etc... but, now I get an 'undefined offset' error for each offset that doesn't exist, ie. not all of the boxes will ever be checked, and so there are never usually five results, meaning that when only two of these checkboxes are checked offsets 2 - 4 don't exist. PHP doesn't like that, apparently.

I'm wondering if my problem here is that I should be using five boolean checkboxes, which at least will always return a result one way or another. That seemed messy when I was planning this out, but now it's looking ever more inviting!

EDIT 2

Since I'm short on time, I decided to go with my thoughts above and base my conditionals on single points of data which can either return me a 'true' or 'false' status. My PHP (as you can probably see above) is crappy to say the least - far too crappy to work out how to get around this one. I'd be interested if anyone has any ideas regarding this though!

Thanks for reading.

EXTRA EDITS for clarity and grammar

My php isn't the best, but I think this should work...

You could try using a foreach loop, and using a condition similar to this:

<?php foreach ($node->field_the_checkbox_field['und'] as $thisfield) {
    if($thisfield['value'] == 'key_of_checkbox'):
   // do stuff
} ?>


PDOException: SQLSTATE[HY000] [2002] No such file or directory in lock_may_be_available() (line 167 I have Drupal 7.2 application site and have upgraded from php 5.6 to php 7.2 since it reached its eol, also upgraded to rhel 8 from rhel 6.5, but while connecting to rds I am getting following error, however while trying to connect to db locally, was able to connect successfully. What does this mean and How can I solve this

lock_may_be_available() is the first call that Drupal makes, in order to try a connection with the database. Then, the first idea seems that is not unable connect to your database so your mysql isn't running well or better, your Drupal can't connect to your MySQL server. Ok.

The next step is think'bout the reasons:

1- In some cases, it's just due to use "localhost" instead of 127.0.0.1 in your settings.php or local.settings.php file. Review this in the database config block:

$databases['default']['default'] = [
  'database' => 'db_name',
  'username' => 'db_user',
  'password' => 'db_password',
  'host' => '127.0.0.1',
  'driver' => 'mysql',
  'port' => 3306,
  'prefix' => "",
 ];

In some cases using Containers (Docker, DDEV, etc) may be necessary change as: 'host' => 'localhost', to 'host' => 'mariadb',.

2- Maybe the MySQL daemon is crashing. Stop the daemon and restart it. You can use:       /etc/init.d/mysqld restart
or:  service mysqld restart // service mysql restart.

3- If you're using some special kind of configuration as multisite, multidomain, etc, then get some of log info from your system, using: tail -f /var/log/mysql/error.log


How to stop infinite loop on hook_node_grants I am using hook_node_grants to provide access to a realm based on whether someone is an 'owner' of a node. The issue is that menu_get_object() may call hook_node_grants recursively.

function hottopics_node_grants($account, $op) {
  $grants = array();
  ...
   try {
      $node = menu_get_object();
    } catch (Exception $e) {
      // URL mustn't be the correct format.
      return $grants;
    }
   ...
    // Is the person a member of the administrator group, or the owner of the parent node?
    if (module_invoke('hottopicsresearch', 'display_moderated_research_access_callback', 'update', $node)) {
      $grants['view_hottopics_manager'] = array(1);
    }

    return $grants

The code recurses at $node = menu_get_object(). Drupal-7.

Load the node directly:

  // Do not use $node = menu_get_object();
  // This calls hook_access which results in a recursive loop
  $node_url = $_GET['q'];
  $nid = array_pop(explode('/', $node_url));
  if (!is_integer($nid)) {
    return $grants;
  }
  $node = node_load($nid);


How to pass an argument from the URL to a views exposed filter? I have a view with an exposed filter as a select list.How can I pass to the exposed filter an argument from the URL?The argument is the Taxonomy ID (tid).I want the exposed filter to show every time the same Taxonomy Id as the Tid that exists on the URL.Is this possible?
Thanks

Assuming you are using arguments (contextual filters D7.x) you can make another display that is attached to the main display.  This attached displays should be programmed to provide a summary list when the argument is not present, and to present the list as a jump menu.  You can then set up the jump menu to select the current URL argument (contextual filter). This provides a select menu for an argument, that shows the current argument if it is specified in the URL.  An example of this is the results summary page I created for our club's main fundraising race.

The main view page display has three url arguments: year, race category, and gender. The attached view has year as its first argument and race category as the second argument.  The second argument is programmed to list available categories (for that year since year is a required argument) if no category URL argument has been specified.  When setting up the jump menu settings it was set to "select the current argument".  The attached display is also set not to inherit the parent display's arguments.  That way when we link (main event page) to a specific category results, the selector shows the results filtering taking place and allows people to easily select a different summary.

Note -  this was done in D6.x using Views 2.16

Clarification - it is critical that the attached jump menu display is set not to inherit the parent display's arguments, but that the jump menu is set to display that argument. Otherwise the attached view won't display the jump list when the url argument is present, rather it will display the resulting content (however you set that up).  For my results summary page I had to pass the year argument to the attached jump selector view via PHP - eke!!


Custom module log activity I have a custom module that interacts with some third-party service.
Please look at this function:

function mymodule_connect_entity_update($entity, $type) {
  // Update the entity's entry in a fictional table of all entities.

  //here's some call to external service and I'd like to log results.
}

I want to log information from $entity and other info. I'd like to know what is the best way to do this. This site is hosted on Acquia if it affects the decision.
Someone recommended syslog, but I'm not sure about that, I'd like to have a separate log for this activity.
My idea is to create a custom logger, and configure Linux logrotator to handle rotation. The thing is that I don't have permissions to configure rotator, and I'll have to support my decision in order to convince the System Administrator, and I'd like to know other approaches and their advantages.

For logging you could use Watchdog. The first parameter $type can be used as a filter on the report page which is often handy.


Views Secondary Group I have a View which is a list of stores and for each store I have a list of products. This is a sample as it looks now:

Ken's Store

Products: Doodles
Products: Daddles

Joe's Store

Products: Acme Hammer
Products: Acme Nails

Stores are a content type and products are a content type. Products has an entity reference to stores. The view is set to Unformatted list and grouping by Content title(store). I'd like the view to group products like this:

Ken's Store

Products:
Doodles
Daddles

Joe's Store

Products:
Acme Hammer
Acme Nails

Setting Content Title (products) as the second grouping field only causes a repetitive title without grouping. How do I get the products to group under the store grouping?

You can set grouping after any field in the view at the format settings. This should work for this.


Drupal 7 with Mongodb I am working on Drupal website, and I heard about the MongoDB module. I installed and enabled it, but I don't understand how it works.

How can I switch all my data from MySQL to MongoDB?
Is it safe to purely depend on it? Can anyone tell me how to configure MongoDB with Drupal?

You currently cannot use MongoDB for all your data. The MongoDB module clearly states what it can store in your mongodb: Cache, Field storage, Session, Watchdog, Lock, Block and Queue. This cover most of your site data. But a SQL database will always be needed.

This tutorial gives configuration to put in your site settings.php to enable various MongoDB storage. But it may be outdated.


How do I display an entire node content on the front page? How do I display an entire node content and not just some intro text on the front page? It seems anything I promote to front page, is also truncated and I can't figure out how to turn this off.

The easiest way is to create a view.

Follow these steps:

Download, extract the Views module
Enable the Views UI module and accept enable the modules that provide the dependencies
Go to the views admin page (admin/structure/views)
Enable the frontpage view (click the link)
Edit the frontpage view (click the link)
Under the format heading, there is an option "show" click the teaser link
Change the view mode option to full and untick the show links checkbox
Click the Apply (all displays) button
Click the save button
Visit the site information page (admin/config/system/site-information)
Change the default front page URL to "frontpage" (without the quotes)
Click Save configuration

It show now just work.


Display a thank you message instead of a page redirect after submitting a Webform in a block? I am using the Webform module, and I've created a block containing a webform. When I submit the form, my browser goes to the main url for the webform.

How can I display a thank you message instead?

You can do it, from the webform configuration page: Use Redirection location or Confirmation message.


DrupalGap Frontpage not displaying I am following the drupalgap hello world creation tutorial, however all i tried to make the hello world proven to be unsucessful.

here is the frontpage config fron settings.js

i did the installation on mobile folder and the setting file is settings.js

// App Title
drupalgap.settings.title = 'gsam';

// App Front Page
drupalgap.settings.front = 'hello_world';

the module name is gsam with directory structure:

mobile/app/modules/custom/gsam

and here is my gsam.js,

when every i load my server pointing to the mobile I have 404, that is after i placed this code.

/**
 * Implements hook_menu().
 */
function gsam_menu() {
  var items = {};
  items['hello_world'] = {
    title: 'DrupalGap',
    page_callback: 'gsam_hello_world_page'
  };
  return items;
}

/**
 * The callback for the "Hello World" page.
 */
function gsam_hello_world_page() {
  var content = {};
  content['my_button'] = {
    theme: 'button',
    text: 'Hello World',
    attributes: {
      onclick: "drupalgap_alert('Hi!')"
    }
  };
  return content;
}

One possible reason could be the apparent failure to refer the your custom module in your project settings.js. This file resides in mobile/app/modules/custom/gsam/www/app. Edit the file and add the following code in the custom module section:

Drupal.modules.custom['gsam'] = {};

drupalgap.settings.front = 'hello_world';


How to show picture of the user who triggered the rule for message activity? I am using message module to record user activity on the site and displaying it through views. I am using rules module to trigger actions on certain events and show the relevant message.

How I can show picture of the user who triggered the event?

For example: When my question is liked by clive, I receive a message notification that "Clive liked your question". I only see a plain text. How to show the user picture?

Since you are using Rules to create your messages to be delivered, you can try to make the missing tokens available by using the Replacement patterns for each message type. Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that (it explains how these Replacement tokens can be used to pass data available in Rules to the Message module).

With that, your only remaining challenge is to get access to the user picture in a custom rule. In D8 that picture has become a field also, but that's not the case in D7. Therefor you may get it to work in D7 also if you also use the user picture field module (which doesn't have an official D7 release yet, but about 11K reported installs sounds like it's a pretty stable module).


Menu on the taxonomy term page maybe the solution to my problem is quite simple but I can not find a way on the taxonomy term page to show a menu block!

I use drupal 8 with bartik theme and have a menu based on taxonomic terms (Module: Taxonomy Menu + Menu Block). This menu is also always displayed everywhere (with the set content types). Just not on the taxonomy term page (the page where all entries are displayed from a taxonomy item in a teaser view).

if I look under Structure> Block Layout> Navigation> Configuration: is there "page" there I tried to enter URL of the taxonomy terms or also / * but both remains without effect.

As mentioned in comments if you want it shown everywhere you should untick the Type options, then they apply anyway. And on the Seite delete everything, that should show it everywhere too without restrictions (no need for /*).

But I think your particular configuration isn't working because you have included the /de/ in your path under Seite, the language prefix is not part of the Drupal path. Remove it from there and it should work.

Instead of:

/de/tutorial/erste-schritte

it should say:

/tutorial/erste-schritte

You have the Visibility limited to the German language under the Sprache tab.


Vocabulary terms deleted but still visible I work on a D7 website where some taxonomy terms were created and then deleted.

I’ve build a search form with views based on taxonomy terms (filter criterion: Content: Term name (field_term_name)) and i see some "deleted" terms in filter exposed to visitor.

I’ve check directly in DB and it appears that these datas (which should be completely deleted) are still in taxonomy_term_data.

I do not see these terms in the Drupal admin but I can however still see them in the database, and I can open them directly using the tid in the Drupal interface.

My experience with Drupal let me think that is not a good idea to delete them directly in DB. So how can I proceed ?

taxonomy_term_data is the canonical location for term data so it sounds like there might be other issues going on (a broken admin display, caching, DB corruption via orphaned parent/child term, we can only guess).

If you want a safe way to remove taxonomy, invoke the taxonomy API functions (they are the same tools the admin interface is using) via Devel, drush eval, or some other dev tool where you can execute arbitrary PHP that uses these functions to remove your desired terms:

For example:

$my_bad_tids = [1, 2, 3];
$terms = taxonomy_term_load_multiple($my_bad_tids);
foreach ($terms as $term) {
  taxonomy_term_delete($term->tid);
}


Why using of custom date format makes my Drupal date outdated and does not change at all? I have custom installation profile and I must set date formats programmatically.

I tried:

db_insert('date_formats')
    ->fields(array(
        'format' => $format_long,  // PHP Date String
        'type' => 'custom',          // 'custom'
        'locked' => 0,               // 0 = user-specified date format
    ))
    ->execute();
variable_set('date_format_long', $format_long);

and

$format_long = 'l, Y-m-d G:h';
system_date_format_save(array(
    'is_new' => 1,
    'type' => 'custom',
    'format' => $format_long,
    'locked' => 0,
));

and set this up:

   variable_set('date_format_long', $format_long);
   variable_set('date_format_medium', $format_medium);
   variable_set('date_format_short', $format_short);

At admin/config/regional/date-time all seems to be fine but:

time is e.g 16:04 (now I have 16:38). Time changing, but on settings page time is still the same (after refresh).

I tried to create a content and at admin/content listing I have content updated date as 16:04 too... :(

If I switch to default formats all works ok.

What is wrong?

EDIT

At admin/config/regional/settings time is 16:04 too....

EDIT

I created module based on suggestion from answer, still no luck :(

define('RPKE_DATE_FORMAT_LONG', 'l, Y-m-d G:h');
define('RPKE_DATE_FORMAT_MEDIUM', 'D., Y-m-d G:h');
define('RPKE_DATE_FORMAT_SHORT', 'Y-m-d G:h');
define('RPKE_DATE_DATE_TYPE_LONG', 'rpke_date_long');
define('RPKE_DATE_DATE_TYPE_MEDIUM', 'rpke_date_medium');
define('RPKE_DATE_DATE_TYPE_SHORT', 'rpke_date_short');

/**
 * Implements hook_date_format_types().
 */
function rpke_date_date_format_types() {
    $types = array();
    $types[RPKE_DATE_DATE_TYPE_LONG] = t('Long date format for RPKE');
    $types[RPKE_DATE_DATE_TYPE_MEDIUM] = t('Medium date format for RPKE');
    $types[RPKE_DATE_DATE_TYPE_SHORT] = t('Short date format for RPKE');
    return $types;
}

function rpke_date_date_formats() {
    return array(
        array(
            'type' => RPKE_DATE_DATE_TYPE_LONG,
            'format' => RPKE_DATE_FORMAT_LONG,
            'locales' => array(),
        ),
        array(
            'type' => RPKE_DATE_DATE_TYPE_MEDIUM,
            'format' => RPKE_DATE_FORMAT_MEDIUM,
            'locales' => array(),
        ),
        array(
            'type' => RPKE_DATE_DATE_TYPE_SHORT,
            'format' => RPKE_DATE_FORMAT_SHORT,
            'locales' => array(),
        ),
    );
}

function rpke_date_flush_caches() {
    _rpke_date_purge_date_formats();
}

function _rpke_date_purge_date_formats() {
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_LONG);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_LONG, RPKE_DATE_FORMAT_LONG);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_MEDIUM);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_MEDIUM, RPKE_DATE_FORMAT_MEDIUM);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
    $format = system_get_date_formats(RPKE_DATE_DATE_TYPE_SHORT);
    variable_set('date_format_' . RPKE_DATE_DATE_TYPE_SHORT, RPKE_DATE_FORMAT_SHORT);
    if (!empty($format['dfid'])) {
        system_date_format_delete($format['dfid']);
    }
}

EDIT

The worst nightmare is that creating custom date format from UI (e.g. custom date format in Views) result display of wrong date too....

Instead of manually inserting stuff in the database, make use of the Drupal API. The blog post Exporting and maintaining custom date formats in Drupal 7 is a great tutorial. It's geared towards modules but I'm pretty sure you can do this in an install profile too.

I think this will solve your problem, and even though I'm not 100% sure, I would always recommend to use the API.

Here's a quick copy-paste of the most important code from that blog post, just in case the link would break in the future:

/**
 * Define and export date formats.
 */

// Give the date format type a machine name.
define('MODULENAME_DATE_TYPE', 'MODULENAME_date_type');

// Define the string to be passed to date().
define('MODULENAME_DATE_FORMAT', 'l, jS M Y ');

/**
 * Implements hook_date_formats().
 */
function MODULENAME_date_formats() {
  $formats = array();
  $formats[] = array(
    'type' => MODULENAME_DATE_TYPE,
    'format' => MODULENAME_DATE_FORMAT,
    'locales' => array(),
  );
  return $formats;
}

/**
 * Implements hook_date_format_types().
 */
function MODULENAME_date_format_types() {
  $types = array();
  $types[MODULENAME_DATE_TYPE] = t('Default date for MODULENAME');
  return $types;
}

The blog post also provides a utility function to clean up old, unused date formats:

/**
 * Delete cruft date formats from the database and resync date formats/types.
 *
 * Call this as often as required to ensure date configuration stays in-sync.
 * Don't call this on every page load. hook_flush_caches() or hook_update_N
 * are good candidates.
 */
function _MODULENAME_purge_date_formats() {
  $formats = system_get_date_formats(MODULENAME_DATE_TYPE);
  variable_set('date_format_' . MODULENAME_DATE_TYPE, MODULENAME_DATE_FORMAT);

  // Date formats without a dfid are being read directly from code. We can use
  // the existence of this value to detect "ghost" formats that are not managed
  // in this file.
  if (!empty($format['dfid'])) {
    system_date_format_delete($format['dfid']);
  }
}


How to display certain links in a menu only if a precondition is met? I've added a checkbox to menu creation so that certain items in the menu will be displayed only if that checkbox is ticked (For test user).

That's the theory anyway.
How can I determine if that checkbox is ticked when displaying the menu on a page?
I assume some hook is involved here, but I can't quite figure out which one.
Any nudging in the right direction is more than welcome.

First of all you need to store value of 'For Test User' checkbox as variable OR as separate column in menu_links table.

like variable_set(url, checkbox_value);

By using hook_menu_alter you can check the variable is set for that url. and if its not set you can set $items['url']['access callback'] = FALSE, By setting this menu will not be visible.

Let me know if anything different required.


Another question on Drupal files folder permissions and security So there are the following two posts (among others) that say 755 is okay for the sites/default/files directory:

What are the recommended directory permissions?
Confusion about files permission

I took over a site that was hacked (due to missing a security update and improper Drupal/server configurations), whereby the hacker setup a generic form to download files (.js, .php, etc.) to the default files folder, then presumably they'd be able to execute them by setting up another page on the site that actually loads the file.

They did this by commandeering a site with admin privileges. And while I could not find an actual file they downloaded to the files directory, they did wind up altering the company's homepage with a "You've been hacked" message and an image of a country's flag.

Now to my questions:

Why have 755 on sites/default/files directory (and sub-directories) instead of 744? Isn't the files folder by definition for user files and system caching files? To flip the question around, is there any legitimate reason to allow "x" for the group/other users?
Is the new default .htaccess file (shown below for reference) that gets written to sites/default/files "secure enough" that even if a user hacks the front end or database, they can't really cause much havoc? If not, is there something that can be done to prevent all executables from running within /sites/default/files?

Here's the .htaccess file written by Drupal:

# Turn off all options we don't need.
Options None
Options +FollowSymLinks
# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
# Override the handler again if we're run later in the evaluation list.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>
# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
php_flag engine off
</IfModule>

Why have 755 on sites/default/files directory (and sub-directories) instead of 744? Isn't the files folder by definition for user files and system caching files? To flip the question around, is there any legitimate reason to allow "x" for the group/other users?

Without the "x" being set for a directory, the group/user will not be able to look inside the directory.  So you usually want the "x" bit set for group/users for the directory in order to be able to examine these in the CLI without being root.

  Is the new default .htaccess file (shown below for reference) that gets written to sites/default/files "secure enough" that even if a user hacks the front end or database, they can't really cause much havoc?

IMHO, the Drupal .htaccess is adequate for preventing executables downloaded to the upload from being executed.

However, having this file in place does not protect you from front-end or database exploits. And attackers gaining access to execute PHP from the database can remove or replace it.

So you also want to prevent PHP injected into the datebase from being executed. You do this by removing the core PHP module. Do this:

rm -rf modules/php/

You should never enable this misfeature (it has been removed from core in D8), but by physically removing out, you eliminate the risk of somebody making a succesful SQL injection exploit also being able to execute PHP.

Provided you don't use it (and you shouldn't), and it is already disabled, removing it has no side-effects.


Add a prefix to a views field pre_render Our Drupal distribution is to be used with different currencies defined by a custom variable...when we display nodes in a view with the price field we don't add the currency prefix...i want to add it through im guessing hook_views_pre_render? How can i inject a prefix using my custom variable?

This is what i am thinking:

if (in_array($view->name, $views_with_prices)) {
//dsm($view->result);
foreach ($view->result as $activity) {
  //dsm($activity);
  $price = $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'];
  if ($price != 0) {
    $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'] = variable_get('my_currency') .  $activity->_field_data['nid']['entity']->field_average_price['und'][0]['value'];
  }
}
}

but ideally i'd like to use a specific prefix functionality that comes with cck fields if possible or views equivalent.

I would do it by creating a template file, like views-view-field--fieldname.tpl.php, for the field and add the currency prefix to it.


Where does Commerce Stripe store the plans that are created on my stripe account? I have a stripe account all setup and I have created plans. In Drupal Commerce I have created products, but I realised it should have pulled the "plans" down from stripe. I have also tried the stripe payment module which did pull the plans down, but it would have required a lot of customisation to work well with the roles that we needed to assign per plan.

Where does Commerce Stripe store the plans created on my stripe account?

While I'm not familiar with Stripe, it looks like the commerce_stripe stores the details in the remote Stripe system via the stripe-php library

e.g, in commerce_stripe_submit_form_submit

Stripe_Customer::create
...
Stripe_Customer::retrieve

The other place for payment gateway settings will be on the individual payment method configuration form under Rules.


Get node fields in Rules action programatically How to get node field values and include it the Rules Action? If I have a custom content type that has taxonomy terms, and I want to display these terms in Action. Example output is simply logging the terms.

Event: content type is created
Condition: of node type: custom_content
Action: Log the taxonomy terms

Pseudo code:

 public function execute() {
    $term1 = field_taxonomy1_fromCustomContentType
    $term2 = field_taxonomy2_fromCustomContentType
    $this->setProvidedValue('concatenated', $term1 . $term2);
    \Drupal::logger('custom_rules')->notice("Rules Action");
  }

Just in case someone had the same approach as mine. Here is the solution from Drupal.org community.


Double content paths ubercart D7 I'm using Drupal 7 and Ubercart 3. Using pathauto I generate clean url's. However there are two paths to my catalog pages.

product_main_category/category

product_main_category/category-0

I think it has something to do with the fact that there is a catalog path and a taxonomy path, but i don't know why. My installation is very basic so i would assume a lot of people should have seen this problem before.

This problem arises because the Ubercart Catalog takes over the display of the taxonomy term pages for the Catalog vocabulary, as well as creating its own set of URL aliases for the Catalog terms.

I solved this problem quite simply, by disabling Ubercart's Catalog module and deleting all the aliases for the Catalog terms (as opposed to the Catalog taxonomy terms).

To achieve this, I had to:

create a new view that mimicked the the Catalog
ensure that the Catalog term pages used my new view. There are various ways to do this in Drupal including overriding the taxonomy default view, enabling a module like TVI, and Panels. I prefer Panels, so that's the route I took.
Optional - replace the Catalog block (which is useful as a sidebar menu for your Ubercart store). I did this using Taxonomy Menu and Menu Block.
Deleting all the aliases for the Catalog and Catalog Taxonomy, and bulk regenerating the Catalog Taxonomy aliases.

In the end, my site looked the same as it did before, but I no longer have the duplicate URL problem, and I'm no longer tied to the rather awkward Catalog module in Ubercart.


What might cause my "User error" in Watchdog? I'm trying to figure out the reason behind this "User error" in watchdog

User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 102 of /core/lib/Drupal/Core/Render/Element.php).

This error comes when I access any non-existing entity like

myentity/762574527 or myentity/anything

On googling, I got this link , which states its due to Token module.

I uninstalled this module and deleted every content related to it, still this error persists.

Can anyone tell the reason behind this error?

This is not connected to the Token module.

You should not try to render a non existing entity. Your code should throw an exception instead:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

  throw new NotFoundHttpException();

Or configure the route so that when you have a non existing entity as parameter in the route, drupal will throw this exception automatically. See the answer from Berdir to your last question:

https://drupal.stackexchange.com/a/205054/47547


How to access from node template a field added by module I have a content type that has a custom template. My content type is article and I have a node--article.tpl.php that displays the following.

<?php
    print render($content['field_image']);
    print render($content['body']);
?>

I have a module that adds a featured image to each node if it is made a featured node in its options. I believe this is the code in the module that is causing it but I'm not positive.

function featured_nodes_field_extra_fields() {
  $extra = array();
  // Get feature types from the database.
  $featured_node_types = db_select('featured_nodes_types', 't')
    ->fields('t')
    ->execute()
    ->fetchAllAssoc('machine_name');

  foreach($featured_node_types as $type => $feature) {
    foreach (node_type_get_names() as $name => $value) {
      $extra['node'][$name] = array(
        'display' => array(
          'featured_nodes_' . $type => array(
            'label' => $feature->label . ' - featured image',
            'description' => t('If this node is featured, display the associated image.'),
            'weight' => -10,
          )
        ),
      );
    }
  }
  return $extra;
}

function featured_nodes_node_view($node, $view_mode, $langcode) {
  if (!empty($node->featured_node)) {
    foreach ($node->featured_node as $delta => $values) {
      $node->content['featured_nodes_' . $values['feature_type']] = array(
        '#theme' => 'featured_node_image',
        '#node' => $node,
        '#view_mode' => $view_mode,
        '#db_values' => $values,
      );
    }
  }
}

Despite my attempts I have not been able to print the featured image from node--article.tpl.php but I believe I got close. When I added

print render($featured_node[0]['image']);

It displayed 10080. And a unique number on each featured node. Possibly the field's id. But I was still unable to produce the image. Any ideas?

I managed to figure it out. I found a location in the module with this code.

function theme_featured_node_image($variables) {
  $fid = $variables['element']['#db_values']['image'];
  $file = file_load($fid);
  $url = file_create_url($file->uri);
  return theme('image', array('attributes' => array(), 'path' => $url));
}

Then I wrote

$file = file_load($featured_node[0]['image']);
$url = file_create_url($file->uri);
print '<img src="'.$url.'">';

Which allowed me to print the image.


How to pass negative values to config-set It seems that we can't set negative values with config-set:

drush cset block.block.myblock_name weight '-1' --format=string -y

doesn't work

The (ugly) work-around is:

echo '-1' | drush cset block.block.myblock_name weight - -y

You don't need to specify that format is string as that is the default.

This seems to be a general problem with Drush commands; values starting with a dash is interpreted as arguments. See bug report for similar issue with vset - https://github.com/drush-ops/drush/issues/378


Authentication by MAC address I want to show view content only to authenticate devices,
So I have a plan to add a custom field for users and add MAC address of authenticated device in it, send MAC address of device via GET/POST method to view and if the MAC address is valid show contents!
Sending MAC address using GET/POST method is not a big problem :) (Already done)
But I don't know how can I authenticate in views side!
is there any module or custom code or something like that to check if MAC address validated show view content ?

Thanks a lot :)

You will have to override the access callback used for your view pages using an hook_menu_alter implementation (from a custom module) to use a custom one that will do the MAC address check.

Assuming the MAC address is provided as an HTTP header, this would look like.

/**
 * Implements hook_menu_alter().
 */
function MODULE_menu_alter($items) {
  if (!isset($items['protected/view/path']['access arguments'])) {
    $items['protected/view/path']['access arguments'] = array($items['protected/view/path']['access callback']);
  }
  else {
    array_push($items['protected/view/path']['access arguments'], $items['protected/view/path']['access callback']);
  }
  $items['protected/view/path']['access callback'] = 'MODULE_menu_access';
}

/**
 * Return whether or not the request contains an authorized MAC address header.
 */
function MODULE_menu_access() {
  $mac_address = $_SERVER['HTTP_MAC_ADDRESS'];

  // Validate the MAC address.
  if (!MODULE_mac_is_authorized($mac_address)) {
    return false;
  }

  // Return the result of the original access callback
  $args = func_get_args();
  $access_callback = array_pop($args);
  return call_user_func_array($access_callback, $args);
}


Feasability of module or submodule for user picture migration It seems like there would be a fairly large number of Drupal 6 websites with user pictures that will need to be migrated to Drupal 7 at some point and that the difficulty of migration might be keeping some sites from migrating.

There are various posts here and there about the code needed to migrate user photos but this may be daunting to some users. Would it be difficult to create a module that the user could configure with source and target directories using the configuration menu and that would then perform the migration, so that user could avoid getting into Drupal's internals?

It would also be nice if drush could be used for this migration, but the solution above would probably be accessible to more users.

I'm not a developer, so creating and maintaining a module seems to be more than I could commit to, but I'm wondering whether this would be easy for someone with more experience.

I hadn't realized that the dev versions of migrate and migrate_d2d now support migrating user pictures.

The UI asks for the location for files in the installation one is migrating from. In my case, pictures were stored under files/pictures but I only had to specify "...files". I don't know if it would work if user pictures are stored in a directory with a different name.

In any case, once I switched to the dev versions, it seemed to work.


How to move the comment form to the top? Per default in Drupal 8 the comment form is rendered below the comments. In Drupal 7 you could move the comment form from the bottom to the top by modifying the comment-wrapper.tpl.php.

Is there also a way in Drupal 8 to get this functionality?

You can in field--comment.html.twig

{#
/**
 * @file
 * Default theme override for comment fields.
 *
 * 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.
 * - title_prefix: Additional output populated by modules, intended to be
 *   displayed in front of the main title tag that appears in the template.
 * - title_suffix: Additional title output populated by modules, intended to
 *   be displayed after the main title tag that appears in the template.
 * - comments: List of comments rendered through comment.html.twig.
 * - content_attributes: HTML attributes for the form title.
 * - comment_form: The 'Add new comment' form.
 * - comment_display_mode: Is the comments are threaded.
 * - comment_type: The comment type bundle ID for the comment field.
 * - 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()
 * @see comment_preprocess_field()
 */
#}

  {% if comments and not label_hidden %}
    {{ title_prefix }}

{{ label }}

    {{ title_suffix }}
  {% endif %}

  {{ comments }}

  {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}

So copy the above code and go to /themes/YOURTHEME/templates folder and create field--comment.html.twig and now paste code.

Now, all you gotta do is just move

 {% if comment_form %}

{{ 'Add new comment'|t }}

    {{ comment_form }}
  {% endif %}

and place it above the {{ comments }} line

Flush/Clear the cache to see changes.


Ubercart entries in menu_links table causing performance issues Drupal 6:
I have found around 130 entries in the menu_links table such as:

user/123/order
user/5a9689f90da4d0d012de104d7da67a8b/order/
user/123/order//invoice

These entries cause a user_load to happen which seems to be irrespective of which user is logged in.

Deleting these entries results in around 1000 less queries being run on a page load.

My question is, is it safe to delete these entries and how would they have ended up in the menu_links table in the first place?

Can you give this patch a try? I can't answer you're question directly but I think this might help with all the user loads http://drupal.org/node/1710656#comment-6474030


Errors when attempting to load Salesforce object from mapping admin page We are attempting to push a content type from our Drupal site to a Salesforce object. We have successfully authorized the link between them. When we attempt to start the mapping, we get an AJAX error. I believe the AJAX error is just a symptom of the real error that occurs within the Salesforce module so I am not providing much about it.

In the logs after the error has been triggered, the drupal log shows 2 errors:

Notice: Undefined offset: 8 in salesforce_mapping_form_validate() (line 590 of /.../sites/all/modules/contrib/salesforce/modules/salesforce_mapping/includes/salesforce_mapping.admin.inc).

and

Warning: Invalid argument supplied for foreach() in form_type_checkboxes_value() (line 2394 of /home/tim/projects/lca/includes/form.inc).

I have attempted to use xdebug to watch this process as it works its way through the salesforce_mapping.admin.inc processes, but nothing has jumped out at me. In the end, phpStorm runs out of memory and stops processing the request. The next page load of drupal crashes the browser window as well leading me to believe there is some sort of recursive error happening.

I have searched this modules issue queue and the interwebs extensively, but nothing fits our situation. Please let me know if I can provide further information for you or can otherwise assist.

I found the issue. For anyone in the future running into this error, I found that you must have both the push and pull submodules enabled for the mapping to work. I was only planning to push records into Salesforce so I mistakenly assumed I didn't need the pull modules enabled. With it enabled, the mapping worked like a champ.


How to change the date format in the date field as a select list? On user registration page, I have added a date field in select list.

In the manage form display tab, I can set the order of the dropdown fields like day/month/year or month/day/year But I am unable to change the format of the date.

Currently in the day dropdown, it is displaying like 1, 2, 3 and I want to change it to 01, 02, 03. Similarly in the month dropdown, it is displaying like, Jan, Feb and I want to display it like January, February.

Is this possible?

If you want to alter the way this component is shown globally, you can implement hook_preprocess_datetime_form(), eg. like this:

function mymodule_preprocess_datetime_form(&$variables) {
  // Ensure there's a month field and it's a select.
  if (isset($variables["content"]["month"]) && $variables["content"]["month"]['#type'] === 'select') {
    foreach ($variables["content"]["month"]['#options'] as $monthNum => $label) {
      if ($monthNum) {
        // Convert month number to unabbreviated name.
        $dateObj = DateTime::createFromFormat('!m', $monthNum);
        $monthName = $dateObj->format('F');
        $variables["content"]["month"]['#options'][$monthNum] = $monthName;
  }
}

}

The code for the day select will be similar.


Establish relationship between two text fields I am stuck in a strange issue. I have two content types twilio  and call recordings. Both content types have caller phone number in common

Recording

Twilio

Now I would like to generate a report using views which can select field between two content types based on phone number.

In non Drupal terms I want inner join based on two text fields.

How can I achieve this?

Both content types have to share a field, in the same way a both the database tables used in a INNER JOIN have to share a common field for the join to work.

In Drupal, this is easy as you can reuse fields between your content types and in this wway joining the content types will be super simple with Views.

Current setup:

  Recording: field_called_phone, field_caller_phone

  Twilio: field_phone_number

Suggested setup:

  Recording: field_called_phone, field_phone_number

  Twilio: field_phone_number


How to get values after form submit I created on custom module to generate a form with this code

function report_page_form_form($form, &$form_state) {
    $meberArr = array();
    $form['field_member_org']=array(
        '#type'=>'select',
        '#options'=> $meberArr,
    );
    $form['field_start_date'] = array(
      '#date_format' => 'Y-m-d',
      '#type' => 'date_popup',
      '#weight'=>0,
    );
    $form['field_end_date'] = array(
      '#date_format' => 'Y-m-d',
      '#type' => 'date_popup',
      '#weight'=>0,
    );
// Provide a submit button.
          $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Filter',
          );
return $form;
 }

In one of my node--nid.tpl.php, I am rendering this form as

 $arr = drupal_get_form('report_page_form_form');
 print drupal_render($arr);

I am writing an SQL query in the same node--nid.tpl.php file to fetch data from DB.

SELECT TITLE FROM REPORT WHERE ....

I need to pass form submitted values to this query. Can anyone help me to do it.

You would get the values of the submitted form in hook_form_submit

function MY_MODULE_NAME_form_submit($form, &$form_state) {
         //your code here
        }

You would get all the required values in $form_state['values']


Commerce Products Display Page Using Views The usual way to display Commerce products is

1. Create Products using Commerce Module Interface

2. Create a Content  Type for Products Line Items by referencing the products

But I have too many different products... should I have to create contents after adding each commerce Products??

I used two views for each products one to create a products listing and other for product display page using contextual filters and by passing the Product ID

Product Listing Page path : /products-list

Product Display Page      : /products/product1

By passing the product ID via URL.

Is this a write way to do it... Or is there anything efficient and meaningful than this method?

You can use this module "https://www.drupal.org/project/commerce_auto_product_display". then you can use Views to show the product display nodes.


Use VBO to send tokenised email in Drupal 6 I have a view table with bulk operations, and I have enabled the send tokenised email field. What I want to do with this is when this is selected and executed, it will take the email of the node which I have selected and send a mail with some content in it to the user. (e.g. we are looking at your support ticket).
When I select a node in the table currently, select send tokenised email from the dropdown and click execute, it does nothing.

The Views Send module solved my issue.

  Views Send enables you to send mass mailing from a View.


Why don't CAS users show up in users_field_data? I have a simple multisite setup in Drupal 8. I installed the CAS module and verified that at least one user logged in successfully using our university's CAS server.

I can see the user at /admin/people, but I cannot see his entry in the database. I looked in the tables users, users_data, and users_field_data, and all I can see is the admin user (me).

Where are the users located in the database?

I need to know for a custom module I am developing. FWIW I do have "Auto Register Users" enabled in the module configuration.

For D8, CAS requires External Authentication module.

External Authentication maintains a db table called authmap.
CAS maintains a table named cas_login_data.

I suspect the data you're looking for is in one of those tables.


Automatically add class to  to WYSIWYG Is it possible to automatically add a class to each <ul> element added to the CKEditor WYSIWYG?

In my project, I decided to not style ul > li in order to not have to rewrite CSS for each ul Drupal can display (i.e. menus or contextual links). So, I have only one CSS rule for my unordered lists: ul.my_custom_class li. I used to add a custom style in CKEditor's Styles dropdown that add this class, but it's not a perfect solution, as some administrators forget to use it (or sometimes, CKEditor does not recognize ul ou a since Drupal 8.4.x, see this thread).

The perfect solution would be that, each time you add an unordered list into the WYSIWYG, instead of having ul li, you'd have ul.my_custom_class li. I know I can use an other CSS rules like .ckeditor ul to make it work, but I want to be able to use this specific class anywhere in the website.

I've found some methods in the CKEditor docs but I don't really know where to use them on Drupal 8.

According to your description, you want to automatically add the class to all lists within the CKEditor content for better theming.

I suggest not doing so within the CKEditor. Use a custom text filter instead. This avoids users accidentially forgetting to add the class manually and keeps your database stored contents cleaner.

The custom filter could parse the content and automatically add the classes when the text format is rendered. A good guide on getting started with creating custom text filters is this one: https://www.lullabot.com/articles/creating-a-custom-filter-in-drupal-8

In your process method you should use a simple DOM parser to add classes to all ul tags (not tested though, just for illustration):

namespace Drupal\my_module\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Drupal 8 filter to automatically add class to unnumbered lists.
 *
 * @Filter(
 *   id = "my_lists_filter",
 *   title = @Translation("My lists filter"),
 *   description = @Translation("Automatically adds my_class to unnumbered lists."),
 *   type = \Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class MyListsFilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    // Create DOM document.
    $dom = Html::load($text);

    // Get all UL tags.
    $lists_query = '//ul';

    // Get DOM nodes from XPath query.
    $xpath = new \DOMXPath($dom);
    $nodes = $xpath->query($lists_query);
    // Whether we have results.
    if ($nodes->length > 0) {
      // Iterate over list elements and add our class.
      foreach ($nodes as $node) {
        $classes = explode(' ', $node->getAttribute('class'));
        $classes[] = 'my_class';
        $node->setAttribute('class', join(' ', array_unique($classes)));
      }
    }

    return new FilterProcessResult(Html::serialize($dom));
  }

}


HTML inside mini-pager navigation control labels I'm trying to customize the output of the mini-pager controller (the "next" and "previous" link with arrows) in a view.
Actually, it is possible to insert custom text for "previous"-link in the view pager options, in the "tag" section.
I tried to add inside the form (for a test), this:

The resulting output is

&lt;i class="icon-chevron-right"&gt;&lt;/i&gt;

So actually I think it filters HTML.
Do you think it's possible to include HTML?

I just spent the last 2 hours trying to solve the same problem, using many different approaches, but I finally managed to get it right.

You just have to override the theme_pager_link function in your theme by copying the code content to template.php and change the return (last line), removing the check_plain() function of the $text variable, leaving it like:

return '<a' . drupal_attributes($attributes) . '>' . $text . '</a>';


Find a node/page in admin by looking at the code I'm very new to Drupal, and I want to edit some text on the front page. In the page.tpl.php, I have this code print render($page['content']), if I remove it, then the area that I want to edit with is disappeared from the front page, so I know this is the right part, but how can I find out which page, content, or node is being called in the backend?

I'm using Drupal 7.55.

I'd recommend installing the Devel module and enabling Webprofiler. It gives you a lot of useful meta information about the current request, including the controller and route used:


Views sorting a custom field I've added a custom field to my view using hook_views_data:

/**
 * Implements hook_views_data().
 */
function homepage_views_data() {
  $data['homepage']['table']['group'] = t('Recency field');
  $data['homepage']['table']['join'] = array(
    // Exist in all views.
    '#global' => array(),
  );

  $data['homepage']['recency_field'] = array(
    'title' => t('Recency'),
    'help' => t('Display a calculated recency date'),
    'field' => array(
      'handler' => 'views_handler_recency_field',
      'click sortable' => TRUE,
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date',
    ),
  );

  return $data;
}

Right now, my field is simply returning the value of node_created. In my field handler:

/**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $output = $values->node_created;
    return $output;
  }

I can add my custom field to a View no problem. But after adding it as a sort field, I get:

  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'recency_field'
  in 'field list'

The query looks like this:

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, recency_field AS recency_field
FROM
{node} node
WHERE (( (node.status = '1') ))
ORDER BY recency_field ASC

Does views_handler_sort_date need to work with a real database value?

I believe views lets the database do the sorting, so unless your field exists inside the database, the database controller won't recognise it which is what your error message basically says.


Convert http to https on save While migrating our site, we have put them on 'SSL required'.

How can we best force, when editors save datas containing http link, a conversion to https ( or //).

i did a module with a custom text format filter :

function my_module_filter_info() {
   $filters ['to_https_compatible_converter'] = array (
        'title' => t ( 'HTTPS compatible convertible filter' ),
        'description' => t ( 'convert http:// to // for https  compatiblity' ),
        'process callback' => '_module_filter_process',
        'tips callback' => '_module_filter_tips'
   );
  return $filters;
 }

 function _module_filter_tips($filter, $format, $long = FALSE) {
switch ($filter->name) {
    case 'to_https_compatible_converter' :
        return t ( 'convert http:// to // for https  compatiblity' );
}
    }

  function _module_filter_process($text, $filter) {
      switch ($filter->name) {
    case 'to_https_compatible_converter' :

        $dom = new DOMDocument ();
        @$dom->loadHTML ( utf8_decode ( $text ) );

        $images = $dom->getElementsByTagName ( 'img' );
        foreach ( $images as $image ) {
            $image_src = $image->getAttribute ( 'src' );
            $image_src=str_replace(['http://','https://'],'//',$image_src);
            $image->setAttribute ( 'src' ,$image_src);

        }

        $links = $dom->getElementsByTagName ( 'a' );
        foreach ( $links as $link ) {
            $href = $link->getAttribute ( 'href' );
            $href=str_replace(['http://','https://'],'//',$href);
            $link->setAttribute ( 'href' ,$href);

        }

        $iframes = $dom->getElementsByTagName ( 'iframe' );
        foreach ( $iframes as $iframe ) {
            $src = $iframe->getAttribute ( 'src' );
            $src=str_replace(['http://','https://'],'//',$src);
            $iframe->setAttribute ( 'src' ,$src);
        }

        return $dom->saveHTML ();

}
 }


How do I run PHP code when visiting a specific URL? In Drupal 8, I want to visit a link (e.g. www.domain.com/url-link) which should activate PHP code which is in a module.

Is there a hook which support this? If so, how do I implement this?

Apart from controllers, one could also listen for Events,  using code similar to the following. Depending on what the custom logic mentioned in the OP is expected to do, this could be an alternative answer.

nncbt.services.yml:

services:
  nncbt_event_subscriber:
    class: '\Drupal\nncbt\EventSubscriber\NNCBTSubscriber'
    arguments:
      - '@logger.factory'
    tags:
      - { name: 'event_subscriber' }

src/EventSubscriber/NNCBTSubscriber.php:

<?php

namespace Drupal\nncbt\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Drupal\Core\Logger\LoggerChannelFactory;

/**
 * An EventSubscriber for REQUEST and TERMINATE events.
 */
class NNCBTSubscriber implements EventSubscriberInterface {

  /**
   * The logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactory $logger_channel_factory
   *   For logging purposes.
   */
  public function __construct(LoggerChannelFactory $logger_channel_factory) {
    $this->logger = $logger_channel_factory->get(self::class);
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['earlyCode'];
    $events[KernelEvents::TERMINATE][] = ['lateCode'];
    return $events;
  }

  /**
   * This method is called for KernelEvents::REQUEST events.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The incoming event.
   */
  public function earlyCode(GetResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

  /**
   * This method is called for KernelEvents::TERMINATE events.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The incoming event.
   */
  public function lateCode(PostResponseEvent $event) {
    $uri = $event->getRequest()->getRequestUri();
    $this->logger->info($uri);
  }

}

Good luck!


Customizing a Views HTML I'll start off saying I'm pretty new to Drupal.
I'm trying to customize the way a view displays. I want it to look like the Industry News section on this page: http://www.silverfishdevelopment.com/clients/maafs

However I'm confused as to what I want to actually edit. Do I want to create a custom views-view.tpl.php file? Or style output, or row style, etc?

And if I create a new tpl file, what are the variables I can use?

I was trying to follow this: http://www.wdtutorials.com/2011/06/29/drupal-7-how-create-custom-template-view#.VPXOIXXN9cY but couldn't get it to print out the $fields data.

Or am I approaching this all wrong?

If you know of a great tutorial too I'd appreciate that as well.
I'm a little overwhelmed with all of it. Thanks for any help you can give.

I found that Semantic Views worked best for me in this situation. It cuts down on the amount of HTML outputted by Drupal Views and allows you to define the HTML tag that wraps each field as well as add a CSS class.


Search module is not working with all content types In my drupal, i have a search module. This module is not working with all content. For example i have a view. This view's show us announcement.
When i was trying to search this content type, there is no result.

I'd tried reindex (/admin/config/search/settings)

So can someone give me an idea?

Default behavior of search module is, it search all the content type contents. If you tried to search with content type name then it is not working, because it is not the search module functionality.


Which entity to check in Rules to disallow taking a Quiz after passing it? I need a way to restrict Quiz  access for users who have achieved a passing grade to stop them retaking the quiz to gain more user points.

It displays "You have already passed this Quiz.", but I can't find an entity to check for it with the Rules module. Previous quiz result fields always return 0 which makes them worthless. Assigning roles won't work because I want to have quizzes daily.

Any hints?

PS: I'm using Quiz 7.x-5.1

Even though the Quiz 7.x-5.x release comes with lots of new Rules capabilities, I've not found any entity to check if a user already passed some quiz. However, using the Flag module you can implement an appropriate flag, and then just check if the quiz node (an entity ...) was flagged by the current user. Read on for how to do so ...

Step 1 - Create a flag for tracking Passed Quizes

Use the Flag module to create a flag labeled (e.g) Passed Quizes. Here is an export of the flag I used for this (you should be able to import it in your own site also):

$flags = array();
// Exported flag: "Passed Quizes".
$flags['passed_quizes'] = array (
  'entity_type' => 'node',
  'title' => 'Passed Quizes',
  'global' => '0',
  'types' =>
  array (
    0 => 'quiz',
  ),
  'flag_short' => 'Flag this item',
  'flag_long' => '',
  'flag_message' => '',
  'unflag_short' => 'Unflag this item',
  'unflag_long' => '',
  'unflag_message' => '',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
    'teaser' => 'teaser',
    'rss' => 0,
    'search_index' => 0,
    'search_result' => 0,
    'answers_full_node' => 0,
    'print' => 0,
    'question' => 0,
    'token' => 0,
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'i18n' => 0,
  'api_version' => 3,
);
return $flags;

This flag will be used in the custom rule, detailed in the next step.

Step 2 - Flag a Quiz node after passing the quiz

Create a custom rule to flag the quiz node (using the flag from Step 1) after a user passed the quiz and which looks like so (in Rules export format):

{ "rules_flag_a_quiz_when_passed_the_very_first_time" : {
    "LABEL" : "Flag a quiz when passed the very first time",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_update" : [], "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } },
      { "NOT data_is" : {
          "data" : [ "quiz-result:score" ],
          "op" : "\u003C",
          "value" : [ "quiz-result:nid:quiz:pass-rate" ]
        }
      },
      { "NOT flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Congratulations, this is the FIRST time you passed this quiz (with a score of [quiz-result:score] %, whereas the pass rate is [quiz-result:nid:quiz:pass-rate] %)." } },
      { "flag_flagnode" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

Step 3 - Create a rule to disallow taking a passed quiz again

Here is a rule which illustrates how to resolve the challenge in your question:

{ "rules_disallow_taking_a_passed_quiz_again" : {
    "LABEL" : "Disallow taking a passed quiz again",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag", "entity" ],
    "ON" : { "quiz_result_insert" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "quiz-result:nid" ], "type" : "node" } },
      { "flag_flagged_node" : {
          "flag" : "passed_quizes",
          "node" : [ "quiz-result:nid" ],
          "flagging_user" : [ "site:current-user" ]
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "quiz-result" ] } },
      { "drupal_message" : {
          "message" : "You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...",
          "type" : "warning"
        }
      },
      { "redirect" : { "url" : "[quiz-result:nid:url]\/quiz-results" } }
    ]
  }
}

Here are the critical pieces of this rule to make Rules-magic happen:

The Rules Event "After saving a new Quiz result" is what gets triggered right after a user attempts to start taking a quiz (a first time, or another time), so even before the first question of a quiz is shown.
The first Rules Condition, which is "the" way to get access to all sorts of data about the quiz node itself (starting from "a" quiz result).
The last Rules Condition, which verifies if the quiz node (to which this quiz result relates) is already flagged (by the flag from Step 1), which indicates this user already passed this quiz.

If all Rules Conditions are satisfied, then these Rules Actions will be executed:

Delete the newly created "quiz result" entity (this is needed, otherwise if the user would try another time to take the quiz, it would be considered as an attempt to resume taking the quiz, starting from the very first question, and the used Rules Event would NOT (repeat: NOT) be triggered ...).
Show an appropriate message.
Perform a redirect (to show the result summary of the quiz for the current user), to relative path node/nid/quiz-results (using nid as the node id of the quiz).

Use the Rules UI to import the above 2 rules in your own site, after you completed Step 1.

Showtime

Here is a sample of a warning message I received after passing a quiz, and trying to take the quiz again:

  You already took (and passed) this quiz. Your new attempt to take it again has been disregarded and you have been redirected to your results summary ...


Load menu items from one menu in other menu I want to load the menu items from the main menu in a other menu. I've read a dozen examples but I can't get it to render the items at all.

Here's my code from my_theme.theme

function my_theme_menu__secondary(&$menu, &$menu_name, &$suggestions) {
  $menu_name = 'main';
  $menu_tree = \Drupal::menuTree();
  $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
  $parameters->onlyEnabledLinks();
//  $parameters->setMinDepth(2)();
//  $parameters->setMaxDepth(2)();

  $tree = $menu_tree->load($menu_name, $parameters);
  $manipulators = array(
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );

  $tree = $menu_tree->transform($tree, $manipulators);

  $list = [];

  foreach ($tree as $item) {
    $title = $item->link->getTitle();
    $url = $item->link->getUrlObject();
    $list[] = Drupal\Core\Link::fromTextAndUrl($title, $url);
  }

  return $list;
}

Heres my menu--secondary.html.twig

{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if list %}
    {% for item in list %}
      {%
        set item_classes = [
          'expanded',
          'dropdown',
          item.in_active_trail ? 'active',
        ]
      %}
      {% if menu_level == 0  %}

        {{ item.title }}

      {% endif %}
    {% endfor %}
  {% endif %}
{% endmacro %}

Any help is appreciated :)

you can add new module twig tweak, after rendering blocks menu with Twig Tweak on template.


How can I see the query that's being run? I'm using hook_views_query_alter(), and I'd really like to print somewhere (screen, error log, whatever) the query that's being run based on the alterations. I've tried dpm($query), but that gives me the whole krumo tree - all I want is the query - i.e. "select x, y from z where a = 2". Possible?

The views_plugin_query_default class has a query() method that will take the parameters currently held in the object and provide you with a standard SelectQuery (un-executed of course).

Since the SelectQuery class implements the magic __toString() method you can then cast it directly to a string, which will be the SQL query itself:

$select_query = $query->query();
$query_string = (string)$select_query;
dpm($query_string);


Get current country pathPrefix How can I get current country pathPrefix in D8 ?

I know drupalSettings.path.pathPrefix gives that in JS, but how can I get it in preprocess hook ?

Following gives only the path alias, but without pathPrefix.

\Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid[0]);

You can call PathProcessorManager::processOutbound() for the internal path and you get the path alias and the prefix at the same time:

$options = ['prefix' => ''];
$path = \Drupal::service('path_processor_manager')->processOutbound('/node/1', $options);
$prefix = $options['prefix'];


Distance to shop long/lat I want to create a filter where companies are able to find users within eg. 10 kilometers using users added long/lat and the company's long/lat they have added.

I am using geolocation but how am I going to go about this?

As Jimajamma pointed out, the Location module along with Views will allow you to filter by distance. I am currently using zipcodes to filter by, but one could do geocoordinates as well.

Here is a step by step article on how to achieve filtering.  Although the article is a tad old, it is still relevant and can easily be adapted for drupal 7.

http://drupal.org/node/359463


Does ajax used in views call preprocessing hooks? I have a view with a bunch of fields and I'm styling those fields in:

views-view-fields.html.twig

In my .theme file I'm also using a preprocess function to pass additional variables to the above template.

function theme_preprocess_views_view_fields(&$vars) {
  $vars['my_var'] = 'hello';
}

So in the twig template, I'm able to do something like:

{% for field in fields -%}
  {{my_var}}
{%- endfor %}

This is working like a charm for the first loaded fields, but when I hit "Load More" or I use exposed filters to filter down the view, the other loaded elements will not have my_var.

Now, "kinting" my_var directly in the template file. I saw that my_var is NULL for all other elements loaded after with Ajax and this made me think that the problem is with
theme_preprocess_views_view_fields being called once, the first time the page is loaded and completely being ignored from the Ajax call.

Shouldn't this preprocess be called and handled by the Ajax call Drupal is doing on the view itself?

If not, is there a way to query Drupal to re-run this hook when other elements are loaded?

Thanks!

In template "views-view-fields.html.twig" there is a three variables returned : "view", "fields", "row" you can see this here
.

So to add your custom variables you need to put it into these three variables like below

 function dt8_preprocess_views_view_field(&$vars)
  {
    $vars['row']->my_var = 'Hey';
  }

and in our template "views-view-fields.html.twig" we print int like this

{{ row.my_var }}


Creating Nodes Programmatically but cannot edit fields using Drupal once created I have a collection of nodes that are created programmatically after having created the content type using Drupal. This is the creation code:

    $node = new stdClass();
    $node->title = $vals->title;
    $node->type = "event_type";
    node_object_prepare($node);
    $node->status                       = 1;
    $node->promote                      = 0;
    $node->comment                      = 0;
    // title
    $node->title = $vals->title;
    // body
    $node->body[$node->language][0]['value']   = $vals->body;
    $node->body[$node->language][0]['summary'] = text_summary($vals->body);
    $node->body[$node->language][0]['format']  = 'filtered_html';
    // intro text
    $node->field_event_type_intro = $vals->field_event_type_intro;
    // teaser
    $node->teaser = $vals->teaser;
    // data
    $node->data = $vals->data;
    // nodewords
    $node->nodewords = $vals->nodewords;

    $node = node_submit($node); // Prepare node for saving

    node_save($node);

This seems to be working but when I then click on one of these nodes to edit it it only shows the title in the edit screen. The body and intro are missing.

What am I doing wrong?

In your code you have:
$node->field_event_type_intro = $vals->field_event_type_intro;

But if you want to add values to your fields you can use this:

if is a text
$node->field_event_type_intro[LANGUAGE_NONE][0]['value'] = field_event_type_intro;

if is a taxonomy
$node->field_event_type_intro[LANGUAGE_NONE][0]['tid'] = field_event_type_intro;

if is a field reference
$node->field_event_type_intro[LANGUAGE_NONE][0]['target_id'] = field_event_type_intro;


Dynamically creating menu items What I need is to add menu item to some menu, but it should have different parameters (title and url) depending on language. So I created new module and added links.menu.yml like:

my_menu_item_id:
  title: 'Dummy Title'
  description: 'Dummy Description'
  url: http://www.google.com
  parent: mainmenu
  menu_name: mainmenu
  weight: -100

And item appears well. Then I added menu_links_discovered_alter hook like:

    function mymodule_menu_links_discovered_alter(&$links) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $links['my_menu_item_id']['title'] = 'Title:'.$language;
    }

And title really get's altered, but that renaming is cached. So when I visit some page in other language previous title remains until I clear the cache. How to solve this. How to make Drupal execute this code with every page instead of using cached value?

The discovery process is not the right place for dynamic behavior. A menu link defined statically in a yaml file can provide dynamic values only in a menu link plugin class.

In your case you would implement the method MenuLinkInterface::getTitle:

  public function getTitle() {
    return $title;
  }

See this answer https://drupal.stackexchange.com/a/249342/47547 for a complete example of a menu link class.

Although for translating the title this should not be necessary, titles of routes and menu links are covered by interface translation, see Translate routing and menu titles


How to fix this error in drupal: ajax: ajax.form.ajaxSubmit is not a function I am creating a form with ajax submission in my Drupal custom form module.

When I click my submit button, I get the following error:

  ajax: ajax.form.ajaxSubmit is not a function.

I am searching some blogs, try something like uninstalling lightbox2 module, color box module, etc. But again the same error is displayed.

How can fix this error?

Note: I installed Lightbox first, but after this error I uninstalled it again.

You'll need to include the Drupal ajax drupal_add_library('system', 'drupal.ajax');


How do I get the field definition of a paragraphs image field I need to get the resolution of the image using getFieldDefinitions(). For normal fields I can get the field definitions with below.

$fieldDefinition = \Drupal::entityManager()->getFieldDefinitions('node', $type);
foreach ($fieldDefinition as $field_name => $field_definition) {
    $settings    = $field_definition->getSettings();
    $resolution  = $settings['min_resolution'];
}

How do I get the field definition of a image field inside of a paragraphs field.

As it mention in comment just use paragraph instead of node.

$fieldDefinition = \Drupal::entityManager()->getFieldDefinitions('paragraph', 'your_paragraph_type_name');
    foreach ($fieldDefinition as $field_name => $field_definition) {
      if ($field_definition->getType() == 'image'){
        $settings    = $field_definition->getSettings();
        $resolution  = $settings['min_resolution'];
      }
    }


Formatting variation as table Very new to Drupal and Commerce 2.x. I'm use to working with WooCommerce on Wordpress.

I have a list of equipment products and product attributes created. Each equipment category has different specification so I created different product variation type so I can add in the different attributes.

Under product types > manage display, the variation format is set to "add to cart form".

My question is how do I style the variation so that it displays as a table? display:table and display:flex doesn't seem to work with the fieldgroups.

Here is what it looks like now:

I want the above information to look like this:

Eventually I will be changing out the add to cart button to a request a quote so I wasn't sure if i needed to keep the variation format as an add to cart form or not. Unless there is a way for me to add the button in the template itself?

What you're needing really is a general overview of Drupal 8 theming using Twig. The parts you're asking about theming here are just Drupal fields like any other, and you can format / render them into the page's HTML however you'd like from the appropriate template file. What that file is called and how you'll reference the fields you've added is dependent on your theme and the names you've set for those fields.

The "Add to Cart form" display formatter doesn't control the inclusion of these fields. It's solely used to render the actual Add to Cart form. The rest of the variation fields are injected into the product display from whatever the currently selected variation on the Add to Cart form is.


Custom field on user page I'm trying to add a new fields with hook_form_alter on user_profile_form. From the core module right now there are:

Password confirm

Pass and re-enter pass

E-mail

This is the part of my code:

/*
 * Implements hook_form_alter().
 */

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

switch ($form_id) {
        case 'user_profile_form':

        $form['account']['telephone'] = array(
        '#type' => 'textfield',
        '#title' => t('New mobile'),
        );

        $form['account']['pass_title'] = array(
        '#type' => 'markup',
        '#markup' => '
Password change
',
        '#weight' => -6,
        );

        //krumo($form);
        break;
        }
}

As you can see I've added the telephone field into the form, but when I add text into that text field it doesn't save. The url is user/%/edit. I'm missing something.

The core fields password and email are properly saving.

The next thing is to do is when I add a new field on user_profile_form to be displayed into user/%.

Previously I've mention admin/config/people/accounts/fields, when I add a field from there let's say "telephone" it's working great. On user/%/edit is appearing as a form field and on user/% the result is rendering well. But my idea is: when I've added this field I want to have a title over the "telephone" field result. The title will be "Changing telephone" and bellow will be displayed the "telephone" field result (the result is what the user filled in the textfield on user/%/edit).

@Alfred Armstrong post helped a lot.

With The Field group module this is possible to achieve. It's amazing that on user_profile_form I can use fieldset and wrap the field into, it displays into user/%/edit  and on display field that render the results on user/% I can use different fieldset and with little CSS I can do exactly what I want. Many thanks to Alfred Amstrong for showing me this module and thank you all who helped me to find an aswer for this task. I wish I could add +1 to you all :)

Take a look at the Field Group module. That will enable you to group fields under a heading as you require. You can add groups on the form or on the display independently.

After you enable the module the display editor at Administration -> Configuration -> People -> Account Settings -> Manage Display will show a new entry to "Add new group". Add a new group of type fieldset, give it a title as required and set it to be "open" (not collapsible). You can then drag and drop individual fields into the group.

By default the group will display in a box. If you don't want that, the CSS to override it is pretty simple, eg:

body.page-user fieldset {border: none;padding:0;margin:0}


Is different checkout-flow per product possible? I've tried finding a solution to this myself, but have so far been very unlucky in that regard.
To save you checking the tags, this question is about:

Drupal Commerce 8.x-2.0-beta6
Drupal 8.2.7

Question
I want different checkout flows on different products, and while I can find plenty of documentation on how to create these, I cannot find anywhere, how you tell the product which flow it should use.

I have tried searching, going to every commerce backend page on my install, searching through the questions here, and looked at commit messages in the hope that they would shed light on it.

Can anyone help me with this? I would greatly appreciate it.

Thanks in advance.

You need to implement a checkout flow resolver.

Look at the default resolver for an example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/src/Resolver/DefaultCheckoutFlowResolver.php
And don't forget the matching services.yml entry:
https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/commerce_checkout.services.yml#L7
(You don't need to set the priority on yours though, it's -100 here so that DefaultCheckoutFlowResolver runs last)


What's the difference between $user login and access? I'm migrating users and I came across the $user object.

What's the difference between the login and access field? Does access get updated with every page request?

The access field is updated in Drupal's session write handler _drupal_session_write. This means it is potentially updated at every page request. If you look at the source code, you'll see that the access field is, by default, only updated every 180 seconds. This interval can be changed by setting the session_write_interval Drupal variable.

// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}


Adding multiple taxonomy terms to a single node programmatically I have the following iteration:

  foreach($category as $cat) {
              insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
              $node->field_tags[$lang_tags][0]['tid'] = $tid_tags;
            }
          }
       }
  node_save($node);

which relies on the following function to create non-existent taxonomy terms:

function insert_term_if_not_exists($term_name, $vocabulary_name) {
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $term = new stdClass();
      $term->vid = $vocabulary->vid;
      $term->name = $term_name;
      taxonomy_term_save($term);
    } else {
      $term = array_shift($matched_terms);
    }
return $term;
}

This couple pieces of code work great to create new taxonomy terms (taken from $category array) and to associate a node with the last taxonomy term. And I need to add all of the taxonomy terms which went through iteration above to the node.

Looking everywhere to find proper instructions to add multiple taxonomy terms to a single node programmatically without much success. Hope someone here can point me to the right direction, thanks!

Finally I have a working code:

insert_term_if_not_exists($cat, 'tags');
              $term_tags = taxonomy_get_term_by_name($cat);
              $tid_tags = key($term_tags);
              array_push($tids, $tid_tags);
              $lang_tags = field_language('node', $node, 'field_tags');
            }
          }
          foreach ($tids as $index => $tid) { $node->field_tags[$lang_tags][$index]['tid'] = $tid; }

       }

All the credit goes to user Albright in IRC channel #drupal at http://webchat.freenode.net who pointed out to me that I needed to collect the tids in an array, then add a second loop which loops through that array and adds the tids one at a time to field_tags.


How to show fid with slideshow image I have very specific requirement. I want to show images in slideshow.
I have created content type "User Slideshow Snaps" and two fields

Slideshow Snaps
Node Id

I want to show slieshow of images in field Slideshow Snaps which belongs to Node Id passed in URL.
The slideshow is working perfectly and I have used Modules Views Slideshow & Views Slideshow: Cycle for this.
Now I want to link Slideshow to external page which will pass FID of current image in slideshow like this:-

But I am facing problem in passing fid of clicked image in slideshow.
This configuration is always passing FID of first image in slideshow even if user clicked on 8th image in slideshow.
Thanks in advance for your help.

You may use views template files. If your view name is gallery and it's machine name is block_0 then in your theme folder create a file and name it views-view-fields--gallery--block-0.tpl.php.

There are two fields in the content type, an image with the machine name field_image and a text that is address of some where else with the machine name field_link.

In the views-view-fields--gallery--block-0.tpl.php file the following variables are available

1. $fields['field_image']->content;
2. $fields['field_link']->content;

To create a slideshow like this

with a string on it you can easily use html tags and css absolute positions to set the string on the image. Anyway you can display it in any way you want. Don't forget to clear the cache.


link to create a user relationship type in views I have user relationship, statuses and views installed. I created a view which shows "users online". I need to add a link to the view, that would allow other users to "create a relationship" with other online users via the view.

The user relationship I created is a one way relationship and there is no need for approval.

Thank you.

Hope this will help  you,

In Drupal 7, after configuration User relationship

Create a php field using views php module and after enabling, add below code in OUTPUT CODE within PHP tags.

  global $user;
  $opt = '';
  $requestee_id = $row->uid;
  $requester_id = $user->uid;
  if (user_is_logged_in()) {
    if ($requestee_id != $requester_id) {
      //for friend request button
      $relationships = user_relationships_load(array('between' => array($requester_id, $requestee_id)));
      if (empty($relationships)) {
        $opt = l(t('Add Friend') , "relationship/$requestee_id/request/2", array('html' => TRUE, 'absolute' => TRUE, 'query' => array('destination' => 'user/' . $requestee_id), 'attributes' => array('class' => array('ur-link add-friend-btn user_relationships_popup_link'))));
      }
      else {
        foreach ($relationships as $relationship) {
          if ($relationship->approved == 1 && user_relationships_ui_check_access('view', NULL, $relationship)) {
            $opt = t('Friends');
          }
        }
      }
    }
  }
  print $opt;

Note

2 is the default USER relationship.
Requester ID - Who requested and Requestee ID - to whome the user is requested.

Make changes as per your requirement.


How to do a custom taxonomy breadcrumb I'm using Drupal 8.3.0-beta1 and I need to write a custom module to customize breadcrumbs in some cases. On of this cases consists in customizing the breadcrumb in path taxonomy/term/% but with my current code there is a problem:

When I visit taxonomy/term/% the "applies" callback of my custom implementation of BreadcrumbBuilderInterface doesn't get executed. However, it gets called on taxonomy/term/%/edit. Maybe that's the reason why the core breadcrumb builder only returns "Home /" in this case. Do you think this is a core bug or I have done something wrong?

Notice I have another implementation of BreadcrumbBuilderInterface for nodes which works well. This is my code:

custom_breadcrumb.info.yml

name: 'Custom breadcrumbs'
description: 'Custom breadcrumbs implementation'
package: 'Custom'
# core: 8.x
type: module

version: '8.x-1.0'
core: '8.x'
project: 'custom_breadcrumb'
datestamp: 1443649740

custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumb_blog:
    class: Drupal\custom_breadcrumb\Breadcrumb\BlogBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 101 }

src/Breadcrumb/BlogBreadcrumbBuilder.php

<?php

namespace Drupal\custom_breadcrumb\Breadcrumb;

use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\LinkGeneratorTrait;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;
use Drupal\taxonomy\Entity\Term;

class BlogBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  use LinkGeneratorTrait;
  use StringTranslationTrait;

  /**
   * @inheritdoc
   */
  public function applies(RouteMatchInterface $route_match) {
    // This breadcrumb apply only for blog taxonomy terms of vocabulary 'categoria_blog'.
    $parameters = $route_match->getParameters()->all();

    /*
     * CORE BUG? applies callback gets called on "taxonomy/term/%/edit" but not in "taxonomy/term/%"
     * https://www.drupal.org/node/2622840
     */
    if (isset($parameters['taxonomy_term'])) {
      $term = $parameters['taxonomy_term'];

      if ($term->getVocabularyId() == 'categoria_blog') {
        return TRUE;
      }
    }

    return FALSE;
  }

  /**
   * @inheritdoc
   */
  public function build(RouteMatchInterface $route_match) {

    $parameters = $route_match->getParameters()->all();

    if (isset($parameters['taxonomy_term'])) {

      $term = $parameters['taxonomy_term'];

      // Breadcrumbs set up (cache settings are so important!).
      $breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
      $breadcrumb->addCacheContexts(["url"]);
      $breadcrumb->addCacheTags(["taxonomy_term:{$term->id()}"]);

      $breadcrumb->addLink(Link::createFromRoute($term->getName(), '<none>'));
    }

    // Reverse order for this to work!!!.
    $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
    return $breadcrumb;
  }
}

The taxonomy module provides a default breadcrumb service and if you have a look at the declaration of this in the taxonomy.services.yml file you will see it has a priority of 1002.

Setting the priority of your breadcrumb service to a value higher than this should get Drupal to use your breadcrumb rather than the default one.

Something like this should do the trick:

custom_breadcrumb.services.yml

services:
  custom_breadcrumb.breadcrumb_blog:
    class: Drupal\custom_breadcrumb\Breadcrumb\BlogBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 10001 }