Form with AJAX callback to query database and display info in block['content'] I have a simple select form that I want to use as a "Sort By" handler. When user chooses a different option I want it to change the query and display the new results. E.G. sort by duration ASC or sort by duration DESC.

This is my form:

function mortgage_multi_view_sort_form($form, &$form_state) {
     $form = array();
     $sortOptions = array(
        1 => t('Mortgage Duration: Shortest to Longest'),
        2 => t('Mortgage Duration: Longest to Shortest'),
     );

     $form['mortgage_sort'] = array(
        '#type' => 'select',
        '#title' => t('Sort By'),
        '#options' => $sortOptions,
        '#default_value' => 1,
        '#required' => TRUE,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'ajax_select_callback',
            //'wrapper' => 'replace_model_div',
            'method' => 'replace',
            //'effect' => 'fade',
        ),
     );

     return $form;
 }

When they change this to Longest to Shortest I want to asynchronously display the mortgages in reverse order. Is this best to do in the callback function?

My callback function (currently):

 function ajax_select_callback($form, &$form_state){
 switch($form['mortgage_sort']){
    case 1:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration DESC');
        displayMortgages($result);
        break;
    case 2:
        $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration ASC');
        displayMortgages($result);
        break;
 }

}

In my displayMortgages() function it just takes the entire query and displays it in a table. How do I get this information to block['content'] from my displayMortgages() now?

You should do all the logic in the form function. However with your particular issue, I would approach it slightly differently. I would simply return the table HTML from displayMortgages() back to the form and display the table as part of the form. But just simply as a #type=> 'markup'. That way, your sort form and the results are one, and you don't need to worry about firing off another ajax command somewhere else.

So your form code would basically be:

function mortgage_multi_view_sort_form($form, &$form_state) {
  $form = array();

  // Default sort direction
  $sort_dir = 'DESC';

  $sortOptions = array(
    'DESC' => t('Mortgage Duration: Shortest to Longest'),
    'ASC' => t('Mortgage Duration: Longest to Shortest'),
  );

  $form['mortgage_sort'] = array(
    '#type' => 'select',
    '#title' => t('Sort By'),
    '#options' => $sortOptions,
    '#default_value' => 'DESC',
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_select_callback',
      'wrapper' => 'replace_model_div',
      'method' => 'replace',
      //'effect' => 'fade',
    ),
  );

  // Check if a selection on the form has been made, if so then update the direction
  if (isset($form_state['values']['mortgage_sort'])) {
    $sort_dir = $form_state['values']['mortgage_sort'];
  }

  $result = db_query('SELECT * FROM {mortgage_database} ORDERBY duration '.$sort_dir);

  $form['result'] = array(
    '#markup' => (count($result)) ? displayMortgages($result) : '',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  return $form;
}

And you just need to return the part that's being replaced in your ajax callback:

function ajax_select_callback($form, &$form_state) {
  // Just a return of result is sufficient since it's being replaced
  return $form['result'];
}


Session variables on custom modules I have two modules. The first module is for custom login form and the other is for custom user pages.
I want to store a session variable from the first module and later to call on the second module.
Let's say my field from the first module is:

<?php
function custom_login_form($form, &$form_state) {

    $form['custom_field'] = array(
       '#type' => 'textfield',
       '#title' => 'Custom field',
    );

   return $form
}

and this is the callback from my second module:

    <?php
    function custom_user_pages() {
       $The_session_stored_field = 'some_value';

    }

How can I store the custom_field with session and how to call it on the second module?

EDIT: My custom modules are connecting with web service and all the information I'm passing with XML. With simplexml_load_string() I'm getting all the data. Now I've used $_SESSION, but I have some error:

  "Exception:Serialization of "SimpleXMLElement" is not allowed in
  session_write_close()...

EDIT2:In my first module I've set SESSION like this:

$_SESSION['custom_field'] = $custom_field;

On the other module I've set $custom_field = $_SESSION['custom_field'];

Is this a right approach?

Yes, I've got an error that's not related with session, because simplexmlelement cannot be serialized like that. Maybe I should open a new thread for that.

In submit of form store your data in session variable $sid with _drupal_session_write('mysession', $value); and in every where you want read it with _drupal_session_read('mysession');

you shold start session before you write or read session variable like php.

drupal_session_start();
_drupal_session_write($sid, $value);
_drupal_session_read($sid);


Menu structure and URL paths I am using a Superfish 2 level navigation menu, and have 3 sub-items under an item.
The url path for the second level item is NOT item/subitem but instead just subitem, if that makes sense.

I've got Generate automatic URL alias checked.

Is it acceptable for the subitems to not have their parent items in the url path? If not, what is the easiest way to automatically have the item appended to the subitems url path?

Yes, it is acceptable for child menu items to not contain any of the parent item's path.


views generated pager url How can I get the url generated by the pager in views.

drupal/project11?page=1
drupal/project11?page=2

I would like to add a link on my image to the 2nd page on my first image, to the 3th page on my 2nd image without using the pager.

I think you're asking for a link to a View like drupal/project11/1 or drupal/project11/2. You can do this with Clean Pagination module.

  Clean Pagination is a very simple module that allows you to enable
  clean URL pagination for specified pages. The way Drupal typically
  works, if you had a view with the URL 'my-view', subsequent pages
  would normally use a query to pass the page number, as in
  'my-view?page=2'. When Clean Pagination is being used for a page, it
  will create a url like 'my-view/2'.

  Currently, the module has just two settings: 1) Set the pages where
  you want clean pagination enabled, and 2) Enable
  search-engine-friendly pagination hyperlinks.

  The search-engine-friendly pagination hyperlinks is an experimental
  feature you can optionally turn on that will add the page URL to
  pagination links, and then remove them via jQuery. To a user, it will
  look like a single number, but to a screen readers and search engines
  it will have the url in the hyperlink text, which is usually a good
  thing.


What way should I use to load a file from a module? What way should I use to load a file from a module?

I am writing a module which is divided into 3 parts

Custom core will be in the module which contains basic functions required for project
Custom notification section will handle the notifications to show on site (It has a section on site where user can see all notifications.)
Custom mail will handle mail (Users will get email on each activity.)

So I have now a module file and 2 include files, but I am confused on how to include them in .module file.

There are 3 different methods available, but I am not sure which one is best and what the major differences between them are.

require_once drupal_get_path('module', 'custom_module')
files[] = mail.inc
module_load_include('inc', 'custom_module', 'mail.inc')

I tried them, and they all are working fine for now; I don't have much experience to guess future issues.

module_load_include() is a wrapper around require_once, with some sugar, so those are essentially equivalent. In the Drupal world, it would make sense to use the Drupal-specific function.

The files[] directive is for class autoloading - you don't use it to include files as such, just to make classes in those files available automatically when you need them.

You shouldn't use module_load_include() at the top of a module (or any other) file, it should be used only after Drupal has been bootstrapped. From the docs:

  Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.


Product image field best practice I am building a site selling engineering components. There are many Variations of some of the products but each variant looks almost identical.

Would I be better placed having an image field for each variant or just one image field in the product type?
If I go down the 'image field in the variant' option, then each variant would have the exact same image; yet, this doesn't strike me as sensible.

If the image doesn't really vary by variation, I would put it on the product. This will save you disk space / database space in the long run. Alternately, you may be able to use the Media module to upload the image once and reference it from all of the variations. This would let you use a single product type to handle product pages whether their variations required different images or not.

At the end of the day, there is no single best option here.


How to compare two fields in a preprocess_field() I need to compare two fields using template_preprocess_field().

I've got a field date and a boolean field.
Field date collect start and end date but if it's one day event, I need to show "start date - one day"

If you don't collect the end date, it will be the same date of the start date.
Of course I can compare start date and end date and if they are the same I will show "one day" but if the event is still running (so I won't collect the end date), I should show "on air"

So I'm trying this

function bartik_preprocess_field(&$variables) {

  //here I call the date field
  if($variables['element']['#field_name'] == 'field_duration') {
    $starttotime = time($variables['element']['#items'][0]['value']); // convert it in time
    $starttodate = date('d-m-y', $starttotime); // formatting date

    // check if start date and end date are similar
    if ($variables['element']['#items'][0]['value'] == $variables['element']['#items'][0]['value2']) {
      // HERE I NEED TO CHECK THE OTHER FIELD
      if (HERE THE FIELD ONE DAY == 0) {
        $variables['items'][0]['#markup'] = $starttodate." - One day";
      } else {
        $variables['items'][0]['#markup'] = $starttodate." - On air";}
      }
    }
  }

hook_preprocess_field() is invoked while rendering a single field, but (basing on the documentation for field.tpl.php) $variables['element']['#object'] is the entity object to which the field is attached. Through that, you can get the value of the other field you are looking for.


Print list of attached taxonomy terms on search result items First off, let me start by saying I am fairly new to Drupal, I come from a heavy Wordpress / Joomla background. On to my question:

I have looked for hours for a way to print a list of the taxonomy terms attached to a search result item. I need it to be as automated as possible (i.e. I need get the nid & vid from the node automatically if possible). I was able to get the nid using the following:

$nodeID = $variables['result']['node']->nid;

I do not need any fancy formatting, or hierarchy, I just need a comma separated list of the attached terms for each item on the search results page. If possible, I would also like to limit the depth to 5, but that is not a primary concern.

Here is what I have so far:

// Add List of Terms to Search Result Items
    $vid = 4;
    $terms = array();
      if (isset($node->taxonomy)) {
        foreach ($node->taxonomy as $voc) {
          if ($voc->vid == $vid) {
            $terms[] = $voc;
          }
        }
      } else {
        // check db in case node doesn't have terms
        $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
      }
      return $terms;

    $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);
    // To store the new terms (if necessary...)
    if ($terms) {
        foreach ($terms as $term) {
            // Each term has the properties:
            // $term->tid
            // $term->vid
            // $term->name
            // $term->description
            // $term->weight
            // To just print the results use something like:
            print $term->name . ',';
        }
    }

