What stops the import of the rule contained in my custom module?

Assuming this is for D7, try this variation of the your code in your item "3)":
<?php
     function my_module_default_rules_configuration() {
      $configs = array();
      $rule = '{ "rules_final_save_pdfs" : {
        "LABEL" : "final save pdfs",
        "PLUGIN" : "reaction rule",
        "ACTIVE" : false,
        "OWNER" : "rules",
        "REQUIRES" : [ "rules", "views_pdf", "entityform" ],
        "ON" : { "entityform_insert" : [] },
        "IF" : [
          { "entity_has_field" : { "entity" : [ "entityform" ], "field" : "field_test_pdf_form" } }
        ],
        "DO" : [
          { "views_pdf_rules_action_save" : {
              "views_pdf" : "test_new_view:pdf_1",
              "path" : "\/workout\/sites\/default\/files\/test_pdfs\/[entityform:field-date]"
            }
          }
        ]
      }
    }';
      $configs['rules_final_save_pdfs'] = entity_import('rules_config', $rule);
      return $configs;
    }
?>

Note the changes in the line with function ... (near the top) and the line with entity_import (near the end).
Be aware: if I try to import your rule (= the string contained in $rule) in a site of mine (where I don't have views_pdf module enabled), and using the Rules UI, I get an import error like so:

Import failed.
Missing the required module views_pdf.

That makes sense of course (since I don't have that module). So check that that is not the case why your rule isn't imported (same for entityform). A possible technique to prevent this issue, is to declare those 2 modules as a dependency in your my_module.info file.
PS: have a look at the code of the Answers Userpoints module for an example where this technique is used also.


Show repeating event just once in Views while sorting by date

I just ran into this issue myself.  The solution is to add a filter of the date delta field =0.  This means only show the 0th (first) matching item and hide any repeating values.

Hope this helps someone.
Selwyn


Problem with specialchars/tokens sent by email with rules module

The good way is to use the -raw output :

[node:field_company_nid-title-raw]


Update node alias while retaining the old alias

Ultimately, a VBO action affecting a node is going to call node_save() which will change the changed node property that determines when the updated marker appears.

To get around this, you'll need to preserve the node changed timestamps following your bulk alias updating. You can do this by directly updating the node.changed column in the database.

Depending on your preferences, there's many ways to backup/restore database data. For example, executing a Drush snippet before node alias bulk updating could dump a JSON file with your nid/updated timestamps:

drush ev '$nodes = db_select("node", "n")
  ->fields("n", array("nid", "changed"))->execute();
$timestamps = array();
foreach ($nodes as $node) {
  $timestamps[$node->nid] = $node->changed;
}
echo json_encode($timestamps);' > my_node_timestamps.json

Following bulk alias updating, another snippet could restore it from the JSON:

cat my_node_timestamps.json | drush ev '
$timestamps = json_decode(file_get_contents("php://stdin"));
foreach ($timestamps as $nid => $timestamp) {
  db_update("node")
    ->fields(array("changed" => $timestamp))->condition("nid", $nid)->execute();
}
'

As the case with any operations directly touching your database directly, make sure to perform backups before performing any such bulk operation.


How to prevent users of particular role to access the content view (node view) of a particular content type?

Ok  there was a mistake from my side

the view 'any delivery_challan content' permission was given to
authenticated user.
And by default any user has role authenticated user.
So User having role 'Data Admin Operator' was able to view any delivery challan content as user also has the role 'authenticated user'
So the solution is to remove the authenticated role from the list of roles under the view any delivery challan content


How to clear page cache without rebuilding other caches

You can use Flush Page Cache or Cache Actions module.
See if either of them solves your problem.
Flush Page Cache:

Easing the pain when you need to flush...Drupal's cache.
Flushing Drupal's cache on a large site can feel like you're waiting to takeoff on the tarmac at JFK. The delay comes from the fact that when you clear Drupal's cache, it clears everything. Most of time you just want to flush the cache for specific object on a page.
The Flush page cache module solves this problem by flushing only the cached objects for a single page. Additionally, you can define custom objects and cache tables to be cleared on specific pages.

Cache Actions:

Cache actions provides rules actions for clearing drupal caches.
It currently provides actions for:

Clearing Drupal cache bins
Clearing CSS/JS cache
Clearing The cache of specific views
Clearing The cache of specific panel pages
Clearing The cache of specific mini panels


Create a new facet block from Taxonomy terms

Here is a tutorial for creating facet blocks :Faceted search using search api tutorial

To add a taxonomy term as a facet just check the fields tab to find your term field and enable it and after enabling it you have to re-index and now your facet can be rendered as a block !!!


Yes - Views. :)

Just create yourself a comment-based view and configure it the way you want. I guess you won't be able to have an in-place editing here, but everything else should be easy achievable.


I couldn't get the i18n_panels module to work, but the Multilingual panels module works a treat.

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


How do I revert the changes made by a specific user?

If you don't have revisions you can't rollback the changes unless you have a database backups that you can use to restore and old copy of your site.

If you don't have any strategy to save your database you can consider use the Backup and Migrate module, for Drupal 6 the last release is the 6.x-2.8

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.


How do I get Facebook latest uploaded images for an account?

I have resolved this in two ways.

First I use Facebook FQL query to get the image of Facebook page posts image. You can find the code from here. Facebook Platform API versions after 2.0 will not support FQL. So I get the images using Facebook graph API.
Then I get Facebook post images using Facebook graph API. Here is my code: Firstly you should have to get page id from where you want to get post images. From here you can get the Facebook page id.

After that use the code:

$data = file_get_contents("https://graph.facebook.com/page_id/photos/uploaded");
$results = json_decode($data);
foreach ($results as $value) {
  echo '<img src="'. $value->source .'">';
}


You need to attach the fields separately, they can't be added through hook_node_info(). You would usually do this in a hook_install() function in your module's .install file.

A nice simple example from Drupal core is in the blog module's install file:

function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

The function simply rebuilds the node types (so the newly added type is available), then adds a body field to it using the node_add_body_field() function. This function in itself gives an excellent example of how to create a field, an instance of that field, and then attach it to a content type using the field_create_field() and field_create_instance() functions.

The code isn't that so long so I'll include it here as an example:

function node_add_body_field($type, $label = 'Body') {
  // Add or remove the body field, as needed.
  $field = field_info_field('body');
  $instance = field_info_instance('node', 'body', $type->type);
  if (empty($field)) {
    $field = array(
      'field_name' => 'body',
      'type' => 'text_with_summary',
      'entity_types' => array('node'),
    );
    $field = field_create_field($field);
  }
  if (empty($instance)) {
    $instance = array(
      'field_name' => 'body',
      'entity_type' => 'node',
      'bundle' => $type->type,
      'label' => $label,
      'widget' => array('type' => 'text_textarea_with_summary'),
      'settings' => array('display_summary' => TRUE),
      'display' => array(
        'default' => array(
          'label' => 'hidden',
          'type' => 'text_default',
        ),
        'teaser' => array(
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ),
      ),
    );
    $instance = field_create_instance($instance);
  }
  return $instance;
}


Drupal 8 follows PSR 4 autoloading standard which is implemented by composer autoloader.

While some Drupal namespaces are registered statically in composer.json and core/composer.json other namespaces are processed dynamically (see DrupalKernel::classLoaderAddMultiplePsr4).

PSR-4 namespaces and autoloading in Drupal 8


Sorry, Drush reserves all short (-f) options for use exclusively by Drush core.  You cannot define them in contrib extensions.

See the function drush_get_global_options for an example of how to define options that have attributes; the short option is 'short-form', although this does not work right for non-Core commands.


How can I create my desired template name suggestion?

If you want to have more meaningful template suggestions, why don't you use better region names and block ids?

Region names are up to your theme, so instead of footer_1, use footer_something, and block configuration names are also up to how you configure/name your blocks.

You could use PHP to filter those things out, that's nothing really drupal specific, but that's likely increasingly complicated as you will have blocks and regions without those number suffixes, so you need to be caruful in not cutting those off.

Also, you could use suggestions based on the block plugin ID, not configuration ID, then placing the same menu multiple times will give you the same template suggestion.

Edit: If you really want to get rid of those kind of suffixes, then you could for example use trim:

rtrim('footer_1', '123_');

You can put whatever characters in there that you want, and it will remove them all from the right side of the string (there is also ltrim for left and just trim for both sides). Note that this will also remove a _ at the end if you have that.


Changing the view mode of EntityReferenceFieldItems programmatically

At this point it should be no problem to change the view mode in the render element of the referenced node. The node has yet to be built and will, hopefully, use the modified view mode.

You can try something like this in a paragraph preprocess hook:

function mytheme_preprocess_paragraph(&$variables) {

  if ($variables['paragraph']->hasField('field_view_mode')) {
    $view_mode = $variables['paragraph']->field_view_mode->value;
    if (isset($variables['content']['field_ref_node']['0']['#view_mode'])) {
      $variables['content']['field_ref_node']['0']['#view_mode'] = $view_mode;
      unset($variables['content']['field_ref_node']['0']['#cache']['keys']);
    }
  }

}

Edit:

To prevent that the node gets cached on it's own in the wrong view mode remove the cache key.


You are missing the System help block.

That is what is displaying the current help tips:

SS http://tardis1.tinygrab.com/grabs/99f4a5fef70efc8f19ddb137c664c7cf22b0599ff5.jpg

When you activate the block the help tips will be displayed whenever possible.


Created a module that has a form: How do I display on a page?

You should use hook_menu().

function member_survey_menu() {
  $items['member-survey'] = array(
    'title' => 'Your title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('your_form_function'),
    'access arguments' => array('access content'),
  );
  return $items;
}

Replace your_form_function with the function that generates the form.

Replace array('access content') with your desired permissions.

You can also use the webform module instead of writing a module.


Mollom tests content for spam. But user creation form does not provide any opportunity to provide spam content in the first place. So you have 2 strategies available:

Protect user creation form with more traditional captcha, or one of it's mutations like reCaptcha or little game humanity test.
Protect comments / node forms with Mollom and automatically block users that will fail mollom test there.

Note, above ways are not mutually exclusive.


Drupal 7 and google maps v3. Which is the module to use ?

The approach should be map agnostic. You need to break things in two parts:

Storing location data
Displaying this data on a map

1) Data storage.