Any help you guys can provide would be immensely appreciated!

You almost have it.  How I'd do it is like this.  First, in (I assume you are doing this already) hook_preprocess_search_results:

function YOURMODULE_preprocess_search_results(&$variables) {

  // the vid you are restricting your results to...
  // it is really up to you to define the logic of how
  // to determine this, but you could use a variable...
  $vid=variable_get('YOURMODULE_search_result_vid', 4);

  $taxonomy=$variables['result']['node']->taxonomy;

  if ($taxonomy) {

    $terms=array();
    foreach($taxonomy as $t) {
      if ($t->vid == $vid) {
        $terms[]=$t->name;
      }
    }

    if ($terms) {
      $variables['terms']=implode(',', $terms);
    }

  }

}

will, assuming no typos and brain fades on my part, produce a $terms variable you can access in search-result.tpl.php.

Now, for step 2, copy the default one out of .../modules/search to your theme.  The default D6 one basically looks like this, with the large intro comments removed:

  <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php if ($snippet) : ?>

<?php print $snippet; ?>

  <?php endif; ?>
  <?php if ($info) : ?>

<?php print $info; ?>

  <?php endif; ?>

so in there, you can change it up basically like this:

  <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php if ($snippet) : ?>

<?php print $snippet; ?>

  <?php endif; ?>
  <?php if ($info) : ?>

<?php print $info; ?>

  <?php endif; ?>
  <?php // THE NEW STUFF FOLLOWS... ?>
  <?php if ($terms): ?>

<?php print $terms; ?>

  <?php endif; ?>
  <?php // ...END OF THE NEW STUFF ?>

and with some CSS styling of your new search-terms class, be on your way.


How do I allow date-time filtering on my custom entity's ISO date field I have a custom entity with a datetime field. This datetime is saved in the database as an ISO string. I would like to use Views on this entity, and select entities with dates before, after, or between certain dates. I see if I make a view against the system log, these options are presented when filtering on Timestamp. How can I enable the same filtering options on my field?

The field definition is:

$fields['set_datetime'] = BaseFieldDefinition::create('datetime')
  ->setLabel(t('Set DateTime'))
  ->setDescription(t('Date and time fermentor was set.'))
  ->setSettings(array(
    'datetime_type' => 'datetime',
  ))
  ->setDefaultValue('')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

After checking your module provided for me on github and some reverse-engineering  I find out the problem is on create('datetime') and you should use create('created') So the following code

$fields['date'] = BaseFieldDefinition::create('created')
  ->setLabel(t('DateTime'))
  ->setDescription(t('Date and time.'))
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'timestamp',
    'weight' => -4,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'datetime_timestamp',
    'weight' => -4,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Results the below image for me. it seems it's Ok now.


Javascript closures in modules I am trying to adapt some code I have written in javascript outside Drupal to a Drupal module:

(function($) {
  Drupal.behaviors.myModule = {
    $(config.targetElement).html(config.template).promise().done(function(){
      initialize($(config.targetElement).attr('data-region'));
    });

    var initialize = function (region) {
      if (region in config.regions) {
        //Calls the API
        $.ajax({
          url: config.apiUrl + config.regions[region]
        }).then(function(data) {
          //Build a regional weather object and render it to the UI
          renderUI(buildRegionalWeather(data));
        });
      }
    };
  }
})(jQuery);

This code was working before I wrapped it in the Drupal behavior, but now it is broken. initialize() can't be referenced from within the promise callback.

I assume it has something to do with the intricacies of closures which to be honest I'm not that familiar with.

I had a similar problem with some other code where I ended up Doing like this:

(function($) {
  Drupal.behavior.myModule = {
    //Document ready code here...
  }
  Drupal.myModule = {
    doStuff: function() {
      //Some public function here...
    },
    doMoreStuff: function() {
      //Yet another public function...
    }
  }
})(jQuery);

Which works, but exposes every single function I write. In the above case it is not so much of a problem, but there are many other functions in the javascript-file I am trying to adapt which should not be exposed like that.

How should I be implementing this?

Try this for Drupal 7 documentation:

(function ($) {
  Drupal.behaviors.myModule = {
    attach: function (context, settings) {
      // code here
      // example function call
      Drupal.behaviors.myModule.exampleFunction();
    },
    exampleFunction: function () {
      // code
    }
   }
 })(jQuery);


Is it safe to truncate a field revision table? I noticed D7 creates a field_revision table for every field, and duplicates the content from its field table counterpart even if one has revisions turned off.

I have a big text table and it is taking up a lot of space (several GBs).

Would it be safe to truncate the revision table?

PS: Meanwhile, I have also reported this as a bug.

I think there the Field SQL norevisions module will help you out:

  Field SQL norevisions provides a field storage backend that prevents
  entity revisions from being saved to the MySQL storage backend.

  The purpose of the module is to reduce the amount duplicated data that
  is saved on large Drupal sites that do not use revisions. It has the
  additional performance benefit of halving the number of queries during
  creating entities with fields.

This module will not allow revision fields to be created so it will increase your performance as number of queries will get reduced, besides that you will have no revisions on nodes further.

Also you can use some custom module codes provided on following URL:

http://www.ambidev.com/make-your-drupal-7-faster-by-removing-all-revisions/

and this module to delete revision entries:

https://www.drupal.org/project/node_revision_delete


How do I generate a HMAC code? How can I generate a HMAC code in Drupal 8?

In plain PHP, I would use hash_hmac(). Is there a more specific method/function, in Drupal 8?

You could still hash_hmac() in Drupal 8. Drupal 8 has a static function that returns the HMAC given a couple of data and key arguments (Drupal\Component\Utility\Crypt::hmacBase64()). The differences are the following.

Crypt::hmacBase64() returns the Base64-encoded HMAC value
Crypt::hmacBase64() replaces some characters to make the string safe to use in URLs
Crypt::hmacBase64() raises an exception when the arguments are not using the expected datatype

If you don't need to encode the HMAC value in Base64, or to pass the HMAC value in URLs, you can use hash_hmac(). You could consider Drupal\Component\Utility\Crypt::hmacBase64() a wrapper around two PHP functions, since its code is the following one.
if (!is_scalar($data) || !is_scalar($key)) {
  throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
}

$hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);


Custom login redirect failed in hook_user_login I'm trying to redirect to the user edit page just after the user logged in from the login block in the sidebar. I implemented hook_user_login, but no luck. It seems to me that drupal_goto() or $edit['rediect'] cannot take precedence over $_GET['destination']

function mymodule_user_login(&$edit, $account){
    if ( user role is employee and user has not completed profile yet ) {
        // both failed to redirect, although my condition is true
        $edit['redirect'] = 'user/'.$account->uid.'/edit';
        drupal_goto('user/'.$account->uid.'/edit');
    }
}

I was at my home page ( mydomain.com ) and tried to log in, but when I exit in my hook, I found that the URL was changed to mydomain.com/node?destination=node. My home page path is blank in site information.

[Edit]
My condition for redirect is that if the logged in user has empolyee role and his profile is not completed yet. My usecase is very similar to this, but i don't use content profile.

I think the way of overriding $_GET['destination'] would fix my issue.

drupal_goto() will use $_GET['destination'] when it is set. The following is the code used from the function.

  if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
    $destination = drupal_parse_url($_GET['destination']);
    $path = $destination['path'];
    $options['query'] = $destination['query'];
    $options['fragment'] = $destination['fragment'];
  }

Setting $edit['redirect'] inside hook_user_login() doesn't have any effect.
What you can do is changing $_GET['destination'] in hook_user_login(). If you want to be sure the user is redirected to the path you set, you should be sure your hook is executed last, for example by increasing the weight of your module.


Give permissions to user of the same role I'm working in a site and I've to set node permissions (edit) so that a user can edit a node that is owned by a user of the same role.
If I have the role "redactor" I can edit any node that is owned by a user that as the role "redactor".
Is there a module that do this?

Or I've to write a custom module?

You can used module content access, he does that easily.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type

Or you have node access which add a tab on each node to control permission for this node (you can configure role or user) I never really used it because there's no very stable version for d7.


How do I pass the value of a PHP variable? I have the following code in Drupal 6.

drupal_add_js(array(
  'take_control_fb' => array(
      //          'pubKey' => variable_get('take_control_public_key', ''),
      'dataUrl' => base_path() . 'admin/build/take_control/fb/getfiles',
      'appUrl' => take_control_app_url(),
      'appDir' => $appDir,
      'extPath' => $extpath,
      'zipMimes' => take_control_zip_mimes(),
      'dirSeparator' => DIRECTORY_SEPARATOR,
      'validationString' => $validationString,
      'validationToken' => drupal_get_token($validationString),
      'curUserId' => fileowner(file_directory_path()))), 'setting');

I need to convert this, since drupal_add_js() is removed from Drupal 8. I can't use this to pass PHP variables to modulename.js file. How can I pass the PHP variable to JavaScript code?

In Drupal 8 drupal_add_css(), drupal_add_js() and drupal_add_library() have been removed, and we are supposed to use #attached.

$page['#attached']['library'][] = 'fluffiness/cuddly-slider';
$page['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

More details about how JavaScript can be added in Drupal 8 can be found in https://www.drupal.org/theme-guide/8/assets#configurable-javascript.


How can I add a view to the front page news feed? I have created a view and I would like to promote the link to this view on the front page. How can I do this?

Thanks

UPDATE 1

I would like the view to show up in the front page news feed like in line along with other content that is "promoted to front page"

You can create a View block and display this block in any region like other blocks. Then make this block to show only listed pages, which is <front>.


Select groups to relate the node to directly in the node creation form An admin who wants to relate a node to a group can go to the group and then create a node from there (/group/{id}/node/create) . The node is then assigned to the group.
Or she can assign a already created node (/group/{id}/content/add)

What I need is a way to relate a node to one or multiple groups directly when creating it.
Is there a module to do this or some documentation to get me started in developing it?

There is no module that offers this out of the box as far as I know. You'd need some custom programming. I don't know what exactly you need, but here's something that might help to get you started.

Let's assume you want to programmatically relate a node/content to one/multiple groups as soon as the node is created. You could use a hook hook_ENTITY_TYPE_insert() (hook replaced by your custom module's name and ENTITY_TYPE replaced by the entity type (e.g. node).

Here's an example for article nodes:

use Drupal\node\Entity\Node;
use Drupal\group\Entity\Group;

/**
* Implements hook_ENTITY_TYPE_insert().
*/
function modulename_node_insert(Node $node) {
  if ($node->bundle() == 'article') {
    $pluginId = 'group_node:article';
    // Here create some logic to load/chose the group id's you want to
    // add the content to
    // ...
    foreach ($group_ids as $gid) {
      $group = Group::load($gid);
      $group->addContent($node, $pluginId);
    }
  }
}

This would automatically add the (article) nodes that are created to one or multiple groups. This is just a basic example of how to code the differnt parts. You can however make it as complex as you need. Hope this helps


How do I theme the user/uid/edit page? I am using two themes for my web and mobile site. And I'm using the ThemeKey module.

No matter what I try, the user edit page is always shown as in the theme of my web site and not my mobile site.

The following code doesn't work.

function mytheme_theme() {
  $items = array();
   $items['edit_profile_user_profile_form'] = array(
     'render element' => 'form',
     'template' => 'templates/user-profile'
   );

   return $items;
}

This only lets me theme the user profile page in user-profile.tpl.php. Also page--user--edit.tpl.php does not work.

How should I achieve this?

I found the solution for this.

The reason for error was that the ThemeKey module was not overriding and admin pages, by default.
Hence pages like user/uid/edit which are admin by nature are not overriden in their theme and pick the admin appearance theme always.

To bypass this I enabled the THEMEKEY COMPATABILITY Module (Part of Themekey module for D7). Open the following settings page:

http://localhost/admin/config/user-interface/themekey/settings/compat

Section Modules>> Integrate Modules in Theme Switching Rule Chain>>

Then check the option "System (Administration theme)".

Now all admin pages like user/uid/edit also come under theme switching rule and pick the theme as defined.


Feeds auto create is not working Am using Drupal 7 Feeds module and I have "Autocomplete term widget (tagging)" field in content type.

As well as I have configured as "Auto create". But, when I import nodes that auto creation does not working, its shows the blank field.

Any other way to do?

If Feeds creating empty values on Auto create, you need to verify your mapping. Make sure your Context Value in XML Xpath parser is fetching the right data by enabling Debug option, so you can see exact value being imported. If it's not, please validate your XPath on your sample data (e.g. on-line on XPath Tester).

If your XPath is correct, then use hook_feeds_after_parse() to debug your feed items, e.g.

/**
 * Implements hook_feeds_after_parse().
 * Invoked after a feed source has been parsed, before it will be processed.
 */
function MYMODULE_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
    foreach ($result->items as &$item) {
      drupal_set_message(print_r($item, TRUE));
      // or: drush_print(var_export($item, TRUE)); exit;
      // or: var_dump($item, TRUE); exit;
      // or: dd($item); exit;
    }
}


Simple test always failing for custom module I am trying to implement simple test for my custom module. But the test case always failing for user login. In the test script what I am trying to test is whether admin page is loading properly without any errors.

I am following similar code from core modules and other contributed modules. But couldn't figureout what I am missig in mine. My test script is given below:

<?php

/**
 * @file
 * Test file for custom_module module.
 */

/**
 * Default test case for the custom_module module.
 *
 * @ingroup custom_module
 */
class MyCustomModule extends DrupalWebTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'My Custom Module Test Case',
      'description' => 'Functional test for My Custom Module Module',
      'group' => 'My Custom Module',
    );
  }

  /**
   * {@inheritdoc}
   */
  function setUp() {
    parent::setUp('custom_module');

    $permissions = array(
      'access administration pages',
      'administer custom module',
    );
    $this->admin_user = $this->drupalCreateUser($permissions);
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Test site working properly after installs the module.
   */
  function testCustomModulePageLoads() {
    $paths = array(
      '/admin/config/custom_module/manage',
    );
    foreach($paths as $path) {
      $this->drupalGet($path);
      $this->assertResponse(200, '200 response for the path ' . $path);
    }
  }

}

Result:

Try calling $this->setUp(); from the testCustomPageLoads() function.


Node update date changes when saving without changing anything Why does the timestamp of node_revisions and changed of node tables are updated when I save a node without making any changes?

All I want to know if anything ever changed in a node (revision). Is there a way to find it?

If you save a node then it has changed according to Drupal...regardless of whether or not any specific property/CCK field values have actually been changed.

You can find the evidence for this in the node_save() function which contains this line of code which runs for every single call to the function:

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

Drupal does not do any sort of diff against the current and new revisions of a node when saving, so if you've pressed "Save" it makes the assumption that you wanted to add a new revision of the node.


How do I use a custom template file? I tried using a custom template file for my theme, but using page--testpage.tpl.php (where testpage is the path alias for the page being shown) doesn't work. It just works with page--node--47.tpl.php

How could I fix it?

Read Drupal 7 Template (Theme Hook) Suggestions

  A theme hook suggestions is an alternate template (.tpl.php) file that
  you have created to override the base or original template file.

The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestions. For example, "http://www.example.com/node/1/edit" would result in the following suggestions:

page--node--edit.tpl.php

page--node--1.tpl.php

page--node.tpl.php

page.tpl.php

Read Theming Drupal 6 and 7

If you still want to alter the suggestions its possible with template_preprocess_page

function template_preprocess_page(&$variables) {
  $variables['theme_hook_suggestions'][] = "page--type--" . $vars['node']->type;
  // likewise you can do
  // $variables['theme_hook_suggestions'][] = "page".GET-URL-ALIAS-HERE;
}


Passing Settings from page.tpl to Javascript: Uncaught TypeError: Cannot read property I want to pass this to my js file :
in page.tpl

<?php
$my_settings = array(
    'message' => $message,
);

drupal_add_js(
    drupal_get_path('theme', 'sizin') .'/js/anim.js',
    array('my_settings' => $my_settings),

    'setting');
?>

in anim.js

var message = Drupal.settings.my_settings.message;

i got this error from chrome:

Uncaught TypeError: Cannot read property 'message' of undefined

Any Help/Idea ?

and i've read this : Retrive $message variables in javascript file

You need two line to add your code. Before one line to add js data settings:

$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

and one line function to add file js

drupal_add_js(drupal_get_path('theme', 'sizin') .'/js/anim.js', 'file');

And better you don't write code in file tpl. You cand add js file, js  settings in hook_preprocess_page(). It's drupal standard and clean tpl file.


Drupal 7 How to find Nodes, tagged with Broken Taxonomies? In Drupal 7, some Taxonomy Terms were deleted (by force from direct DB Query, for some reason). So some Nodes left remained by still tagging this deleted Taxo Terms. Then the problem is arising at the Site Indexing stage. The process is getting broken.

So i believe i need to find the Nodes which are tagging to these no longer existing/broken Taxonomy Terms, to un-tag those.

Which is the best way to do it?
What will be the best Query for it?

Thanks.

Just as an FYI, even if the terms had been deleted properly, the references still would have been broken (see Database records not deleted for Term Reference Fields after Term is Deleted).

Either way, to answer your question, you could use use super useful Taxonomy Orphanage module.

  This module provides interfaces (drush, cron, admin form) for removing
  orphaned taxonomy term references from entities.


How to allow html tag in menu? How to allow html tag in menu in Drupal 8. For example if use home @reg used in menu title it display the html tag.

Following solution works:

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 */
function YOURTHEME_preprocess_menu(&$variables){
  foreach($variables['items'] as &$link){
    $link['title'] = Markup::create($link['title']);
  }
}

Source: Allow html into menu item names - Solution for Drupal 8


My theme CSS uses relative paths, but Advagg or another module seems to be rewriting them to absolute paths. Core aggregation uses relative paths Our CSS authored in the theme uses relative paths for all references to assets
But the CSS aggregated/processed by Advagg has absolute paths where the authored CSS uses relative paths

I can't see any Advagg settings where I am asking it to convert relative paths to absolute

When Advagg is disabled, the CSS aggregated by Drupal core noes not have any absolute paths, instead the relative paths from the authored CSS are used
If I enable Advagg but enable the advagg_convert_absolute_to_relative_path setting then relative paths are used, but doing this would cause problems elsewhere on the site where some CSS is used that requires absolute paths. I'd rather Advagg left our relative paths alone, rather than seemed to convert them to absolute paths, and then back to relative paths.
I have a custom module on the site that alters the base URL to make links/URLs absolute for a small subset of the site (which is consumed and displayed on an external domain). This seems like a potential cause, but disabling this module does not resolve the issue.

A potential cause of the issue?

I have a module that uses hook_url_outbound_alter() to make URLs on some pages absolute by modifying the base URL:

/**
 * Implements hook_url_outbound_alter().
 */
function site_absolute_paths_url_outbound_alter(&$path, &$options, $original_path) {
  if (drupal_static('_is_absolute_path_requiring_callback')) {
    $options['base_url'] = _site_absolute_paths_url_modified_base();
    $options['absolute'] = TRUE;
  }
}

This seems like it could be a candidate for causing the issue, but the problem persists even when the changes to the options array in this function are commented out.

I'm not sure how else to debug this? I suspect it is not an issue with Advagg, but something else on this site that is interacting badly with Advagg. That said, it is odd that the aggregated CSS produced by Drupal core has the correct paths rather than the absolute paths.

If the advagg_convert_absolute_to_relative_path setting seems to resolve the issue, does that suggest that something 'upstream' of Advagg is adding the absolute paths? But isn't adding them when the core aggregation process is run?

Things I have tried

A breakpoint in the first line of advagg_file_create_url() gives "/" as the value for $aggregate_settings['variables']['base_path']. This is what I would expect to be working OK.