You'll need three modules here:

Address field to store addresses (http://drupal.org/project/addressfield)
Geofield to store latitude/longitude (http://drupal.org/project/geofield)
Geocoder to geocode addresses from addressfield into lat/lon for geofield (http://drupal.org/project/geocoder)

It may look difficult, but it is really easy to configure these three modules to play nicely.

2) Data display.

Now having data stored in database we can choose any display approach we want. Here you have two+ choices:
  - GMap (http://drupal.org/project/gmap)
  - OpenLayers (http://drupal.org/project/openlayers)
  - As a third option, you can have a custom js code which plays with Google Maps

Everything depends on your final goal. OpenLayes plays with different map engines and to me it looks a bit bloated. If you go with GMap you'll get Google Maps V3 support which is better to stick with instead of Google Maps API V2. Google Maps API V2 development has stopped, no new features are being rolled and it can be abandoned at any moment, so why to risk?

Go with custom js maps code if GMap module doesn't give you what you need. But I do really suggest you to look at GMap module a little bit closer.


How can I output log messages to stdout/stderr?

I’ve been using the log_stdout module for stdout logging. It works well with Docker containers.

This module provides a hook for Drupal Watchdog that directs log messages to php://stdout or php://stderr for better log handling with Docker.


Best way to benchmark Drupal stack performance

I like jmeter, http://jakarta.apache.org/jmeter

It allows actual benchmarking of authenticated sessions, which many of the other approaches like ab do not. There's an article about using jmeter with authenticated users at this link


How to filter Date Views with correctly timezone

Ok, I made it working.
My solution is created a custom drupal 8 module with the file: .views_execution.inc inside your module folder.

Inside that, I added function modulename_views_query_alter($view, $query) with:

//Filter by timezone for bettingsafe's local ip
switch ($view->element['#name']){
    case 'league_match':
        $key = 0;
        foreach ($query->where as $key => $value){
            $key_2 = 0;
            foreach ($value['conditions'] as $key2 => $condition){
                $length = strlen('DATE_FORMAT');
                if (substr($condition['field'], 0, $length) === 'DATE_FORMAT'){
                    $condition['field'] = str_replace('DATE_FORMAT(<date field>', 'DATE_FORMAT(CONVERT_TZ(<date field>, <from timezone>, <to timezone>')', $condition['field']);
                    $query->where[$key]['conditions'][$key_2]['field'] = $condition['field'];
                }
                $key_2+=1;
            }
            $key+=1;
        }
    break;
}

From my server Centos, I install the tool CONVERT_TZ:

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql -p<sql root's password>

Restart mysqld and clear Drupal cache.

Hope that's will help someone.


That's a very broad question so I can only really give a very broad answer. There are two options that I know of for this type of workflow:

The aptly named Workflow module

  The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.

A combination of the Workbench and Workbench Moderation modules

  Workbench provides overall improvements for managing content that Drupal does not provide out of the box.

  Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.


How can I programmatically alter Webform "To Email Address"?

I think a more apt place to alter the destination email would be hook_mail_alter() where Drupal lets you alter an email before sending it out. The webform module includes all the submission data in the $message['params']['submission'] object.

You can do something like this in your module:

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {

  //Catch Webform submissions when we have a valid postal code
  if($message['id'] == 'webform_submission') {
    $postal_code_component = 5;
    if(isset($message['params']['submission']->data[$postal_code_component][0])) {
      $postal_code = (int) $message['params']['submission']->data[$postal_code_component][0];

      //Find right addressee to switch to
      if(0 <= $postal_code && $postal_code <= 13999 ) {
        $message['to'] = 'addressee.1@example.com';
      } elseif(14000 <= $postal_code && $postal_code <= 14990) { //Etc...
        $message['to'] = 'addressee.2@example.com';
      } else { //Catchall
        $message['to'] = 'addressee.3@example.com';
      }
    }
  }
}


Exposed filter (by terms), only to show terms related to this content type

You can use hook_form_alter to alter the exposed form:

<?php
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'form_views_exposed_form') {
    drupal_set_message("Form ID is : " . $form_id);
  }
}
?>

Just write some code that fetches all the used categories in content type A and compare those with the categories in the dropdown. Then, unset the categories that aren't used.

You can do this by building an array that has the same structure as the options in the drop down and then use array_intersect to get all the values that are shared over your custom build array and the options in the dropdown.


Wrapp every form item select with div, excluding label

This theme function should do what you need.

function mytheme_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '
<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>
';
}


Replace the underscore with a hyphen, and you get the name for the template file.

If the suggestions you are getting are the ones reported by theme_get_suggestions(), then they are the ones returned from template_preprocess_html() for a page at /profile_personal/113/edit.

The first suggestion would be applied for all the pages with a path starting with /profile_personal/; the last suggestion would be applied also for a page with path /profile_personal/edit, and the one before the last would be applied also for /profile_personal/113/revisions.

Whichever you choose, you should always check the path of the currently show page, via arg().


You can set the "threading" option for each node type on the node type form (eg. on admin/structure/types/manage/article, where 'article' is the name of your content type). Deselecting that will put all comments in chronological order.

As far as I can see, the setting for the sort order (newest first/oldest first) was removed in this issue, but I'm not sure why.


how to delete a node programitically in drupal 6?

The node_delete() function requires to have the delete permission for the current logged user.
If you run the node_delete() function as anon user, is probably that doesn't work


Sort a View by whether content has a user reference

I have an idea!  Use your current block to limit the list to users who are referenced in the node, and then add an ATTACHMENT to the block listing users who have flagged it who weren't referenced in the node.

That way you can separate them our and sort independently, but they'll still appear as if they're displayed in the same view.

Here are the exact steps:

Add an additional relationship that is the node user reference field, but reversed:

I added the 'Content: nid' field with the above relationship to my view just while testing, and that was helpful, so I'm including it as a step...
Add that field 'Content: nid' using the user-reference relationship to your set of contextual filters too, if you're using it, to make sure the content they're referenced in is the current node (don't want to sort them first just because they're referenced in SOME node on the site, right? ;-))