global $base_url;
echo $base_url;

In /devel/php gives http://my-site.drupal.dev

Variables used in Advagg hash

Array
(
    [variables] => Array
        (
            [advagg_gzip] => 1
            [is_https] =>
            [advagg_global_counter] => 10
            [base_path] => /
            [advagg_ie_css_selector_limiter] => 1
            [advagg_ie_css_selector_limiter_value] => 3500
            [advagg_scripts_scope_anywhere] =>
            [advagg_devel] =>
            [advagg_convert_absolute_to_relative_path] => 0
            [advagg_convert_absolute_to_protocol_relative_path] => 0
            [advagg_force_https_path] => 0
        )
)

Is this an intended feature of Advagg? This line seems to suggest so:

// Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
$contents = preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);

This is an intended feature of AdvAgg, see Mike (one of AdvAgg maintainer)'s issue on Drupal.org where a 'do not convert' option has been raised as a feature request.


Module for sidebar menu which appears in open atrium I wanted to know if any modules already exists for creating side bar menu which appears in open atrium. So that it expands only when required.

/** Update **/

Please see the image below. I am talking of the LHS black sidebar.


Simplenews Scheduler Sending Newsletter Twice a Week I'm having trouble configuring how to send a simplenews newsletter to subscribed users twice a week.  I'm using Simplenews scheduler but just don't know how to configure it.  I want to send a newsletter of all my updated content to my users on Sunday and Thursday.

I've got everything else working, just don't know how to configure it to send on Sunday and Thursday.  In Simplenews Scheduler, we can schedule it to start sending on a specific day like Sunday and set the Sending interval to 'Day', then, set Interval Frequency to 4.  But I am certain that after the first two times, the days will shift and the third time it will send on Monday and fourth time on Friday and just keep shifting a day each time.

So, hope you guys have some ideas on how to configure it correctly.

There is a way of solving it without Rules, you can use Simplenews Scheduler.

Simply create two different Simplenews nodes of the same Simplenews category. You can use the same views token (or whatever you use to fill in the content of the newsletter) in both nodes.

Then set one node to send on Sunday weekly, and the other on Thursday weekly.

This can be done because Scheduler is set per node, not per category, and also subscribers are subscribed to Categories, not nodes, so each time all of the subscribers will receive the news, no matter if Sunday or Thursday nodes happen to be sent.


How to get taxonomy term values? In my user entity, I have a term reference. In that vocabulary, I have a regular field. How can I fetch that field's value? I tried the below in  devel/php to no avail.

$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department->entity;
\dpm($dept->field_administrator_e_mail->value);

My end goal is to send the email to the department's administrator when a user is created.

UPDATE: I also tried the below:

$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department;
\dpm($dept->name);

Your missing link is the entity function, which returns the referenced entity object:

$host_entity->host_field->entity->remote_field->value


How do I disable the Quick edit module? I tried uninstalling Quick edit via the user interface.

I cleared the cache via drush cr, but it doesn't work.

How can I disable it?

Even drush en -y quickedit and drush pmu quickedit don't work.

As far as I understand your question, you want to get rid of the "Edit" pen icon, displayed when you put the mouse over a node.

This is not provided by the "Quick Edit" module. You have to disable "Contextual Links" if you want to get rid of that menu.

Alternatively, if you are using those links for managing blocks for example, you might want to force hiding contextual links on nodes via CSS.

For example:

.your-node-selector .contextual {
  display: none!important;
}


Multilanguage In Drupal Now, I'm trying to translate my content pages into Burmese language. But, the problem is there is no language option appear in "Publishing Options" Tab. I enabled Content translation, Locale and Multilingual Internationalization, Variable modules. Although I enabled all these modules and clear the cache, it still doesn't appear.
Please, help me!

If your language is not already added, you can do it in this interface admin/config/regional/language/add
You have to check that your new language is activated in the languages manager admin/config/regional/language
Check that this modules are activated : Local, i18n
In your content type manager, check that multilingual settings tab exist
In this tab, choose the elements suitable for your case
In Publishing options tab, check that multilingual support is activated


When does hook_menu run? I need to edit the hook_menu function in my  module.  I need to add a new link to a menu, and edit the path for an existing link.  Is this possible without creating a whole new module?

The only example in the docs for when hook_menu runs is when the module is enabled.  Is there any other time it runs?

Clearing the cache the menu and routing tables will be reconstructed.

In the admin UI, go to:

/admin/config/development/performance

Using drush:

drush cache-clear all

Other methods are described here: How do I call the menu_rebuild function in Drupal 7?


Duplicate / Triplicate inline javascript On some pages of my site when inline javascript has been added to page it get added multiple times.

I've looked through my base theme (Zen) and my default theme (custom) for anything that may be messing with the drupal_add_js process but I haven't been able to find anything.

Does anyone have any suggestions for what might be causing this?

The problem ended up being the module Panelizer.  I was using the Default view and should have been using the Full Page Override view.


How do I add a term reference name to the Pathauto pattern for a content type? I'm trying to create a website with 2 sections, Home and Business. For this I have created a vocabulary called 'Page Type' and added those section names to it.

I've added a term reference field to my content type to relate nodes to my vocabulary.

What I need to do is automatically set the titles of the nodes to include the section name they are related to, using the Pathauto module.

I'm at the settings page (/admin/config/search/path/patterns) but I don't know what pattern to use - 'Page Type' is a vocabulary, not a content type, so I don't know how to use it as part of a pattern.

How do I add the name of the referred taxonomy term to the node path? For example, I'm expecting URLs like this:

example.com/home/page-title
example.com/business/page-title

So I want the node page to have a vocabulary in its path, the vocabulary of a term it is tagged with.

It should be something like [node:field-yourfieldname].

On that page underneath each conten-type field, do you not see a "Replacement patterns" title?

If not, install the token module.


How can I add custom client-side validation to a Webform field using advanced custom properties? The setup:

I have a Drupal 8 form created manually, and I would like to recreate it using Webform module.

So far, I have managed to recreate everything (required fields and submission handler), but there is a last bit missing: the client-side validation that triggers on change.

The initial form have fields defined as follows:

$form['first-name'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('First name'),
  '#required' => true,
  '#required_error' => $this->t('This is a required field. Please enter your first name.'),
  '#ajax' => [
    'callback' => '::validateFnameAjax',
    'effect' => 'fade',
    'event' => 'change',
    'progress' => FALSE,
  ],
);

Calling validation functions like this one:

public function validateFnameAjax(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $errorValidation = '

';
  $successValidation = '

';
  // Assert the name field has been included
  if (!$form_state->getValue('first-name') || empty($form_state->getValue('first-name'))) {
    $message = $this->t('This is a required field. Please enter your first name.');
    $response->addCommand(new InvokeCommand('.staff-register-form .js-form-item-first-name .form-text', 'removeClass', ['is-valid']));
    $response->addCommand(new InvokeCommand('.staff-register-form .js-form-item-first-name .form-text', 'addClass', ['is-invalid']));
    $response->addCommand(new ReplaceCommand('.js-form-item-first-name .form-item-message', $errorValidation));
    $response->addCommand(new HtmlCommand('.js-form-item-first-name .text-danger', $message));
  }
  else {
    $message = $this->t('Your first name is valid.');
    $response->addCommand(new InvokeCommand('.staff-register-form .js-form-item-first-name .form-text', 'removeClass', ['is-invalid']));
    $response->addCommand(new InvokeCommand('.staff-register-form .js-form-item-first-name .form-text', 'addClass', ['is-valid']));
    $response->addCommand(new ReplaceCommand('.js-form-item-first-name .form-item-message', $successValidation));
    $response->addCommand(new HtmlCommand('.js-form-item-first-name .text-success', $message));
  }
  return $response;
}

In the new webform function I have changed lines one and six, but the rest of the code is the same.

New line one:

  public function validateFnameAjax(WebformSubmissionInterface $webform_submission) {

New line 6:

  if (!$webform_submission->getElementData('first_name') || empty($webform_submission->getElementData('first_name'))) {

The challenge:

Implement the same behaviour: trigger the custom validation when the content in the field changes (before submission).

Current status:

I have tried to include the Ajax properties using the Advanced tab of the edit field UI as you can see in the following screenshots:

But I get this error in the log:

  Symfony\Component\HttpKernel\Exception\HttpException: The specified #ajax callback is empty or not callable. in Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse() (line 67 of /var/www/drupalvm/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php).

Does anyone know what am I doing wrong to get this error, and how to make this client side validation work?

Although this answer does not provide the solution to add custom client-side validation to a Webform field using advanced custom properties, it provides a working alternative to add client-side validation to a Webform field.

Given that Webform UI comes with the option to add custom CSS and Javascript to a Webform, I have made use of this option to add my custom validation.


get taxonomy terms of parent node while in block I'm in drupal 7. Let's say I have a block on a website page.  The website page is a node that has taxonomy terms.  How do I programatically get the taxonomy terms of the website page node from my block?

You should be able to use menu_get_object() to get the node object if the block is being displayed on a node page. Then, with the $node object you can retrieve terms for the node.

if ($node = menu_get_object()) {
  $query = db_select('taxonomy_index', 'r');
  $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
  $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
  $query->fields( $t_alias );
  $query->condition("r.nid", $node->nid);
  $result = $query->execute();
  $terms = array();
  foreach ($result as $term) {
    $terms[$term->tid] = $term;
  }
}

Just remember that that if caching is enabled in your block it should be per-page caching, otherwise you could get unexpected results.


How to create a controller that runs query? I have a query:

$sub_query = \Drupal::database()->select('test_file_discovery', 'f')
  ->fields('f', ['nid'])
  ->condition('extension', 'pdf');
$or = $sub_query->orConditionGroup()
  ->condition('path', \Drupal::database()->escapeLike('_TT'), 'LIKE')
  ->condition('path', \Drupal::database()->escapeLike('_OT'), 'LIKE')
  ->condition('path', \Drupal::database()->escapeLike('_AT'), 'LIKE');
$sub_query->condition($or);

$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->condition('nid', $sub_query, 'IN');
$query->range(0, 10);

But I don't know how to create a controller / page where I can display this query's results in a table, "Name" and "Actions" as labels / headers.

Anyone can give me assistance?!

@asrob,
Please refer the basic docs provided by Clive to create a controller in drupal 8 with route to access the same or
this link to create a custom module in drupal
and follow this sample code below to display your data in table format along with a pager:

  <?php

  /**
   * @file
   * Contains \Drupal\custom_module_name\Controller\DetailsController
   */

  namespace Drupal\custom_module_name\Controller;

  use Drupal\Core\Controller\ControllerBase;

  /**
   * Description of DetailsController
   *
   * @author aaditya.walawalkar
   */
  class DetailsController extends ControllerBase {

    const RECORDS_PER_PAGE = 10;

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

      $records = $query_result_from_query;

      // total records
      $totalRecords = $total_records_count_from_query;
      $recordsPerPage = self::RECORDS_PER_PAGE;
      // initialize pager
      $page = pager_default_initialize($totalRecords, $recordsPerPage);

      $offset = $recordsPerPage * $page;

      $data = array();
      foreach ($records as $delta => $details) {
        $data[] = array('data' => array(
          $details['name'],
          $details['remarks'],
        ));
      }

      $recordsToDisplay = [];
      $recordsToDisplay[] = [
        '#theme' => 'table',
        '#header' => array($this->t('Name'), $this->t('Remarks')),
        '#rows' => $data,
        '#empty' => $this->t('No Records(s) Found.'),
      ];

      // Finally, add the pager to the render array, and return.
      $recordsToDisplay[] = ['#type' => 'pager'];
      return $recordsToDisplay;

    }
  }


Inline add/edit/delete data in views in Drupal 7 I am trying to create a content type (say Meter). Each Meter consists of a "Meter Reading". This meter reading content contains three fields, say title, date range and usage. I have a Panel page where I display all the Meter Readings related to a parent Meter. I have displayed the Meter Readings in a tabular format.

I want the user to be able to add new Meter Readings without going to the default Meter Readings creation page. Rather than the default form kind of page, the user should be able to enter the data in the table view provided and it should be automatically saved into the project itself.

So, I want the functionality to be like:-

Display all the meter readings with two links, i.e., Edit and Delete,
When the user clicks on Edit link, the meter reading row should become editable and the user should be able to make the changes inline in the same table,
In the footer there should be a link for adding a new meter reading and when the user clicks on it, a new blank row should be added dynamically to the table and the user should be able to make a new entry into it.

Is there a module in Drupal 7 for doing so?? I have already tried out several modules for this such as SlickGrid, jQGrid and jEditable.

Any help would be great. Thanks in advance.

I think Editable Fields module should do the trick for you. It lets you edit the fields in both node and views. Checkout the project page image for more details.

Regarding the delete option you may need to do some tweaking. Adding a 'add new meter reading' should not be very difficult. Just get the nodes value from the context and generate the add link.


Taxonomy i18n does not translate term name in a term page I set option Localized in my Vocabulary "Categories" and translated all the terms in english French and german some of them. The default language is russian.
Term page title has russian name: http://tlito.ru/en/categories/debugging in all the languages. I've made html-document title in need language using Page Title module. But the page title rest russian.
Please what is this bug?

This is a known issue: Vocabulary Name value doesn't get translated. It dates from 2005 (!), related to D6, status "won't fix". However comment # 2 in that issue states:

  I have used the locale module to translate the name of the vocabulary, and display it with t($vocabulary->name). If all modules would display the name this way (e.g. taxonomy_menu does it), then there is no need for a new database table i18n_vocabulary.

The t($vocabulary->name) seems like a possible/partial work around to consider, i.e. from within a (custom) module.

There is a more recent similar issue, i.e. Vocabulary names are not translated. That one is for D7, with status "needs work".

Another potential work around could be to have a separate taxonomy for each language (and with a "name" corresponding to that language). Of course, you'd have to think how to best use these separated taxonomies for each content type (a kind of "solution to the problem, changes the problem) ...

That's probably the best you can get these days. Does this somehow "answer the question"?


Using drupal_add_feed() in template.php gives warning errors As soon as I add a call to drupal_add_feed in my theme template.php file I get this warning:

  Warning: call_user_func_array() expects parameter 1 to be a valid
  callback,   no array or string given in theme_get_registry() (line 277
  of  /var/www/example.com/includes/theme.inc).

The feed (created by Views) is valid, and the code works, i.e. it does add the meta tag. But the warning is unacceptable, obviously.

Fix? Something I'm doing wrong?

You need instal Zen and STARTERKIT theme in (...sites\all\themes).Because STARTERKIT need Zen theme to work.


Views - List of content that user (ID from URL) voted on I want to make a list on every profile page of content that the user voted on.

I've yet only managed to show the current logged in user's votes, not the user from the profile page.

In other words, I need to pass the User ID from Contextual filters to the Filter criteria with VotingAPI.

I tried with the filter Votes: User, but I wasn't able to set Is one of: % as the username, which would've solved my problem.

Contextual filters by definition should already filter your result set on the field for an entity you choose based on the value of the URL.

Set up the contextual filter to filter on Votes: User and make sure you have no other filters or relationships that restrict your result for the logged in user.


Privatemsg Module and custom timestamp By default the Privatemsg Module has three timestamp displays for various lengths the message has been sent. After a certain point the listed 'time' changes.

What I want to do is append the next timestamp to the end of the current one. This way it remains the details of minutes and date posted as time moves forward.

Example: after 24hrs, instead of it just saying 'Oct 8' I want it to say 'oct 8 12:45' and after a year '2014 oct 8 12:45'

I think I found the code in the module where timestamps are printing, I just can't figure out how to add to it.

function privatemsg_date_formats() {
  $formats = array('g:i a', 'H:i', 'M j', 'j M', 'm/d/y', 'd/m/y', 'j/n/y', 'n/j/y');
  $types = array_keys(privatemsg_date_format_types());
  $date_formats = array();
  foreach ($types as $type) {
    foreach ($formats as $format) {
      $date_formats[] = array(
        'type' => $type,
        'format' => $format,
        'locales' => array(),
      );
    }
  }
  return $date_formats;
}

function privatemsg_date_format_types() {
  return array(
    'privatemsg_current_day' => t('Privatemsg: Current day'),
    'privatemsg_current_year' => t('Privatemsg: Current year'),
    'privatemsg_years' => t('Privatemsg: Other years'),
  );
}

function privatemsg_format_date($timestamp) {
  if ($timestamp > ((int)(REQUEST_TIME / 3600)) * 3600) {
    return t('@interval ago', array('@interval' => format_interval(abs(REQUEST_TIME - $timestamp), 1)));
  }
  if ($timestamp > ((int)(REQUEST_TIME / 86400)) * 86400) {
    return format_date($timestamp, 'privatemsg_current_day');
  }
  if ($timestamp > mktime(0, 0, 0, 1, 0, date('Y'))) {
    return format_date($timestamp, 'privatemsg_current_year');
  }
  return format_date($timestamp, 'privatemsg_years');
}

Add these two date formats (in admin/config/regional/date-time/formats):

M d H:i

Y M d H:i

After that choose above created date formats (in admin/config/regional/date-time)
in

Privatemsg: Current year & Privatemsg: Other years  respectively.


How to speed up performance of taxonomy hierarchical select drupal I have a taxonomy that have 35(States) -> 650(Districts) -> 6500(Blocks) -> 650000(Villages) taxonomy terms using hierarchical select  module

when i filter it on my content type form then it's performance is very slow. so, i want to know that how to increase it's performance when filtering.

i have installed taxonomy manager module but we can't use it as CCK Field of Taxonomy Term.

Using High-performance JavaScript callback handler will speed up it a bit while i recommend using Simple hierarchical select rather than Hierarchical Select , cause it is much faster in queries (off course less user friendly) .

this is the description High-performance JavaScript callback handler :

  JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc.
  This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.


I can't override the node template I have installed Barrio Bootstrap (8.x-4.33) and it worked so far.
But I can't override a template for a specific node type.
I copied the original template into my subtheme/template folder and named it like suggested in the FILE NAME SUGGESTION (debug mode).
E.g.: bs-2col-bricked--node-cuba-casa-particular-full.html.twig
This doesn't work.
Only when I name it like the original file bs-2col-bricked.html.twig it works.
I tried also 5.1.4, but it's the same. Anything wrong with the FILE NAME SUGGESTIONS?
In my Bootstrap3 theme it worked.
Can anybody help, please.

My solution was to turn off the layout ('Manage display' --> 'Select a layout' --> 'none').
Now the debug mode FILE NAME SUGGESTIONS showed the correct suggestions.
I was able to override the 'node.html.twig' in my subtheme (in my case with 'node--CONTENT-TYPE--full.html.twig')from 'themes/bootstrap_barrio/templates/content/'.
Neither the FILE NAME SUGGESTIONS for the DS (8.x-3.9) nor the Bootstrap Layouts (8.x-5.2) were working (the one you see in debug mode, when one of those layouts is selected in 'Manage display').
Maybe there is a better way ...


URL condition in Twig I have a category mysite/news (the page created by the Views) and when I turn to the next page of this category - mysite/news?page=1, some text and image should not be displayed.

This code does not work

{% if url == 'mysite/news' %}
some text
{% endif %}

You should be able to use 'in' operator to get around this issue. Try something like:

{% if 'mysite/news' in url %}

some text

{% endif %}


Views Slideshow Stops Working Alongside Other Slideshows I've made several thumbnail-sized cycle slideshows as block views, which display fields from nodes created via an HTML feed. Each slideshow is basically the same, but they all use a different taxonomy term as a filter on a single content type, and have a different XPath parsing structure.

The slideshows work perfectly on each view's preview page. Each also works separately when its block is displayed on the main page. I've managed to get 6 slideshows at once scrolling normally as blocks on the main page.

However, when I display a 7th slideshow in a block on the main page, only two slideshows work properly, with the rest not progressing via time or clicking on the controls. If I add an 8th slideshow block, 3 of them work, and the other 5 do not.

The 7th and 8th slideshows have slightly different field output, as the feed source is configured differently, but I don't think this is relevant, as the view-generated HTML looks the same.

I can get sporadic results by re-arranging the blocks in the block list, and by displaying them in different block areas. Some permutations allow all the slideshows to function, some only allow a few.

Is there a limit to the number of JQuery slideshows that can be running at once? Or, is there maybe some kind of naming convention that's causing these mixed results with different ordering?

Totally confused, and disappointed. :(

After some inspired messing around, I determined that the issue only stopped slideshows that were displayed after a certain slideshow. Using that information, I deleted the isolated block, and re-created it in the same form as the other slideshows.

This appears to have solved the problem. I guess something was corrupt with that particular view. It was the one I was originally using as a clone base for all the other slideshow blocks.

Hopefully this "fix" persists!


Import CSV file from S3 Bucket Using s3 file system & feed import module. Issue is the fetching of csv file from s3 working... says no file or folder detected ... have the folder under s3://public/repo.csv and had read/write permission.

When running import, it will have a no file / directory found.

To detect folders created and files added to an S3 bucket, you need to Flush s3 media file metadata cache.

To do it,
Configuration > Media > S3 File System > Actions > File Metadata Cache > Refresh File Metadata Cache

The file metadata cache keeps track of every file that S3 File System writes to (and deletes from) the S3 bucket, so that queries for data about those files (checks for existence, filetype, etc.) don't have to hit S3. This speeds up many operations, most noticeably anything related to images and their derivatives.

This button queries S3 for the metadata of all the files in your site's bucket (unless you use the Root Folder option), and saves it to the database. This may take a while for buckets with many thousands of files.
It should only be necessary to use this button if you've just installed S3 File System and you need to cache all the pre-existing files in your bucket, or if you need to restore your metadata cache from scratch for some other reason.


How can I assign pages to templates like in WordPress? I've just made the jump from WordPress to Drupal, and though I love what I'm seeing there's a basic piece of functionality that's obvious in WordPress but is escaping me in Drupal- How does one, for a given page or piece of content, assign it to a specific template?

Please note that I'm not trying to design a template for a specific content type, rather I want the ability to choose a template at the individual content/node level, in the edit screen.

It doesn't look like this is part of out-of-the-box Drupal, so does anyone have suggestions as to how to go about implementing it?

What I would do, is to create a Vocabulary called "template" (using the Taxonomy module in Drupal core) and add some template names to it as taxonomy terms. This will allow you to 'tag' your nodes with the template name for that node.

Next, I would create a preprocess function for the node template in my theme's template.php file and add template suggestions based on the taxonomy term. Roughly the preprocess function would look like this (not working code, just an outline):

function MYTHEME_preprocess_node(&$variables) {
  // Get the Term ID from the "template" vocab for the current node.
  $template_tid = ... // (figure out where that data is in the $variables)
  if (!empty($template_tid)) {
    // Tell Drupal to use the node--[template_tid].tpl.php template if it exists.
    $variables['theme_hook_suggestion'] = 'node__' . $template_tid;
  }
}

Note that I'm suggesting to add template suggestions based on term ID, not term name. If you build it like this, you can always change the term names without breaking your template files.

For more information about template suggestions, see Working with template suggestions.


The Zencoder API library is not installed ... zencoder in a library path such as sites/all/libraries I have installed Zencoder 2.1.1 for my Drupal 7.22 but it's not working as I see the following error:

The Zencoder API library is not installed. Download the library and install it to a directory called zencoder in a library path such as sites/all/libraries.

I have already done what it required:

[root@ip-10-128-146-179 libraries]# pwd
/var/www/html/drupal/sites/all/libraries
[root@ip-10-128-146-179 libraries]# ls -lrt zencoder/Services/
total 12
-rw-r--r-- 1 root root 7867 Jul 21 16:32 Zencoder.php
drwxr-xr-x 2 root root 4096 Jul 21 16:32 Zencoder
[root@ip-10-128-146-179 libraries]# ls -lrt
total 4
drwxr-xr-x 5 root root 4096 Jul 21 16:32 zencoder

What do I need to now?

Screehshot

I cleared all caches and ran cron and that solved the problem.

Thanks to this.


wysiwyg editors malfuction First, the problem:
I create a new Basic Page content with simple text and a couple of carriage returns, for example:

this
is
my
content.

I save the content using "Filtered HTML".  When I then try to edit that content (still with "Filtered HTML") the content in the body of the editor has lost all the carriage returns (and formatting if applied) and looks like this:

this is my content.

If I save this content it still looks like the above.

This does not happen with the WYSIWYG module installed but no editor added.  When I add TinyMCE and configure with any buttons, then I get the above problem.  This also happens with CKEditor.

I've tried three new clean installs of test sites (two on my local server and one remote) and I get the same results when I try to configure an editor with WYSIWYG.

The only non-core modules I have installed are chaos tool and WYSIWYG.

Very perplexing.  Can anyone help?

Put <br/> in view source mode of your field as your line separators.


Is it possible to remove Route objects from a RouteCollection object? When I look at the code used for the method handling a RoutingEvents::DYNAMIC event, which receives a RouteBuildEvent object, I notice the code is always similar to the following one.

$collection = $event->getRouteCollection();
$route = new Route("$path/display", array('_form' => '\Drupal\field_ui\DisplayOverview') + $defaults, array('_permission' => 'administer ' . $entity_type . ' display'));
$collection->add("field_ui.display_overview.$entity_type", $route);

Since the RouteCollection class defines the RouteCollection::remove() method, would not removing routes from the collection be possible? I was thinking of removing a route to redefine it.

There is also a RoutingEvents::ALTER event, which runs afterward.

You can think of the difference between RoutingEvents::DYNAMIC and RoutingEvents::ALTER as similar to the difference between hook_menu() and hook_menu_alter().

There is a Views issue that discusses replacing routes, as opposed to removing and adding them, perhaps follow their example.


How do I verify a route exists? In Drupal 8, I need to verify a route exists or not in a custom module. How can I achieve this?

/* @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
$route_provider = \Drupal::service('router.route_provider');
$route_provider->getRouteByName('abc.xyz');

RouteProviderInterface::getRouteByName() returns a \Symfony\Component\Routing\Route object if it exists, or throws an exception if it does not.

You can use RouteProviderInterface::getRoutesByNames() if you don't want an exception.

$exists = count($route_provider->getRoutesByNames(['abc.xyz'])) === 1;


Search in specific content type I want to make a custom search box but I only want to allow users to search in a specific content type. How can I do this?

These modules may help: Custom Search, Search Configuration


Drupal Backup and Migrate Error I'm looking to use Backup and Migrate modules to port over my website. However, even when I go and install a fresh install, update all the modules and activate them accordingly, and finally restore my database, I come out with a white page with the error below. I've done some searching around online here and elsewhere looking for a solution to the following error, and while I've found similar things none have been able to help me resolve this error:

Fatal error: require_once(): Failed opening required '/var/www/html/profiles/acquia/modules/ctools/plugins/export_ui/ctools_export_ui.class.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/includes/bootstrap.inc on line 3168

From what I've read thus far, I am getting that this is basically telling me the something doesn't exist and needs to be added into the PHP. That's where things have begun to get foggy as I continue to push through.

Thanks in advance!

The issue was while I had imported all of the past module information, I was missing the profile files.


How to add two separate GA accounts in one Drupal site I have one Drupal site and I am using google analytic module for add ing GA account? Now client want to add two separate accounts.

UA-87XXX-XX
UA-87YYY-YY

How can I add these two accounts?

Go to /admin/config/system/googleanalytics > ADVANCED SETTINGS > CUSTOM JAVASCRIPT CODE > Code snippet (after)

ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'foo'});
ga(function(foo) {
  foo.send('pageview');
});
ga('create', 'UA-XXXXXXXX-Y', 'auto', {'name': 'bar'});
ga(function(bar) {
  bar.send('pageview');
});

This worked for me.


Show a Display Suite view mode depending on a field value in the profile of the viewing user I'm not looking to use Views for this challenge here but simply to add a check for a value of a field on the viewing user's profile and then to select the correct view mode from Display Suite for that node depending on that value. What would I have to do to accomplish this?

Are you looking for code or just the approach? One approach would would be to use HOOK_entity_view_mode_alter(&$view_mode, $context) in a custom module:

Check that the user is logged in
Check that the user is viewing the right kind of node
Load the user and get the profile field value
Based on the field value, set the view mode ($view_mode = 'custom')


Display extra information adjacent to system_settings_form() output I have a properly constructed set of data coming out of a call to system_settings_form().  How can I add to that data to display additional items on the form page?

I'm currently trying (and failing with):

// ...inside drupal_get_form callback
// $form has some form elements in it
$return =  system_settings_form($form);
if (!hay_problemas()){
    $return['warning'] = array(
        '#type' => 'div',
        '#class' => 'warning',
        '#markup' => 'WARNING:  Filesystem permission are broken'
    );
}
return $return;

I think this must be

// ...inside drupal_get_form callback
// $form has some form elements in it

if (!hay_problemas()){
  $form['warning'] = array(
    '#attributes' => array('class' => array('warning')),
    '#markup' => t('WARNING:  Filesystem permission are broken'),
    '#weight' => -10, //set position relative to other $form['key']
  );
}

return system_settings_form($form);


How to print parent taxonomy term name in a block? Using Drupal 7, I want to create a simple block that will be on all taxonomy term pages that will show the first parent of the current term (there will be a tree of parents, but I want just the next highest).

The below code works to pull the current term name, but I'm unsure how to go about pulling the parent term  of this term page.

$current = taxonomy_term_load(arg(2));
if ($current):
echo $current->name;
endif;

Any suggestions?

I had to create a new question to get the answer (PHP is not my strong point).

$parent is actually an array, so it's output is a little different.  There's likely many ways of doing it, but

echo reset($parent)->name;

worked for me.


What should I set my Content-Security-Policy to? I'm using Drupal 8, and I currently use

Header always set Content-Security-Policy "default-src 'self'; nosniff"

However, this causes bugs, such as Google Analytics not working and the textbox mysteriously disappearing from the Edit page. What should I do?

The policy needs to contain every domain where assets are loaded from, which will vary depending on which services your site uses such as a CDN or third party JavaScript widgets.

For Google Analytics, it must be able to connect to www.google-analytics.com, and stats.g.doubleclick.net if Display Features tracking is enabled.
The Google Analytics module also requires the unsafe-inline policy value, since it injects the analytics snippet directly on the page.
Googalytics is an alternative built specifically for Drupal 8 that works without unsafe-inline.

Core also currently requires 'unsafe-inline' for scripts in element attributes due to its use of CKEditor 4 (see https://www.drupal.org/project/drupal/issues/2789139)

In order to test a Content Security Policy without impacting the functionality of your site, first use the Content-Security-Policy-Report-Only header instead.  This will make the browser report violations of the policy in the browser console and to the report-uri address, without blocking the content on the page.  Once you have a policy that works without violations, change the header to Content-Security-Policy.

You can also provide both headers at the same time, allowing you to test changes without the risk of breaking functionality.

Report-uri.io provides a free logging service that you can use to collect violations of both your enforced and report-only rules, and audit for any changes you may need to make.
They also have a wizard utility to help setup your policy for the first time.

Setting up a policy in Drupal 8 is also easier with the Content Security Policy module.  It integrates with Drupal 8's libraries system to automatically add script and style sources, provides an admin UI that validates your settings, provides a local handler for report violations, and will apply some optimizations to shorten the policy if possible.


How do I programmatically create an entity with its fields? I'm using Entity API to work with some entities but I cannot figure out how to create a new entity with its fields attached.  I created a bundle and added some fields to that bundle.  I'm looking to do this:

$a = entity_create(...);

return an array:

isNew => TRUE,
title => '',
attachedField1 => '',
attachedField2 => '',
etc...

I'd then like to be able to simply update the values and then entity_save() them:

isNew => TRUE,
title => 'Title of my entity',
attachedField1 => 'data for attached field 1',
attachedField2 => 'data for attached field 2',
etc...

Is this doable?  If so, how?  I'm having a tough time working with entities.

Here's my entity info:

  $return['k_profile'] = array(
      'label' => t('Profile'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'base table' => 'k_profile',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'pid',
        'bundle' => 'type',
        ),
      'bundles' => array(), //added later in hook_entity_info_alter()
      'bundle keys' => array(
        'bundle' => 'type',
        ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'access callback' => TRUE,
      'module' => 'k_profile',
    );

Here's some code that creates a product programmatically, including fields and properties.

/**
 * Create a product programmatically.
 *
 * This is stolen shamelessly from commerce_bpc. However, I'm not comfortable
 * with the field saving using form api. Seems quite odd.
 *
 * @param $product_type
 *   (string) The name of the product type for which products should be created.
 * @param $values
 *   Keyed array with
 *   - 'price' => actual amount owed on this installment; decimal text like '1.50'
 *   - 'amount_paid' => price amount already paid as a decimal text like '1.50';
 *   - 'original_order' => order id of the original order
 *   - 'original_line_item' => line item id of original line item
 *   - 'original_product => product id of the original product from which the
 *     new product is being created.
 * @param $extras
 *   An array for the values of  'extra fields' defined for the product type
 *   entity, or patterns for these. Recognized keys are:
 *   - status
 *   - uid
 *   - sku
 *   - title
 *   Note that the values do NOT come in the form of complex arrays (as they
 *   are not translatable, and can only have single values).
 * @return
 *   The ID of the created product.
 */
function commerce_installments_create_product($product_type, $values, $extras) {
  $form_state = array();
  $form_state['values'] = $values;
  $form = array();
  $form['#parents'] = array();

  // Generate a new product object
  $new_product = commerce_product_new($product_type);

  $new_product->status = $extras['status'];
  $new_product->uid = $extras['uid'];

  $new_product->sku = $extras['sku'];
  $new_product->title = $extras['title'];
  $new_product->created = $new_product->changed = time();

  // field_original_order[und][0][target_id]
  $order = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_order'])));
  $form_state['values']['field_original_order'] = $order;

  // field_original_line_item[und][0][target_id]
  $line_item = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_line_item'])));
  $form_state['values']['field_original_line_item'] = $line_item;

  $product = array(LANGUAGE_NONE => array(0 => array('target_id' => $values['original_product'])));
  $form_state['values']['field_original_product'] = $product;

  //commerce_price[und][0][amount]
  $price = array(LANGUAGE_NONE => array(0 => array(
    'amount' => $values['price'],
    'currency_code' => commerce_default_currency(),
  )));
  $form_state['values']['commerce_price'] = $price;

  // field_due_date[und][0][value][date]
  $due_date = array(LANGUAGE_NONE => array(0 => array('date' => $values['due_date'])));
  $form_state['values']['field_due_date'] = $due_date;

  // Notify field widgets to save their field data
  field_attach_submit('commerce_product', $new_product, $form, $form_state);

  commerce_product_save($new_product);
  return $new_product->product_id;
}


Conditional Fields with multiple conditions I am using Conditional Fields module. I need some guidance when setting dependencies for multiple fields (accepting unlimited values). Here is the situation:

In my entity form I have two fields:

Assignment Status --> This is Select List type with two values DRAFT and FINAL
Upload File -->  This field is required field for accepting documents from student ONLY when Assignment status is FINAL else it is optional field.

Now my question is when I am using this case and creating Dependent and Dependee relation only for one assignment this work fine but when I give an option for accepting unlimited values the Conditional Fields doesn't work.

Because one student is required to submit more than one assignment I used Paragraph Module and also tested this case also  with MultipleFields Module. I am not able to find any answer to my query. Please help me to find this answer.

You can try the module Reference Option Limit

With this module you can try to make a reference.

The documentation of this modules is here

Documentation

Is a Great module, hope i can help you


How to create and send an HTML formatted eMail using CSS? I am going crazy in making a welcome eMail in Drupal.

What I want is sending a nicely formatted eMail using HTML and CSS. I do not need to send an eMail to user except a welcome eMail after user registration, that's all.

I've tested my code in eMail field in the "Home » Administration » Configuration » People" page, but it does not accept CSS code.

HTML email and mail system modules are so sophisticated that I could not use theme.

Anybody a solution for this?

With some experience in that field I must say designing 'nice' html mail templates can be difficult – no matter what system you use to actually send your mail. The reason for this is that there are quite many different email clients – from full blown local desktop computer programms to mobile apps on smart phones and feature phones – and a virtally countless number of online services –– all behaving slightly different. Some email clients do accept css3, some don't interprete css at all, some only accept inline css.

So I suppose you probably either have to start digging into that – or use the methods that are rather 'safe' to use as offered by various services and/or modules.


How to implement facebook wall? Is there any module which works the same as facebook's user wall?

On facebook's wall, users can post/share anything and friends can also post/comment.

Yes, but it's under development.  It's called statuses.


Can the core Profile module (it is deprecated) be used? And how will I upgrade? The profile core module is being deprecated in D7.  It exists and operates in D7, but is hidden and can only be enabled with drush or a custom module.  Drupal.org recommends that users now use Profile2, a custom module, but my attempts to do so have met with WSOD on several attempts. In fact, after enabling the module, it will crash the site if you try to disable it.  The problem links to a core issue, but even with the recommended patch, Profile2 still has other problems I have not been able to correct yet.

In the meantime, I enabled Profile, and it has desirable features I would like to implement.  My concern is that whatever I do may be lost in the future.  Since I cannot load Profile2, I do not know if it builds on Profile or I will have to reconstruct everything later.

First of all, it's important to understand something MotoTribe has already mentioned. The most important functionality of "Profile" is now in for Drupal 7 new "users are entities" concept. Since this allows you extend users with fields, the profile module was considered redundant.

If I recall correctly, the main reason for it remaining in Core, was as a transition path from D6 Profile. In D8 I don't believe Profile will exist at all, and since it's already deprecated, I very much doubt there will be an upgrade path from D7 profile.

If we instead follow the trail of issues that follow from yours on the Profile2 queue, we find a Core issue, which is so far advanced that it has been applied to D8, and applies cleanly against D7 with full test coverage. I would apply that D7 patch, and try with Profile2 again.


How to create and display user content submission form? Drupal 7

Could someone point me to the right direction on how to create a submission form through which users can post content? I have a specific content type that I expect the users to fill in while submitting.

I know it's horrible, but i was thinking to link to the relevant admin page, but there must be a better way (something like Views but for submission forms)

Thanks, Markus

The create content pages are separate from Drupal's admin section. You can set up the permissions so users can add content of a specific content type but don't have access to any other content types or the admin section.

There's also a permission 'View the administration theme' if this isn't set for a particular role, but they can add content, then the Create Content page will use the default theme. There's also a setting at the bottom of the appearance page, if you deselect 'Use the administration theme when editing or creating content' then everyone who accesses the create content pages will use the default theme also.


How to use Composer to install third party libraries All I thought Composer takes care of any external library a contrib module requires automatically. I tried installing one, Composer took care of all its dependency modules, but not so much with the external library.

How do I use Composer to install external libraries that any module depends on?

It is not recommended to installing JavaScript libraries using composer.json, but it is possible.

Note: This repository type has a few limitations and should be avoided whenever possible:
Composer will not update the package unless you change the versionfield.Composer will not update the commit references, so if you use master as reference you will have to delete the package to force an update, and will have to deal with an unstable lock file.

(Composer docs)
If your package is available for download at an external source, e.g. as an archive, you could add it as custom package with type drupal-library to the repositories section of your Drupal project's composer.json, and then require this package accordingly:
"repositories": {
  "drupal": {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  },
  "mypackage": {
    "type": "package",
    "package": {
      "name": "myvendor/mypackage",
      "version": "1.0.0",
      "type": "drupal-library",
      "dist": {
        "url": "https://example.com/mypackage.zip",
        "type": "zip"
      }
    }
  }
},
"require": {
  ...
  "composer/installers": "^1.2",
  "myvendor/mypackage": "1.0.0"
},
"extra": {
  "installer-paths": {
    "public/core": ["type:drupal-core"],
    "public/libraries/{$name}": ["type:drupal-library"],
    "public/modules/contrib/{$name}": ["type:drupal-module"],
    "public/profiles/contrib/{$name}": ["type:drupal-profile"],
    "public/themes/contrib/{$name}": ["type:drupal-theme"],
    "drush/contrib/{$name}": ["type:drupal-drush"]
  },
  ...
}

Check the Repositories documentation for Composer for more details or other source types.


How to link views content nodes to custom URL I have nodes in a view using a custom view mode (using Display Suite).  I'm doing some AJAX stuff when the user clicks on a particular node, so I need to wrap the nodes in a custom URL, like somenode/nojs/(nid).

I feel like I should be able to do this in Views, since fields can link to the content.  Is there a way to get the node to link to a custom URL?

I don't know if you can get the node link in a custom URL, but you can overwrite the output of the nid field.

Steps:

1. Add NID field

2. Hide field (this might change depending in your setup)

3. Go to the overwrite section and overwrite the NID output

4. The rest is up to you. You can display a field as a link and add the NID field as a replacemente pattern or use it as is.


WHen I delete products andvariations via VBO some are still left I delete all my products and also the variations were deleted at the same time

but still after VBO delete under commerce/#overlay=%3Fq%3Dadmin%252Fcommerce%252Fproducts

some products are still left

why? I am attaching the image, there are empty products without variations inside that I cant delete

why is this happening?

In Drupal Commerce there are products and product displays. Did you delete the products and perhaps these are the remaining displays, which aren't displaying properly because you deleted the products?


How to write a Drush script to retrieve data? I want to retrieve a field value by given nodes. Node has a field 'promo code'.

How can I retrieve imageurl value by giving 'promo code' field using a drush script?

What is the better way to do it?

I want to get data as a JSON or XML format for all the given nodes.

You can start checking the code of the Drush Entity module.

  With drush entity you can query the entity system available for Drupal
  8, 7 and (some of) 6.

And as Greg says you can use the Drushify module to start.

In this links you can find good references:

How to Create Your Own Drush Command
How to write drush commands and hooks
Drush Integration for your modules


How to create a Drupal 8 distribution So I have this Drupal 8 site with its custom theme, some blocks, menus, content types, views and other more stuff. What I am required to do is create a site distribution of this site for drupal.org, but I have absolutely no idea of how to do it.

I created the profile folder in doctoot/profiles and created the info.yml with the profile basic information. I also have the .install and .profile files but they are empty. These files were created using drupal generate:profile

After that I exported the config YAML files using drush config:export, but they were created in config\sync in the profile folder, but I saw in another distributions that these files are located in config\install rather than sync,and I don't know if that makes a difference.

I don't have anything besides that and I don't know what to do after that to configure things in the distribution in terms of theme and configuration. I have the project page in drupal.org already with the git configuration. Hope you can help me with this issue.

What you need is to create an installation profile.

Follow the instructions on drupal.

How to write a D8 profile

Move the files from the config/sync folder to config/install folder. Be sure to delete core.extension.yml and remove all UUIDs.

Optionally, you can try this project:project config_installer


How do I add authentication to a POST request on an implementation of hook_menu? I have a list of lesson plans, sorted by category. Underneath each category, I have a link called "Add new lesson/category/root term".

I would like it so that when the user clicks on "Add new category" or "Add new root term", they are prompted with a message box to get the name of the new term to add. Then, that message box will make an ajax call to mysite.com/add-new-term, with the name of the new term as a POST argument.

I know how to make an HTTP POST request using jQuery.post(). I know how to implement hook_menu() to enable requests to mysite.com/add-new-term. And I know how to use PHP's superglobal array $_POST to get the data from the request.

BUT, I don't know how to add user authentication to the request.

How can I ensure that only logged-in admins can make these requests? I don't want just any random person on the web to be able to create new terms.

Turns out this is actually really easy.

You can get the current user's roles with:

global $user;
$roles = $user->roles;

That returns an associative array with the roles as values. Getting the values is trivial with in_array():

if (in_array("Teacher", $user->roles)) {
  // allow the post request to have effect
}
else {
  // don't go through with the request; return an error
}

Because the module is called during the lifecycle of the Drupal structure, you have access to the whole environment.


Multiple facets are shown with Content fields with multiple words I implemented filtering through facets and facing a very strange problem.

I have been trying a content type with a field for Region. Region contains options like North America, Latin America, Asia, etc. In my facets, it ends up looking like this (screenshot attached as well):

REGION:
america
asia
north
latin

What I am hoping is that it shows me the way I entered it in the system.

Why is it breaking at the spaces and turning "North America" into "North" and "America"?

The field type is "Text" though.

Found the solution.

I was using Search API for indexing, and within that type of field to index was set to Fulltext. I changed it to String and it got fixed.

Thanks.


Show full list of nodes that reference the node being shown I have a content type (let's call it course) and a content type named edition (if we have a course named "English 101", we can have "English 101 - June", "English 101 - July" and so on.) For this, I used Entity Reference.

If I see the node "English 101-June", I can see the "parent" node being rendered (I chose that on Manage Display". What I want now, is when I see the "parent" node "English 101" the full list of referenced nodes to be rendered. How can I do this?

There are a number of ways to get reverse references. Probably the best option is to use the Views module. The reference module allows to create a reverse relationship in the view. You could do something like this:

With the Views module, create a view of nodes with a page display at path 'myview' ;
Set up your view to display only the title of each node ;
In your view add an argument that matches your node id ;
In your view add a reverse relationship that matches the field that is used to reference content. The name to use for the relationship would be something like field_my_reference_field (reverse)

Save the view, now go to 'myview/1' and you will see all the nodes that reference node 1. You could also get this displayed in a block, or as a field using the ViewField module.

If you don't want to use the Views module, then you can use the Nodereferrer module to achieve this. However in that case you can only get the list as a field - you can't get it as page or a block.


Add a file field to a block I have a problem concerning the blocks in drupal.

I need to create a block that has additional fields, image and files, I am currently using the add block feature in Home » Administration » Structure and I just need to add two fields there so I can upload pdf's and images.

I was thinking that there must be a way to add those fields from the admin panel, without programming it by hand or installing modules? Is it possible ?

No.

Blocks aren't entities in Drupal 7, so there's no real way to add fields to them.

If you want fields on blocks, then take a look at the awesome Bean module.

  Beans were driven by the API first. This means that you can create
  block types (bean types) all in a plugin class turning off the UI. The
  entire configuration in code. No worry about feature reverts.


How to make wkhtmltopdf work on Drupal I have installed the drupal Print module, but have not been successful in getting wkhtmltopdf to work. The drupal print documentation is outdated and despite of a number of request to update it, it still is outdated. https://www.drupal.org/node/306882

CASE DESCRIPTION
In my case, I want to allow the creation of pdf versions of nodes. The Nodes have inline CSS (using Tinymce editor with Wysiwyg). I tried using Dompdf library, but the inline css is not being used for the created pdf.

I have read that wkhtmltopdf creates an internal browser that renders a html page, so that should be the ideal solution in this case.

However, after downloading the rpm file from http://wkhtmltopdf.org/ into the sites/all/libraries folder of my website, and installing it using
   rpm -Uvh wkhtmltox-0.12.2.1_linux-centos6-amd64.rpm
in my website, the library is not recognized, not visible in the status report page and not in the pdf configuration page /admin/config/user-interface/print/pdf

In addition to Yuri's answer, I wanted to provide more detail for how I solved this issue, where I couldn't resolve the following error:

  No PDF generation tool found! Please download a supported PHP PDF generation tool

install the print module
install pdf php handlers and libraries for your environment from https://wkhtmltopdf.org/downloads.html; see note
create symlink in sites/all/libraries/wkhtmltopdf to library in server; make sure symlink is executable to the server sudo chown -h [owner]and sudo chgrp -h [group]
install and enable phpwkhtmltopdf
run drush make --no-core -y sites/all/modules/contrib/phpwkhtmltopdf/phpwkhtmltopdf.make
enable print_pdf_wkhtmltopdf
set up and customize; see recommendations in this blog for more
info

Note: My local dev environment is on a Mac OS X so I had to download and run the package, then create a symlink to sites/all/libraries/wkhtmltopdffrom /usr/local/bin/wkhtmltopdf

Sources:

https://www.drupal.org/node/2430561
https://www.sitepoint.com/effective-pdf-generation-drupal/
https://wkhtmltopdf.org/downloads.html


How to create and send via email a PDF file with rules? I need to create and send via email a PDF file with Rules using Drupal 7. I need to send it as an attachment, not as a link.

I found this post,  Generate PDF with Print PDF and send in email, but Views PDF MIMEMail is a D6 module.

How can I do this?

You should write a port to Drupal 7. The Views PDF MIMEMail module codebase is pretty lightweight (~300 LOC). Essentially, it's a

.info file declaration
A .module declaring a theme function
Various Rules integration functions (.rules.inc).

You can figure out how to convert the .info & .module by Googling around how to convert a .info to D7 and look up how hook_theme() changed in D7. There's a comprehensive guide on porting D6 modules to D7 if needed.

As for #3, the Rules module has some internal documentation that describes how to integrate Rules in D7. There's likely a few structural changes you'll need to do, but essentially most PHP code should stay the same.