Add an attachment to your view, and set it to display directly after your existing page or block.  In this one, you'd want to do the exact same as above, however, when you're setting the contextual filter, select to 'Exclude' the matching answers (you'll find that check box in the collapsed 'More' section at the bottom.


It is working for me. I have created a module called testtheme and mytemplate.tpl.php file is under testtheme/templates/.

Please try following sample code

/**
 * Implements hook_block_info().
 */
function testtheme_block_info() {
  $blocks['testtheme'] = array(
    'info' => t('Test Theme'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function testtheme_block_view($delta=0) {
  $black = array();
  if ($delta == 'testtheme') {
    $block['subject'] = t('Test Theme');
    $args = array(
      'title' => 'Filter by Town / City',
      'locations' => 'Bangalore',
    );
    $block['content'] = theme('list_city_display', $args);
  }
  return $block;
}

/**
 * Implements hook_theme().
 */
function testtheme_theme() {
  $path = drupal_get_path('module', 'testtheme');
  return array(
    'list_city_display' => array(
      'variables' => array(
        'title' => NULL,
        'locations' => NULL
      ),
      'template' => 'mytemplate',
      'path' => $path . '/templates',
      'type' =>'theme',
    ),
  );
}


Ajaxy entity reference views filter by entity reference view

I'm not sure this question has a good, Drupalish answer.  I've got a crazy idea, though, that you might try.

Instead of letting your users go straight to node/add/typeA, send them first to a custom page where they choose their size. That link will then send them to the node add screen with a TID tacked onto the end, like /node/add/typeA/34.

On the node creation page, your custom module will automatically select the right Size term based on the URL path, and disable the widget so the user can't change it.

In your Entity Reference view, when you provide a default value to your contextual filter, instead of "Taxonomy term ID from URL", simply choose "Raw value from URL" and set the Path component to 4. With any luck, the Entity Reference view will get the TID from your modified URL and show the right list.

When they try to edit that node after creation it gets a bit tricky. You could just forcibly redirect the path to node/[nid]/edit/34 and do the same thing, but now you've made it so the user can never change the category after they select it the first time, which is bad. Maybe you can hijack node/[nid]/edit and send them to your custom page again? I've never seen that done before.

This whole idea kind of craps up the usability of the site, but it's the best idea I can think of, short of writing your own custom AJAX stuff to provide your argument to the ER view manually, rebuild the form, etc.


Multisites with different database share rules

SOLVED: Problem appear when a sigle site (default) is moved to a multisite (sites/XXX).
SOLUTION: erase rules in the other site don´t erase in the original site.


Because you are on shared hosting the PHP process may not be given enough memory.  If you have a complex site or page the drupal bootstap may run out of memory and fail. I have had this problem trying to run a heavy site (one of the more Drupal complex distributions) on a shared host.  I would take a quick peak at how much memory is given to a PHP process (and Drupal) by visiting admin/reports/status and look for the "PHP Memory Limit".  I typically use 128M on a complex site.

You said also you can't edit you php.ini file - are you certain?  Many shared hosts allow you to to override the global php.ini file with one in your account.  Most will have a wiki explaining how configure such overrides.  If not you may need to move to a different host.


The Fast Permissions Administration module is the closest equivalent that I've found

  This module is here to alleviate frustration when trying to manage permissions in Drupal. By providing a better permissions interface hopefully a few innocent keyboards and mice can be saved.

You get a UI like:


Since you specifically mention the Features module in your question, (also mentioned in the upvoted and accepted answer to: How do I manage collaborative development on a Drupal site?) I shall assume you're asking about how to share the database and code under development among team members, and not about tools for team collaboration ("groupware") in general.

First, let me say that I don't think Features is the right tool for this task, and shall propose an alternative set of tools.

A prerequisite for team collaboration is to have a staging server for testing out development versions of the project that is separate from your production server.  All development code is tested at the staging server, and only pushed to production server when it is stable and ready for deployment.  However, the developers doesn't work directly at the staging server.   Each developer work at his or her own workstation, using a revision control and source code management (SCM) to coordinate his or her work with the rest of the team.

The SCM system allow team members to work in parallel on different branches of the code without interfering with each other.  Only the master branch is deployed on the staging server for testing purposes.

To mirror the database between production, staging and workstations, there is a module named Backup and migrate that can be used if you're on shared hosting and not managing your own database. If you're managing your own database server, this is the only project on that server, and you use mysql, the following pair of commands are handy:

To dump:

mysqldump --all-databases --opt -u root -p > DUMP.sql

To restore:

mysql -u root -p < DUMP.sql

If yours is not the only database on that server, script some version of mysqldump (or equivalent if you're not using mysql) that dumps your databases only.

Make a policy that it is the database on the production server that is master.  The staging server and workstations should be a copy of the production database, not vice versa.

Note that Drupal 7 keeps all its admin setting in the database.  This means that mirroring the database between the production site, staging site and workstations will migrate admim settings without Features.

Now, for sharing the code:

The standard way for sharing code among the members of a development team is to use SCM system.  Drupal happens to be default be managed with such a system named git.

Git allows the use of local or remote repositories.  If the team members are located in the same physical space, you can set up a local repository on your staging server.  If they're spread geographically, you can set up a remote repositiory.  If you don't mind others having read access at your code under development, you can use a sandbox at Drupal.org as a remote repository. You can also use a project area on GitHub.  GitHub is not only a repository, but comes with a some tools for collaboration, and allows both public and private repositories.

Basically, a SCM system allow team members to pull source code and documentation from  the respository shared by the team members, and push it back in again after having worked on it.  The SCM keeps track of changes and if there is a conflict (i.e. somebody tries to push code that doesn't the contain the changes another team member has committed), it will tell you and also suggest a way to resolve this conflict.

Usually, with some cordial communication about how the tasks are divided among the members of the team, there will be no conflicts.  But with the SCM system keeping track of things, conflicts become manageable even if mistakes are made or communication fails.

There exists a lot of tutorials on getting started with and using git (GIYF).  Two I will recommend are: the git-scm website and Pro Git by Scott Chacon.


How to limit a user to one vote when using Fivestar?

You can easily do this using a custom module that contains code similar to the following one.

function YOURMODULENAME_print_rating($nid, $fivestar_widget) {
   $path = drupal_get_path('module', 'fivestar');
   drupal_add_js($path . '/js/fivestar.js');
   drupal_add_css($path . '/css/fivestar.css');
   $voting_message = '';
   $output = '';
   $is_login = user_is_logged_in();
   $rating = votingapi_select_single_result_value(array(
       'entity_id' => $nid,
       'entity_type' => 'node',
       'tag' => 'vote',
       'function' => 'average',
   ));
   if ($is_login) {
     if (isset($rating)) {
       $voting_message = "
You have already rated this.
";
       $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
     }
     else {
       $output = render($fivestar_widget);
     }
   }
   else {
     $fivestar_links = l('Login', 'user/login') . ' or ' . l('Register', 'user/register');
     $voting_message = "
Only registered user can rate this content type.
$fivestar_links to rate this content type.
";
     $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
   }
   return $output;
 }

Use the below snippet in your node template file.

hide($content['field_fivestar_rating']);// This line will hide the stars which are coming from the fivestar module.
print YOURMODULENAME_print_rating($node->nid, $content['field_fivestar_rating']);// This will print the fivestar.


How to edit the Comment Administration Page

I'm not too familiar with the comment system in Drupal, but you should be able to.

First check that the commment admin page is loading the theme you are using and not a system  admin theme (Link to a screenshot if you are not sure).

If it is loading your custom theme then inspect the elements that you want to wrap as you may already have unique classes that you can use to style. Even the body tag should have unique classes for the comment admin section or you could add unique body classes in the template_preprocess_page function in template.php

If it is loading an admin/default theme you have 2 safe options:

Set drupal to load your custom theme for admin pages (but then you would have to style all the admin pages)
Copy & rename the admin theme, and set Drupal to load the copied theme for admin pages and change the styles in the copied theme.

If you know PHP well enough you could add your own template but you would have to override the default Drupal hook -  hook_comment_admin_overview() and add a template to the form with the theme() function (if a template file doesn't exist) but that could be quite difficult to get working without breaking.

Finally, if all else fails the quick dirty way would be to add html wrappers with jQuery but this is not recommended.

EDIT

Please check in your theme's html.tpl.php you have this code snippet:

<body class="<?php print $classes; ?>"

There should already be classes that are added to the $classes variable when editing a comment.


Open the AJAX Login/Register popup when clicking on post titles

You simply have a typographic error. Use "class=..." instead of "classes=..."


Create hook menu with custom module (child/%)

try to follow this code

<?php
/**
 * Implements hook_menu().
 */
function example_menu() {
  // In this example, the third parameter will be passed.
  $items['admin/example/%'] = array(
    'title' => 'Example of first parameter being passed',
    'description' => 'This has a page arguments index of two because the wildcard occurs at the 3rd parameter',
    'page callback' => 'one',
    'page arguments' => array(2),
    'access arguments' => array('access administration pages'),
  );
  // The third and fourth parameters are being passed, hence we need to create an array with values 2 and 3 for the page arguments key
  $items['admin/example/%/%'] = array(
    'title' => 'Example of multiple parameters being submitted',
    'description' => 'Example of multiple parameters being submitted',
    'page callback' => 'two',
    'page arguments' => array(2, 3),
    'access arguments' => array('access administration pages'),
  );

  return $items;
}

/**
 * One parameter being passed.
 */
function one($one) {
    return $one;
}

/**
 * Two parameters being passed.
 */
function two($one, $two) {
    return $one . ' ' . $two;
}

Thank You.


Rendered entity reference field (list-group) disappears, when user can't access the referenced items. Why?

FWIW :

The entity reference field formatters that are in core use the method getEntitiesToView() (From class EntityReferenceFormatterBase) to load the referenced entities.

This method honors entity access :

$access = $this->checkAccess($entity);
// ...
if ($access->isAllowed()) {
  // ...
     $entities[$delta] = $entity;
    }
//...
return $entities;

so yes, it seems normal that nothing is rendered.


Form generated from form cache displays, but missing name and value attributes

Figured it out. Use form_get_cache() to get the cached entity, throw that into $form_state, and then use drupal_build_form() to put it together again.

    $form_state = array(
        'submitted' => FALSE,
        'rebuild' => FALSE,
        'cache' => TRUE,
    );

    // Pull the entity object from cache.
    $cached_form = form_get_cache($form_build_id, $form_state);
    $myentity = $cached_form['#entity'];

    $form_state['myentity'] = $myentity;
    $output = drupal_build_form('myentity_form', $form_state);


display nodes of types on a menu item : drupal 7

Is it just the book name? Like a list of the names and then you can click on it and view more information? In that case, you could just put those book links in the menu itself (if you have a drop-down).

Otherwise, and the more doable option is to just use Views and have it create a page that displays the names of all of the books you've entered.

Is there a reason why you are opposed to using Views to do this?


Drupal 7 form alter required field is not working when i used field from "Add existing field"

Try

$form['field_email']['und']['0']['value']['#required'] = TRUE;

and if not work then try

$form['field_email']['und']['0']['#required'] = TRUE;


Save button missing on User Account Edit form

Try disabling i18n synchronization module.

There is another question similar to yours. Save button missing from content type edit form
Problem: save button missing from content type edit form. Reason: bug in i18n synchronization module. Solution: none here, but...

There is another case where i18n synchronization causes an infinite loop and there is patch along the lines of

if (function_exists(i18n_sync)) i18n_sync(FALSE);

This is the link, the patch is at #3. https://drupal.org/node/1372500
Maybe that will help you to the right direction.


How can I get the length of a list in Rules?

Make a custom module eg. customrules and create customrules.rules.inc in this module.
In customrules.rules.inc place following code:

/**
 * Implements hook_rules_action_info().
 */
function customrules_rules_action_info() {
  return array(
    'customrules_list_length' => array(
      'label' => t('Get length of list'),
      'group' => t('Data'),
      'parameter' => array(
        'list' => array(
          'type' => 'unknown',
          'label' => t('List'),
        ),
      ),
      'provides' => array(
        'list_length' => array(
          'type' => 'text',
          'label' => t('List length'),
        ),
      ),
    ),
  );
}

/**
 * The action for 'customrules_list_length'
 */
function customrules_list_length($list) {
  return array(
    'list_length' => is_array($list) ? count($list) : NULL,
  );
}

Now you should be able to use this action to get the list length


How to manage reservations with a 2 hours duration without duplicate bookings?

If you don't want to re-invent the wheel, have a look at these contributed modules that are typically used for this (quotes are from their project pages):

Availability Calendars.

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Simple Reservation.

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependend on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.


Here is the steps to get user email in your language (describing all the steps in case you missed any)

Default installation of Drupal 8

Enable translation module (core modules)

Configuration Translation
Content Translation
Interface Translation
Language

add your language visiting

/admin/config/regional/language
in my example added Greek with Language code el

translate emails visiting

admin/config/people/accounts/translate
and pressing edit on your language
which in my example would be take me to this page
admin/config/people/accounts/translate/el/edit

add language switcher block (optional)

so you can switch to appropriate language

visit registration form for your language

in my case /el/user/register
and fill out the form

The email should come in the registration language

It came in Greek in my test.


If using fields as the display type the data will not be readily available in the display or style output, but can easily be gotten in the field tpl's by accessing the $row object which has all of the original raw data from the database.

Click on Theme: Information when in Views (editing the view in question) and you'll see all of the template recommendations to use. You'll probably want to use a tpl file that involves both the view and field name, e.g. view-view-field--[view_name]--field-[field_name].tpl.php.

Once you've created this tpl file you can access the following variables:

$view: The view object
$field: The field handler object that can process the input
$row: The raw SQL result that can be used
$output: The processed output that will normally be used.

You could do something special in <?php ?> and then print it like normal. For example, this would print out a specific field from a node that's referenced in a node_reference field:

Contents of view-view-field--blog--field-blog-parent.tpl.php:

<?php
$a_referenced_node = node_load($row->{$field->field_alias});
if ($a_referenced_node) {
  print $a_referenced_node->field_some_other_field[0]['value'];
}
?>


Images in sites/default/files are not allowed to be seen anymore

Ok, so I found a solution that worked for me.

In the process of investigating in this problem and the fact why it does not appear on other Drupal installations I have running on the same server I messed up the permission settings on my server. In order to reorder things, I installed the module https://www.drupal.org/project/security_review - it produces a list with potential security problems of your Drupal installation. I worked myself down the list solving the issues one by one. I am not sure if this was the point in the beginning but after I changed the permissions of the .htaccess-file in sites/default/files to 444 (readonly) suddenly my images were accessible again.

For your reference, here are a lot of other approaches you can try if the one I presented is not helping: https://www.drupal.org/node/1170440


Drupal site returning 404 error for all pages besides the main page

I copied and pasted the <VirtualHost *:443>
section several times...and every time I changed the ServerName and ServerAlias...but didn't change the <Directory /var/www/example.com>

I hang my head in shame and embarrassment.


Reason for javascript disabled in drupal site?

Hierarchical select adds that info box but removes it with JavaScript. This means that this error can happen for three reasons:

The hierarchical_select.js file is not loaded on the page.
You have an js error on the page before the hierarchical_select.js file is executed.
You have changed the markup for that info box, so that it is not removed by the JavaScript.

The most obvious reason is a that a JavaScript error breaks this page for you, but that is something you'll have to debug yourself...

To do so open firebug on Firefox or the preinstalled Developer Tools on Chrome (strg+shift+i). If you use firebug first enable the Console. Then reload the page and if there is a Javascript Error it will be indicated  with a red warning.


How to allow a user with some role to let people to register their new accounts in drupal 7?

In Drupal 7 you can use Administer Users by Role module

  Administer Users by Role : This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

Reference:

Create role for changing user accounts and not admins


Associate multiple Profile2 profiles with vocabulary and expose the vocabulary's terms in a views' filter

This probably doesn't answer your specific question, but this poses an alternate solution.

If you created two fields to allow the user to select a different number of terms, you could potentially do this with one field and a form_alter hook or validation.

The idea is that the form alter would change the number of allowed values based on some custom logic. Ideally this would make downstream functionality like views simpler because you're dealing with a single field.

The answer on this question may help give you ideas.
How do I set the fixed amount of values to 11?


Why do I get "Type does not correspond to an entity on this site" when POSTing to REST api behind an Apache Reverse proxy?

The solution is to remember set the base url of any _links href values to use http if Drupal expects it, and https if Drupal, instead, expects that.

In my case, I was using https, but the https connection was terminated at the Apache reverse proxy, so Drupal wanted http.

Using a REST extension to test with let me manually change the links array to reflect that, and the user was created just fine.

Also, the "type" href should not have the _format=hal_json on it.


How do I turn off the trimming of comments?

Have you looked if the format is not set to "trimmed" on the comment display page (/admin/structure/comment/manage/comment/display) ?


Twig adds an unwanted 'row' class that doesn't appear in class array

Those 5 classes are being added using .addClass() to a pre-existing {{ attributes }} Twig object. The 'row' class must already be in the attributes object when Drupal passes it to the Twig template.
Typically, the place where something like that would happen is in your .theme file (or the parent theme's .theme file if yours is a subtheme). Look for a function like THEMENAME_preprocess_region() and see if you can find a hard-coded "row" string being thrown in there.
Alternatively, some fancier theme systems might expose configuration options in the Drupal interface that could be setting that class. You'd find those under Admin > Appearance, then in "Settings" for your active theme.


How to discard unsaved changes to a view when editing it leads to a WSOD?

A quick fix would be to delete the data from the expirable key/value store:

\Drupal::keyValueExpirable('tempstore.shared.views')
  ->delete('view_id');

Alternatively you could wait a week until it expires itself - probably not practical :)


Can be done with Jquery
Check for the class "view-empty", if this div has inner div, then that means it has some content, if not hide that parent tab div.


Progress bar example:

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Import'),
    '#ajax' => array(
        'callback' => 'import_submit_callback',
        'wrapper' => 'import-form',
        'progress' => array(
            'type' => 'bar',
            'message' => t('Importing..'),
            'url' => 'import/progress', //url to fetch current progress percentage
            'interval' => '1000' //progress bar will refresh in 1 second
        )
    ),
);

Then create menu like this for url 'import/progress' :

$items['import/progress'] = array(
    'title' => t('Import progress'),
    'page callback' => 'import_progress',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);

Then output json data indicating current status like this in that page callback function:

function import_progress() {
    $progress = array(
        'message' => t('Starting import...'),
        'percentage' => -1,
    );

    $completed_percentage = variable_get('import_status'); // calculate progress percentage here

    if($completed_percentage){
        $progress['message'] = t('Importing...');
        $progress['percentage'] = $completed_percentage ;
    }

    drupal_json_output($progress);
}

Further reading: https://www.drupal.org/node/1401966


Control access to a custom blocks edit page

/**
 * Implements hook_permission().
 */
function my_module_permission() {
  return [
    'my_module_custom_permission' => [
      'title' => t('My Module Custom Permission'),
      'description' => t('Explain what this permission allows the user to do.'),
    ],
  ];
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {
  $items['admin/structure/block/manage/block/5/configure']['access arguments'] = ['my_module_custom_permission'];
}

If you use the code above, follow the steps below.
Steps

Replace all instances of 'my_module_custom_permission' to a machine name that makes sense.
Update the 'title' and 'description' for the custom permission.
Replace all instances of the word 'my_module' with your module's machine name.
Change the $items path from what I have to the block path you are trying to update.

Important to note
If the block you are editing was created from the frontend of the Drupal website, then it can be deleted. If it gets deleted and then recreated, the block's ID will change. Which in turn changes the path to the block's configuration page.
Testing
Make sure to give your test user the permission we've just made and make sure they can edit the block configuration. Also, test a user who does not have the permission and make sure they can not edit the block configuration.


How to cancel installation of my module if requirements are not met

You can do this in hook_requirements, from the documentation:

  During the 'install' phase, modules can for example assert that
  library or server versions are available or sufficient. Note that the
  installation of a module can happen during installation of Drupal
  itself (by install.php) with an installation profile or later by hand.
  As a consequence, install-time requirements must be checked without
  access to the full Drupal API, because it is not available during
  install.php. For localization you should for example use $t = get_t()
  to retrieve the appropriate localization function name (t() or st()).
  If a requirement has a severity of REQUIREMENT_ERROR, install.php will
  abort or at least the module will not install. Other severity levels
  have no effect on the installation. Module dependencies do not belong
  to these installation requirements, but should be defined in the
  module's .info file.

After your check, you return array (see docs again) with REQUIREMENT_ERROR.

function example_requirements($phase) {
  $requirements = array();
  // Ensure translations do not break at install time
  $t = get_t();

  $requirements['example'] = array(
    'title' => $t('Example Library'),
  );

  $libraries = libraries_get_libraries();
  if (isset($libraries['example'])) {
    $requirements['example']['value'] = $t('Installed');
    $requirements['example']['severity'] = REQUIREMENT_OK;
  }
  else {
    $requirements['example']['value'] = $t('Not Installed');
    $requirements['example']['severity'] = REQUIREMENT_ERROR;
    $requirements['example']['description'] = $t('Please install the example library %url.', array('%url' => 'http://example.com'));
  }

  return $requirements;
}

You can check this code example here.


Create custom language not based on english

Be sure to create the new custom language:

admin/config/regional/language
(use fr-CA language code)

Get the French po files from here:

https://localize.drupal.org/translate/languages/fr

Then import (choose Canadian French):

admin/config/regional/translate/import


How to configure date facet filter with year granularity, when click it should show months

I have found the solution.

Just select the Granularity to "Days" instead of "Year" in the facet configurations.


Documentation for theme_menu_link():

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

The generated html needs to be returned as a return value.

The $variables argument has all the data.

Instead of var_dump(), you should install devel and do a dpm($variables). You might have to refresh the page twice to see the result.


You could do that by implementing the hook_form_alter, in your custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login') {
    $form['name']['#description'] = t('Enter your username');
  }
}


Drupal 7 module issues using node_ functions

Never ever call functions from the global scope. You are probably running into a situation where other modules (the node module) are not yet loaded.

<?php
if(isset($_GET['fetch']))
{
    social_fetch();
}

You could try to add your function to hook_boot(), but even then the node module might not be loaded, so you will have to ensure it is loaded manually.   drupal_load('module', 'node');

You'll end up with

function social_fetch_boot() {
  if(isset($_GET['fetch'])) {
    drupal_load('module', 'node');
    social_fetch();
  }
}


"Strict warning: Only variables should be passed by reference in eval()" when concatenating several text fields

$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_address')));

=>

$items = array_pop(field_get_items($entity_type, $entity, 'field_address'));
$entity_field[0]['value'] = array_pop($items);

You have to store result of function in variable and pass it to another function, instead of pass function to function.

Passing by Reference


Is there an advantage to Featurizing a view, over using Views' export?

For a single View, there is no difference in functionality really. The view will be the same regardless.

I use Features anyway because it's makes it more conventient to organize multiple pieces of configuration into "features". I'm not aware that ctools offers any easy way of doing "This view with that panel and those three dependencies in one module". That is what features adds on top of Ctools.

It's worth mentioning that the Configuration module is an useful alternative that largely makes the configuration tracking easier. If you don't care about the features aspect of features, take it for a spin. (Thanks Clive for pointing this out)


Solved it with the following code:

function custom_form($form, &$form_state) {

global $user;

if (!isset($form_state['profiles'])) {

  $profile = profile2_load_by_user($user, 'profile_machine_name');
  if (!$profile)
  {
    $profile = profile_create(array(
      'type' => 'profile_machine_name',
      'uid' => $user->uid
    ));
  }
  $form_state['profiles'][$profile->type] = $profile;
}

profile2_attach_form($form, &$form_state);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
);
return $form;
}


I suggest the use of the Read only mode module, it places your site in the maintenance mode, but your visitors can still view the site without enter or change content.

Then make a copy of your database and get out of the maintenance mode.


You can make the same with semantic views, it let you to choose what hmtl tag wants for every field, and also what class/id you want to use.

also, without programing,

I leave enable the link.

I dont't output the amount.

But in the 3º element, I will rewrite the ouput and add the [amount-token] So you can build the div you need also.

all this without use tpl.

anyway the best option always will be to make make as say the first comment.


Drupal already sets a session cookie when a user logs in: see the function drupal_session_regenerate().

Can you use this session Id for your purposes? If not, then you just need to create a new value in the cookie the same way that you will do in PHP, $_COOKIE['my_value'];. Place this code in the hook_init() of a custom module, adding a if() to filter the landing page.

Later, you retrieve it and use it in your view; you can use some of the hooks of Views depending on your needs. You can also use the module Views custom field, and embed your PHP code there.


I think your talking about remote entity.

Remote Entity API provides a system for treating data from remote sites as local, Drupal entities. Remote data is stored locally in an entity base table, and can be periodically refreshed with data from the remote source.

Once a custom entity type is defined, entities can be manipulated just as normal Drupal entities: they can be loaded and saved to the local database, and have fields added to them. Remote Entity API provides ways to load an entity remotely, query the remote source for multiple entities, and save back to the remote source.

From the Remote Entity Documentation page:

  Creating a connection

  TODO.

  Creating a resource

  The Clients Resource for the remote entity type is composed of two
  parts, and as such can't be created in the UI:

  hook_entity_info() defines the remote entity type. See remote_entity_hook_entity_info() for the additional keys that must/can
  be defined here.
  The Clients resource itself must be defined with hook_clients_default_resources():

/**
 * Implements hook_clients_default_resources().
 *
 * Define our remote entity resource.
 */
function example_clients_default_resources() {
  $items['my_entity_type'] = entity_import('clients_resource', '{
    "component" : "my_entity_type",
    "connection" : "my_connection_name",
    "name" : "my_entity_type",
    "label" : "My Entity Type",
    "type" : "remote_entity", // do not change @see function remote_entity_load_by_remote_id
    "configuration" : null,
    "rdf_mapping" : []
  }');
  return $items;
}


html text or custom image to the user profile page?

you can also add a block to the "content area" to be shown below the user profile (restricted to user/* pages). In the block you an use short PHP snippets.


How to create a bean bundle programatically

With bean modules it's required that if you use "name" attribute  is the same name that the $plugins key.

In my case

'name' => 'beanform'

The beast options is not use it, it's no a required attribute.

Oskar

my actual code:

  $plugins['beanform'] = array(
'name' => 'beanform',
'label' => t('Bean form'),
'description' => t('Choose a form to print into a bean'),
'handler' => array(
  'class' => 'BeanForm',
  'parent' => 'bean',
  'path' => $plugin_path,
  'file' => 'Beanorm.inc',
),
//   'path' => $plugin_path,
//   'file' => 'BeanForm.inc',
   'editable' => TRUE,
  );


Remove home page navigation from logo at checkout

A good method of doing this is with the context module and context layouts.

Context module: https://drupal.org/project/context

You can specify two layouts, one for main and one for checkout.

Heres a vid about it. http://www.youtube.com/watch?v=rzBpjZ_ZRfo


How to remove Analysis button from Webform results tab

The best way to hide menu item from the secondary tabs should be to alter the access callback of the menu item.

function yourmodule_menu_alter(&$item) {
  // This hides the analysis item. Others should work simillary.
  $item['node/%webform_menu/webform-results/analysis']['access callback'] = 'yourmodule_webform_result_access';
}

function yourmodule_webform_result_access($node, $account = NULL) {
  // You can put here any custom logic of your needs.
  return FALSE;
}


Rewrite output of a field and include another one templated

As you might excluded the field from display which bypasses the template file that build the display of the field.

So you have to use .tpl file to build the markup you need or put the markup in the rewrite which is not the best solution but may be accepted if you just write simple markup of one tag and classes to let css style apply.


You can do that quite easily with the Views module and contextual filters.

The one thing that I don't suggest doing is using Taxonomy.  I don't like using taxonomy because besides it being a non-indexed list of vocabulary, it allows for too much variance.  For instance in taxonomy:

"hat" != "Hat" != "hAt"

So, if you tagged one page as "hat" and the other "Hat", you would have to search for both term to get the content to display.

It much better to use the existing functionality of Content Types to create your "taxonomy."  Coupled with Views, Entity Reference, and Path Auto, you can do exactly what you are looking to do with a minimum of additional modules and "no taxonomy."

I would definitely suggest taking a look at the Relativity Data Model put out by Jay Epstien.

The Florida Drupal Camp website was redesigned with this model.  The most important thing to notice is the speed at which things load.

I have also been using it quite extensively and can tell you that excluding content, my site is less than 5K in size; that's about the size of an iPhone app.  This is accomplished mostly due to the fact I am running less than 20 modules total.


Include Entity Reference values to term page Solr results

Here's what I did to merge entity reference nodes to Solr results (Solr-generated taxonomy terms)

I did a _term_load()_ on _theme_preprocess_search_results()_ to pull all the entities from entity reference field and load them using _entity_load()_ and get the renderable array by using _entity_view()_ and render it by render().

After assigning those referenced nodes into a variable, I printed the variable in search-results.tpl.php above the _$search_results_.

It should display the referenced nodes into Solr page, above the actual Solr results.

To prevent displaying the node twice, I filtered all nodes from entity reference field not to show in current Solr page.

foreach ($term->field_article_reference[LANGUAGE_NONE] as $key => $val) {
  // Exlclude items that is already in term's entity reference field.
  $excluded_ids[] = $val['target_id'];
}
foreach ($excluded_ids as $excluded_id) {
  $query->addFilter('entity_id', $excluded_id, TRUE);
}

To maintain the total number of rows, here's what I did.

// To get rows variable subract 11 from the total number of reference
// items, first page should start with first item 0.
// Start variable should be the product of $rows and the page number, if
// page number exists. And it should always shows 11 total rows.
$total_rows = 11;
$param = drupal_get_query_parameters();
if (empty($param['page'])) {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = 0;
  $query->addParam('start', $start);
  $query->addParam('rows', $rows);
}
else {
  $rows = $total_rows - count($term->field_hero_stories[LANGUAGE_NONE]);
  $start = $rows * $param['page'];
  $query->addParam('start', $start);
  $query->addParam('rows', $total_rows);
}

Note: Maximum items from reference field should not be equal nor more than to the total number of rows.


How to not let users remove the entity reference once they added

Using Hook_form_FORM_ID_alter on the node form and disabling the field for users that are not the initial author should work.

Code is untested but shows the general idea behind the solution

HOOK_form_FORM_ID_alter($form, &$form_state){
  global $user; // Get the current logged in user information
  if($user->uid != $form_state['node']->uid){ // Is the current user not the original author of this node?
    $form['FIELD_REFERENCE']['und'][0]['#access'] = 0; // Restrict access to this field (You'll have to check where exactly in the tree to place this).
  }
}


why system/connect web services return nothing in drupal 7?

The services module allows a resource to define the following "things":

Operations: provide 5 different verbs

retrieve: Make a GET request based on the resource name and an identifier i.e. GET /endpoint/user/ID
index: Make a GET request based on the resource name to get a list of resources i.e. GET /endpoint/user
update: Make a PUT request to a resource name and an identifier i.e. PUT /endpoint/user/ID
create: Make an idempotent POST request to a resource name to create a new resource i.e. POST /endpoint/user
delete: Make a DELETE request to remove a resource by identifier i.e. DELETE /endpoint/user/ID

Actions: Allows to make a custom POST request to a resource. This is used for login, logout, etc... These are never GET.
Targeted Actions: Allows to make a custom POST request to a resource + identifier. This is used for making hierarchical resources.
Relationships: Allows to make a custom GET request to a resource + identifier. This is used for make hierarchical requests for things like group membership.

The system/connect resource is defined as an "action" above. This means that you must make a POST request instead of a GET request. And it may require a CSRF Token.

POST /login_x/system/connect HTTP/1.1
Content-type: application/json
Accept: application/json
X-CSRF-Token: 'TOKEN'


How can I move custom panels content from a panel to a mini panel (using Features)?

I ended up just doing it manually.  Though it took some time, I was unable to find a faster solution.


Auto Post to Google + from RSS Feed Content

Edit: google+ does have an api, but this module is old, and doesn't implement it.

You can't post using this module.

This link night give you some more information: https://stackoverflow.com/questions/7570327/how-to-post-in-google-plus-wall


Front page meta tags and multisite configuration

It depends on how your sites are structured. Are all three basically the same site only available via different URLs?
First off, be aware that this can penalize you for having the same content available via multiple URLs, search engines don't like that. You should use Nodewords' ability to hardcode a specific base URL to pick one of the domains to say that one is the primary domain; the others are secondary that will help avoid penalties.

That, of course, is if you're using Drupal 6; for Drupal 7 there are other options.

Disclaimer: I am the maintainer of the Nodewords module.


How to redirect a user to previous page after successful login?

The following implementation of hook_user_login() will override the redirect path set by user_login_submit().

As with the default behavior, setting the destination in the query string overrides this redirect.

<?php

/**
 * Implements hook_user_login().
 */
function mymodule_user_login(&$edit, $account) {
  $edit['redirect'] = $_GET['q'];
}


Webform override only certain groups of fields in webform-form template

Finally I created several css classes that I add either to element wrapper or to the input element itself, and I position each element accordingly.

If your form is not too long, and you don't mind creating other webform elements, you might want to wrap the fields that you want to put on the same line in a fieldset, you give row-fluid class to the fieldset, and all is good. This obviously also depends on the functioning of the form, some modules don't work as expected with nested fieldsets, ex. webform add more module (at leat las I checked it didn't, was about a month ago)

In my case I didn't want to do this, as the form is long and complicated and it could've broken some functioning.

Cheers!


what can be removed when minimizing hook_views_default_views in a module?

I find that the features module does a better job exporting the view. It adds an array of translatable strings. I haven't compared the verboseness of the views exported, but most they are probably the same. Most of the verboseness comes from defining fields. Some options might not be strictly needed - compared to the UI, but when importing/exporting things, it's better to be a bit over verbose, than to rely on default values.

With some practice, you can learn to spot the important stuff and ignore the rest.


How to use .schema.yml definition for two entities avoiding duplicated code

Solution
Here is a very good way to do this, with thanks to @sonfd for the link.
node.type.*.third_party.my_module: &third_party_settings_alias
  type: mapping
  label: 'My Module'
  mapping:
    lots more lines here ...
    which I do not want to duplicate ...

# Use saved alias to repeat the same settings for media.type
media.type.*.third_party.my_module:
  *third_party_settings_alias

That's all there is to it. All the settings for node.type are repeated for media.type


The Drupal's jquery.once.js is to blame. Deleting every *-processed class worked.


How to merge WYSIWYG fields from separate nodes

Welcome to Drupal Answers. You can use views module with simplenews to achieve above functionality.

Please find simplenews features below.

Sending nodes as newsletters to subscribers
Multiple newsletter categories with separate settings
Per category and multi-signup Blocks and Pages
Subscriber management including mass-subscription and export
Optional E-mail confirmations for anonymous users
Customizable newsletter templates
Support for HTML (including text alternative) newsletter when used in combination with a supported mail system module
Views and Rules integration
Support for multi-language newsletters


Updating the PHP version of an existing site?

Is it possible to update the PHP version of an existing Drupal site that is installed on a local server on Ubuntu?

Yes, upgrading server software for existing applications is common practice both inside and outside of the PHP/Drupal worlds.

If your operating system supports a newer version of php than you currently have, and Drupal (plus the contrib modules you're using) supports the same version you're planning to upgrade to, then you should have no problems.

  Is it done by an internal Drupal module or an external tool?

Drupal can't upgrade the software on your server, that's something that gets done at the operating system level; consult the documentation for your OS for details on how to actually do it (Google "ubuntu upgrade php 7").  Make sure you back up and perform this in a test environment before doing anything on a production server, just in case.

PHP 7 has significant performance improvements, and Drupal 8 supports it, so the particular upgrade you're suggesting would be a good move.


Check performance of drupal websites using some modules or tools

You could try new relic, it will give you insight into how expensive database queries are or where you have a bottle neck which is slowing down your site. It has some integration with Drupal and could also show you if you have a problematic module...

Also if your pages use a lot of views, have you tried caching the views? It is part of default views module, go into your view edit under "advanced" on the right. Click caching and turn this to time based. This means that rather than running each view query / view rendering on every page load - It will run it on the first load and retrieve a cache until it expires. The caveat here is that you will have a lag on the results for how ever long you choose to cache.


From your question, I believe you want one exposed filter to reload the page when chosen and then all the other views on the page follow that filter?

A workaround if no one else answers is to expose the filter on all views and hide the ones you don't want with css. In each view, go to the filter's settings under Admin at the bottom and you can rename them all to field_month_value if they're different.


To get the links for the next/previous pages you need to use theme('pager').

On this post you can find an example of that implementation.


How to use a field other than node id or term id as contextual filter?

I think you need use the field type "list" or the field type "Taxonomy term".


How do I filter a view with a field on a group the current user is in?

It looks like this may not be possible with the current stable release of OG (7.x-1.3). I think it would require at least the patch from issue #1341990 along with the patch from this comment on issue #1151648, but I'm completely new to Drupal so it's not unlikely that I'm missing something.


remove node options from admin area when creating nodes

You need to create a module and implement hook_form_alter.

Then, in the $form array, unset the array index(es) containing the parts you don't want your users to see and configure.

ps: I advice you do the above by permissions. So, those array indexes are unset for specific roles not all roles which would include user#1


How to resize an image programmatically when creating node?

Don't forget to use image_save() after you've resized it!


developing a site in drupal made a mess in modules .. is there better way?

You can of course create a test site to experiment with certain modules and patches before adding them to the real site.

Version control is also really helpful, because it allows you to revert to a previous version of your code. However you need to keep in mind that your database is not under version control, so you need to take a snapshot of that as well to do a proper rollback.

A more advanced solution is to use drush make and the features module. The features module allows you to store a lot of configuration in code. When combined with drush make, it allows you to roll out a fresh copy of your code again and again.


Drupal rendered page for directory root, followed by static pages?

Add your own .htaccess file under the my-dynamic-page and my-dynamic-page/static1 with only this in it:

DirectoryIndex index.html index.htm


Custom content type and views field rendering

Have a look at views-view-field.tpl.php. It' not used by default views, but available as a template override.

Edit: In views-view-fields.tpl.php you can also use $fields['my_field_name']->content; to access individual fields, but this will give you the fields default markup as well. The raw values can be accessed with $fields['my_field_name']->raw but those values must be proper sanitized before printing.


Drupal does it on elements theme level with _form_set_class function. This function gets $element array and checks if it has errors with function form_get_error. Because errors are set with indexes like 'foo][bar][value' (parents) that can be not so easy to find them in the $form array. So I suggest to use the same check as in _form_set_class with your function at pre_render, theme or validate level when you have $element array. hook_element_info_alter can be useful.

The super simple example:

function YOUR_MODULE_element_info_alter(&$elements) {
  foreach ($elements as $type => $value) {
    $elements[$type]['#pre_render'][] = 'YOUR_MODULE_element_error_check';
  }
}

function YOUR_MODULE_element_error_check($element) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $element['#suffix'] = t('error!');
  }
  return $element;
}


Automatically scroll to content when block link clicked?

First, you need to know the ID of the Drupal region/element that you want to jump to when the responsive theme is activated. With the standard Bartik theme the id is the main content region is "block-system-main".

Then you could append #block-system-main to all links within your side. This will cause the browser to jump to the HTML element with that ID after clicking the link. You could append this tag to all links using javascript. See this question. It could also be done in PHP. This would be a good module and AFAIK no exists currently.


You can try dsm($page) in page.tpl.php of your theme to see the contents of $page array.

As mentioned by Clive, context really matters. If you will try to print $page array when it has no elements then it will display word Array.


How to create entity relation of counselor to client?

You seem to need two relations/references; one to connect clients with counselors, assuming that doesn't change for each new session, and then a session node (Session Content type) related to either the client or the councelor, depending on what makes more sense in your case.

Or you might orient it around sessions, where you have two user reference fields, one to the counselor and the other to the client. Although that seems less likely to make sense.

If the hours is the only thing that needs to be recorded maybe you can get away with only the reference between counselor and clients, with the added Hours field to the reference field, with unlimited values so with each new session another value is added. You can use Views to summ them up.

You haven't said anything about privacy and permissions requirements and how the data is maintained. There are modules that can control access through references made between entities. Maybe explore that to find the right combination for you.

Group module can also be used, although it may be an overkill depending on your requirements.

Which modules/structures to use and build becomes obvious once you have all your requirements clarified.


Rewrite CCK field output without using templates

Sounds like you're looking for the Custom Formatters module, very similar to Contemplate, but specifically for create Field Formatters to be used via the Display Settings page or Views.

Custom Formatters can be built with both Tokens or pure PHP code.

Additionally, Custom Formatters can be exported as native Drupal Hooks or in a custom Features exportable format.


(dis)advantages of staging dev->production using 'drush rsync' vs 'git'?

I have used both techniques.  Both can be used to guarantee that the same files that you test on @stage end up on @live.  The advantage of rsync is that you do not end up with extra files (e.g. ".git" and associated) on your production server.  I tend to rsync to a vps, and use git on a box I own (e.g. intranet sites).


I did a work around without using composer to do the install by doing the following:

make a drush directory in your home folder (~)
git clone https://github.com/drush-ops/drush.git
cd into that directory
./drush --version (it should complain about composer install)
run composer install
./drush --version WORKING!

I'm using ubuntu so initially I did apt-get install drush, but that version is 5. Then I did the following to download the latest into ~/drush

From there I went to my global run folder: /usr/bin and renamed the old drush to drush_old and then did a ln -s ~/drush/drush drush now its on the latest drush!


I'm running Pixture Reloaded, another Adaptivetheme and I use Panels for nearly everything on my site and have experienced no such problems.

I have used both the 2.x and 3.x series with no incidents.

I doubt your problem is Corolla; from your post, it is clear you are still running alpha versions of Panels and Views.  These modules have had stable and security releases for D7-- Views is now version 3.3.  You really need to keep your modules up-to-date when there are security releases

Update all your modules to the latest versions (or at least Ctools, Views, and Panels), run update.php, and then do this:

Enable Corolla.
Clear the cache twice.
Go to the Corolla theme settings page.
Click save.  (It doesn't matter if you make any changes.)
Clear the cache twice again.

This will ensure that all the files that are automatically generated by Corolla have been rebuilt properly and should fix the problem.


How to share some content in a multisite?

There are quite a few solutions available in Drupal contrib which allows sites to share the content with each other:

Workspace In core now creates multiple versions of the site.
Entity Pilot is a really good use core serializer solution. It tracks changes allow and merging via UI. If you want to track the content then you can also use Entity Pilot Git
.
CPS D7 version only.
Domain access if your site shares the domain name then this is the best solution to display the same content on different domains.
Default Content you have to manually import export the content.
D8 to D8 migration is the last ditch solution there is no D8 to D8 migration in Drupal core at this moment but you can export content in CSV using CSV Serialization and then import it via Migrate Source CSV. The sites can periodically import or export data in hook_cron.


Cannot access empty property on entity.inc line 277 when trying to access entity add page

Your entity keys don't seem to include bundle, label, or language. - @beth


Drupal 7 & Facebook Connect - Connect Button Problem! Help please?

I have the same issue, FB Connect will do this when your site tries to connect to an  FB App and cannot. Check your API and Secret keys first, other possible problems are the URL settings which should match in both FB and Drupal/FBConnect. Lastly in my case, everything was working until I reset an auth key in FB which I should not have done and it created issues for me.


The problem I can see with your code is the file name for the template file that you declare in your hook_theme() implementation.
The file name for the template file should be the theme identifier used as array index in the array returned by hook_theme() (in your case, "profilebuild"); where the identifier uses underscores, the template name should use hyphens.

As example of how the template files are named, see the following hook_theme() implementations for Drupal core modules.

function book_theme() {
  return array(
    'book_navigation' => array(
      'variables' => array('book_link' => NULL),
      'template' => 'book-navigation',
    ),
    'book_export_html' => array(
      'variables' => array('title' => NULL, 'contents' => NULL, 'depth' => NULL),
      'template' => 'book-export-html',
    ),
    'book_admin_table' => array(
      'render element' => 'form',
    ),
    'book_title_link' => array(
      'variables' => array('link' => NULL),
    ),
    'book_all_books_block' => array(
      'render element' => 'book_menus',
      'template' => 'book-all-books-block',
    ),
    'book_node_export_html' => array(
      'variables' => array('node' => NULL, 'children' => NULL),
      'template' => 'book-node-export-html',
    ),
  );
}

function aggregator_theme() {
  return array(
    'aggregator_wrapper' => array(
      'variables' => array('content' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-wrapper',
    ),
    'aggregator_categorize_items' => array(
      'render element' => 'form',
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_feed_source' => array(
      'variables' => array('feed' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-feed-source',
    ),
    'aggregator_block_item' => array(
      'variables' => array('item' => NULL, 'feed' => 0),
    ),
    'aggregator_summary_items' => array(
      'variables' => array('summary_items' => NULL, 'source' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-items',
    ),
    'aggregator_summary_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-summary-item',
    ),
    'aggregator_item' => array(
      'variables' => array('item' => NULL),
      'file' => 'aggregator.pages.inc',
      'template' => 'aggregator-item',
    ),
    'aggregator_page_opml' => array(
      'variables' => array('feeds' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
    'aggregator_page_rss' => array(
      'variables' => array('feeds' => NULL, 'category' => NULL),
      'file' => 'aggregator.pages.inc',
    ),
  );
}

Drupal 7 implementations of that hook is slightly different from the implementation done in Drupal 6, but the "template" index is used in the same way in both the versions.

function block_theme() {
  return array(
    'block_admin_display_form' => array(
      'template' => 'block-admin-display-form',
      'file' => 'block.admin.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}


galleria Slideshow images does not display

Thanks for browsing my question.
I got it right by simply reverting back to an old version of Galleria Jquery plugin. I used galleria 1.2.9 instead of 1.4.2 and all is well.

I am still puzzled though as to why the new version is not working.


There's two possible approaches you could take here:

Add a custom hook_form_alter to test in php if the user is logged in, and then set the disabled/locked attribute to the field.
Add javascript that on page load checks to see if the body has the "logged-in" class and if the field is already populated/has a value; then disable/lock it.


The short answer is yes; the .front class is more than adequate.

Using SASS nesting, your CSS would probably end up looking something like the following.

@media all and (min-width: 960px) {
 $zen-column-count: 5;

 .front {
   .sidebar-first {
    #content {
     @include zen-grid-item(4, 2);
     color: red;
    }

    .region-sidebar-first {
     @include zen-grid-item(1, 1);
    }
  }

 /* not-front pages */
 $zen-column-count: 10;

 .sidebar-first {
  #content {
   @include zen-grid-item(7, 3);
  }

  .region-sidebar-first {
   @include zen-grid-item(3, 1);
  }

 }
}

Note that I've removed the .not-front class from the second batch. Adding the .front class to the first block gives it a higher level of specificity, so it can't be overridden by what is in the second block. Basically, if you are using .front for the first bits, then it is redundant to use .not-front for the second block.

As an FYI, there is an awesome CSS specificity article here.


How do I use an absolute URL to set as breadcrumb link?

Using PHP code you can build absolute urls with the url function.

Example:

$url = url('/category.html', ['absolute' => TRUE]);


How do I transfer nodes categorized with one taxonomy term to another?

You can use hook_update_N() to update multiple nodes at once with a single run of update.php. Inside it you can load all the nodes that you need to modify using node_load(), and after you are done changing the taxonomies programatically, call node_save().


D9 modules will work on D8. You'll have to go back to a D8 core  and then go to /update.php or if you have Drush, run drush updb; otherwise, you'll have to manually do the changes to your DB that those updates execute.


Autofilling fields based on another field

If you want it to happen live, and all fields are on the form already, safest way would be to use hook_form_FORM_ID_alter() to add following to a form:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'module_name') . '/js/copy_field_value.js',
);

Then in copy_field_value.js create behavior:

(function($) {
  Drupal.behaviors.moduleNameCopyFieldValue = {
    attach: function (context, settings) {

      // Repeat this for all fields as needed
      $('#source', context).on('blur', function () {
        // above you can use change instead of blur if element is not changed by another js
        if (!$('#destination').val() || 0 === $('#destination').val().length) {
          $('#destination').val($(this).val());
          // wrap line above in "if no value" like I did, or other condition you like
        }
      });
      // end of "repeat this"
    }
  };
})(jQuery);

You can also use hook_form_FORM_ID_alter() to add #ajax parameter to source field, but it would make your form to call a server on each field copy. If you need to actually query database, it is the way to go. It would be pretty broad to describe it anew here. You need to alter $form_state["input"] array to update real values seen by user. Do it in form creation function, wrapping it with isset to avoid notices.

If your form element is $form["something"]["something"]["element"], its value will be in $form_state["input"]["something"]["something"]["element"] - and you can set it in hook_form_alter all right, just remember to take both $form and $form_state by reference.

Note: .on() method was added in jQuery 1.7, so you will need jQuery Update to use this answer directly, or translate my code to use .change() or .blur() method.


You just want to make the links show as uppsercase text!? Since you're not altering the HTML structure of the menu -- there is no need to modify any theme function. You just do it using CSS.

/* In ideally your last css file listed in your .info file
 * add a line such as
 */
#main-menu a { text-transformation: uppercase !important; }


Creating a filter programatically with views_get_view

The first key to enlightenment is to at error message.  It says the fatal error happened in views/includes/view.in, around line line 2450. I don't know your exact version, but in one of my Drupal 7 installs, here's what's close to line 2450:

  /**
   * Add an item with a handler to the view.
   *
   * These items may be fields, filters, sort criteria, or arguments.
   */
  function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
    $types = views_object_types();
    $this->set_display($display_id);

    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);

My line numbers don't match in my version, but notice the last line of the excerpt.  Best guess that $this->display[$display_id]->handler ($this is your view) is either NULL, or is not an object.

$this->display is an array of view_display objects; and $this->display($display_id) should either be a view_display, or perhaps, NULL or FALSE.

I'd recommend trying the following to debug this:

First, perhaps it's possible that $view->current_display is not initialized, or isn't what you think it is. Try substituting it with 'default', which usually works with Views.
If you look at your view's definition and know the machine ID of one of your displays for that view (say, 'page_1'), try substituting that and see if it works.
If you're using an IDE with a source debugger, this is a good time to learn to use it a bit. Views can be pretty opaque as to what it's doing under the hood, and sometimes, seeing what the data actually is in real time can save you a lot of time.

That's as much as I can suggest w/o knowing the exact version of Views you're using, but it may get you started.

Good luck, in any case.


Drupal 8 cron not running from external source (as anonymous)

I know the question is old, but I faced a similar problem and would like to help people coming from google.

I assume you have a function in one of your specific cron hooks which needs extra permissions to run which won't work because Drupal runs cron as an anonymous user.

What helps is to identify which hook_cron needs elevated rights and switch to e.g. the admin account before the affected code runs:

use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();


Admin (uid=1) access denied to custom module page

This:

'access callback' => array('view ledger reports'),

Needs to be:

'access arguments' => array('view ledger reports'),

Currently you're trying to make Drupal invoke a function by string while giving it an array - it's not going to like that very much ;)


Users chosen from a field in a content type see only their result

Views module doesn't control content access
Views module respects the entities permissions set elsewhere in Drupal.
There are Permissions option available in Views but that only controls that particular Views Display global visibility, it doesn't control the nodes/users visibility. You can set Views to be visible by a certain user role or some other permission, but it will only apply to that Views page/block, it will not apply to nodes that are listed in that Views results! Even if a user is restricted from viewing that Views, they will still be able to see the nodes listed in the Views if they visit the nodes through the individual nodes links.
To properly restrict access to content on your Drupal site you need to restrict it on the node level, not Views level. Once you have it sorted out on node level, Views will respect it, check access for each node and show only the result rows that the user has access to view. There is a way to turn of node access check in Views (under Advanced options) but that's not recommended and it's rarely used.
Use Content access modules, Views will respect them
In your case you want to restrict access in a very granular way, to show content to only the user that is referenced from individual content item. You can do that with the help of additional module(s), you should research Access modules on drupal.org that relate to entity references.
Some of the ones I can suggest to test:

Access by Reference
Permissions by field


I just finally installed the XHProf profiler under Windows7 x64 - PHP 5.3.x. Assuming that you have a functional PHP environment, this checklist should work for you too:

Download the pre-compiled XHProf 0.10.3 - PHP 5.3 VC9 NTS binary.
Paste the downloaded dll file to PHP extensions directory.
(You can find the directory path in extension_dir directive of php.ini file.)
Append extension=php_xhprof.dll directive to the php.ini.
Restart the web server and searchphpinfo() output for XHProf. found? done!
You might also want to use XHGui fork instead of the built-in UI.


How do I turn off mobile menu collapse for bootstrap 3 theme in drupal 8?

Just override the menu--main.html.twig template that comes along with the bootstrap theme, and replace the HTML classes with your own classes, then the bootstrap mobile styling won't affect your menu.


Change Drupal interface language back to English

You can change the language back to English by adding this to the url of any page:

&language=en

EDIT:

To have a seperate admin and front end language I'd suggest looking at the Admin Language module - http://drupal.org/project/admin_language

SECOND EDIT:

To do this via role have a look at this page - http://deglos.com/blog/2010/06/12/overriding-language-drupal-backend

They are doing what you want with a custom module. You could throw in the user role code there using the global $user.


What is the best way to add "last_imported" field into a view for a node entity-reference field joined to migrate_map table?

So I found the solution to that.
You have to add relationship to referenced "fruit" entity to the view. And immediately following field will be available.
In my fruits_import.module.php I added hook_view_data() as follows.
/**
 * Implements hook_views_data().
 */
function fruits_import_views_data() {
  $views_data = [];
  // Exposing Migrate Map table.
  $views_data['migrate_map_fruit']['table'] = [
    'title' => t('Related migration'),
    'group' => t('Fruit Entity Migration Tables.'),
    // Watch out! This is not a base table, so we use a different key and
    // explain to Views how this table can be JOINed to our base table of
    // 'fruit'.
    'join'  => [
      // We are explaining Views how 'migrate_map_fruit' can be JOINed to 'fruit'.
      // By the way, you do not necessarily have to JOIN onto a base table. You
      // may as well JOIN in chain a few non-base tables. Although for a table
      // to become visible in Views UI, it must be connected one way or another
      // to a base table on which the view is being built.
      'fruit' => [
        // Column from 'fruit' table which will participate in the JOIN clause.
        'left_field' => 'id',
        // Column from 'migrate_map_fruit' table that will participate in the JOIN
        // clause.
        'field'      => 'destid1',
      ],
    ],
  ];
  // Exposing last imported col only for now. (We could expose other ones here)
  $views_data['migrate_map_fruit']['last_imported'] = [
    // Human friendly name for Views UI.
    'title' => t('Last Imported'),
    'help' => t('Timestamp for an fruit last imported.'),
    'field' => [
      // In the 'id' key we place the name of Views field plugin that is
      // responsible for operating the column. The id "date"
      // corresponds to \Drupal\views\Plugin\views\field\Date class. It is
      // an extremely simplistic straightforward field plugin that appends the
      // column into SELECT query (see ::query() method) and then displays the
      // fetched column as field output (see ::render() method).
      'id' => 'date',
    ],
  ];
  return $views_data;
}

Credits to awesome Views tutorial by Oleksandr


Is there a way to hook on cache clearing?

The way to do this is to use hook_flush_caches in combination with register_shutdown_function. Example code:

/**
 * Implements hook_flush_caches().
 */
function mymodule_flush_caches() {
   // After caches are cleared we will run mymodule_cache_rebuild()
   register_shutdown_function('mymodule_cache_rebuild');

   // We don't want to add any custom cache-tables, so just return an empty array
   return array();
}

/**
 * Rebuild expensive cache items that need to be rebuilt immediately.
 */
function mymodule_cache_rebuild() {
  // Do the cache rebuild work here
}

Using register_shutdown_function means that our cache-rebuilding function will be called after the caches have been cleared. We are abusing hook_flush_caches in a way that it was never intended to be used, but this should do exactly what you need.


Adding jQuery to Drupal 7 site: drupal_add_js() adds but doesn't call?

You're most of the way there!  You just need to convert what's in your ready() to a function:

drupal_add_js('jQuery(document).ready(function(){jQuery(".accordion").accordion({collapsible:true,active:false})});', 'inline');

Also, according to docs you should change your googleapi calls from file to 'external',

drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', 'external');


How to customize the map used on gmap module (node locations)

The google maps parameters can be changed in file: "sites/all/modules/gmap/js/gmap.js"

Here is the option I choose:

Street View enabled:

opts.streetViewControl = true;

Satellite map disabled:

opts.mapTypeControl = false;

Zoom widget change:

opts.zoomControl = true;
opts.zoomControlOptions = {};
opts.zoomControlOptions.style = google.maps.ZoomControlStyle.LARGE;


How to get SMS as send method in the Messaging&Notification module (D7)?

I've used SMS Framework for D7 ,, built a sub-module for my SMS Getway provider (it might be already there for your case),, and with my custom module controlled the rest in notifying|messaging ,,, etc

  The SMS Framework is set of modules that enables interaction between
  mobile users and Drupal using SMS. Several popular SMS gateways are
  supported and the included API allows developers to add support for
  additional gateways. The API also allows other modules to implement
  SMS features.


Is it possible to generate an URL object from a path?

Use Url:fromRoute () and pass in the route's name and arguments. You can also use fromUri() for external paths. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromRoute/8.2.x

I usually find the route name by searching the routing.yml files for the path.

Alternately, you can do this. How to get the Route object from an URI?


How to turn off panels in-place edit bar

Click on the "Panelizer" tab of your content type then click on "Full page override" (or whatever view mode that is panelized" and then under settings you will see:

Standard
In-Place Editor

Click the standard.

The In-Place Editor setting is what is creating the tool bar at the bottom.


Are 'active' and 'staging' required in config_directories?

The default.settings.php file contains the following comment:

  The staging directory is used for configuration imports; the active directory is not used by default, since the default storage for active configuration is the database rather than the file system (this can be changed; see "Active configuration settings" below).

In short:

The staging directory is used only when importing configuration from the UI
The active directory is not used by default from Drupal 8, which saves the configuration data in the database, like Drupal 7 did with the persistent variables

In both the cases, I would expect Drupal to correctly handle the case the global $config_directories is not set.