Workbench sections - notify users in a section on state change

If you use workbench access with a taxonomy scheme you could try this

In rules, add an event After moderation transition.
Add the conditions (previous state moderation, current state moderation) according to yours states in workbench moderation
Add the condition Entity has field and then select the field of your workbench access section (field_section for example : should be the field of your taxonomy vocabulary)

Add an action : send an email.

Then in the field TO of the email , you could use this snippet php wich return the user's email wich have access to the section (specified in Editorial assignments by editor in Workbench Access) and have a specific role id. This snippet return too all the users who have been assigned by their role to the section by their role (Editorial assignments by role in Workbench Access)

<?php

$sections = $node->workbench_access;

$terms=taxonomy_term_load_multiple($sections);

foreach ($terms as $term) {

$parents=taxonomy_get_parents_all($term->tid);

  if (!empty($parents)) {

    foreach ($parents as $parent) {

    $tid=$parent->tid;

    $voc_name=$parent->vocabulary_machine_name;
      if (!in_array($tid, $sections)) {
        $sections[$tid]=$tid;
      }
    }

  $sections[$voc_name]="'".$voc_name."'";
  }
};

// Only the users who have the role id [ROLE_ID]
$role_id=[ROLE_ID];
$emails = array();

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_user workbench, users_roles roles WHERE roles.rid=$role_id AND user.uid=roles.uid AND user.uid=workbench.uid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

foreach ($sections as $section) {
$result = db_query("SELECT user.mail AS mail FROM users user, workbench_access_role workbench, users_roles roles WHERE user.uid=roles.uid AND roles.rid=workbench.rid AND access_id=$section");

  foreach($result as $record) {
    $mail=$record->mail;
    if (!in_array($mail,$emails)) { $emails[] = $mail; }
  }
}

print implode($emails, ",");

?>

And you complete the others email's field with the token available.

This sandbox project Workbench Notify implement this snippet


Theming login form just for specific user registration / Auto Assign Role Page

You are rendering the user_login_block within your template, which is not rendered on the /user/login page.

As long as you have not placed a login-block, that you don't want to be affected, you should not have any problems.

You can use the template file block--user--login.tpl.php to theme this block or even use a form_alter hook to alter the form.


I ended up resolving this by uninstalling and reinstalling all of the migrate-related modules.  Not an ideal solution, but it worked.


How do you automate text file upload daily to a Drupal Page?

it's much more simple, use Mailhandler

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

Mailhandler can connect your inbox and with feed you fetch the messages, so basically you need to run the feed using cron job.
you will find all of that in the configuration of the feed and mailhandler.

Also you can map the attachment with the field where you keep your text file, I don't think there is need to create any plugins, everything you need in mailhandler & feed.


User being logged out of drupal when using form redirect

You should better use $form['redirect'] within a form rather than drupal_goto().

  If you use drupal_goto() you will short cut the form processing skipping any other form_submission functions that have attached themselves to the form. Thus, if you use path_auto and do a drupal_goto while processing a node form, a nice path will not be added to your node because the drupal_goto() was executed before pathauto's node submission handler was called.

Source

This was before the original post was edited. Regarding the logout issue, let us review your procedure.

So essentially: when a form is submitted, mymod_form_submit() calls _mymod_create_order(), which calls _mymod_create_user(), which in turn calls _mymod_logout_user(). All of them unconditionally so far.

If not user 1, you will logout the user and then back in _mymod_create_user() you will attempt to create if necessary and then log the user in.

When you attempt to login the user via user_login_submit(), Drupal will call drupal_session_regenerate(). There, in an attempt to prevent several nasty security possibilities such as session fixation, will generate a new session ID. I suspect the trouble is somewhere there, depending on what exactly happens in the code that displays the redirection page "checkout/...".

In order to deal with this issue I would recommend you to adopt the procedure that other modules use to deal with the possibility that an anonymous user needs to login / be created. Ubercart and Drupal Commerce certainly deal with that. Personally I would suggest to take a look at Ubercart file "uc_cart/uc_cart.pages.inc", function uc_cart_checkout()


When adding a relationship to the author, I'm unable to see any custom field

Ideally it should work... Please find exported view below which displays Author Name of last blog post.. You can able to add more fields to the same view..

$view = new view();
$view->name = 'blog_last_poster';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Blog Last Poster';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Blog Last Poster';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '1';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'blog' => 'blog',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');


My bad, i had one of those blind drupal moment :)

Yes it seem that drupal can't find the url because of the 404 which become the current node, but with some PHP we can still get it.

  $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
  print $pageURL;

[that is not my code, so thank you Google.]


Have Leaflet marker popup open on page load

The leaflet module fires an event after a map is created, called "leaflet.map".
You should be able to listen for this event and get the map object like this:

(function ($) {
  Drupal.behaviors.openMarker = {
    attach:function (context, settings) {
      $(document, context).on('leaflet.map', function(event, map){
        // console.log(map);
        // logic to open marker goes here
      })
    }
  };
})(jQuery);

Leaflet module also fires an event called 'leaflet.feature'.

NOTE: the above code is untested


How can I add custom content to a Drupal 6 menu?

Try the megamenu module.  I haven't used it, but it appears to be designed to do exactly what you are looking to do.  Unfortunately, it appears that the capability to add blocks inside menu items only exists in the version for Drupal 7, but the D6 version supports most of the functionality you need.


Without going into the ins and outs, Drupal understands the .module file as being a module within the system. The .inc notation has always been used in PHP for 'include' files. When developing modules you might want to split functionality into different .inc files.

Modules being used in specific cases use conventions similar to .admin.inc. That file typically includes all the code necessary to run the administrative interface, and a file node.pages.inc for example contains the code executed for other menu callbacks.


Just like validating the user email in any system you check if its already exists or not, in your case we need to check that we have no entity with the same attribute value exists:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'Fruit_Store')
  ->entityCondition('bundle', 'store')
  // this is a condition for the entity field values
  ->fieldCondition('field_title', 'value', 'spotlight', '=');

$result = $query->execute();

if (!empty($result['Fruit_Store'])) {
  // entity already exsits.
}
else{
  // add new entity
}

you can find more information about EntityFieldQuery in this page:

https://www.drupal.org/node/1343708


Try with this:

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

This should print the field you want.

Change 'your_field_name' with machine name of the desired field.

You can install and enable Devel module and add this:

<?php dsm($node); ?>
<?php dsm($content); ?>

in your print.tpl.php file. You will see all $node and content fields.

UPDATE

Also, you can add this function in your template.php file:

/**
  * Renders the content of the print page using the theme api.
  */
function THEME_preprocess_print(&$vars, $hook) {

// Global node.
$node = $vars['node'];

// Create a var and render using field_view_value
$vars['any_variable'] = field_view_value('node', $node, 'your_field_name', $node->your_field_name[$node->language][0]);

}

Replace THEME with your theme name, any_variable with any name you want for this variable and your_field_name with machine name of your field.

After this you can render your field in print.tpl.php file like this:

<?php print render($any_variable); ?>

Again, change any_variable with the name you choose for this variable in function from template.php file.


Using Media, views, and colorbox to create a image gallery

I don't see anything in bold but is the issue showing the image in your custom style or having it open in a modal?

For the latter, opening the image in a modal, you would need to set one field item to be the colorbox trigger.

The trigger needs to be a field you have already added, in your case the image field which you will use the custom display format with. Then you add the image field again with the desired popup format. You set this field to display within the colorbox trigger.

There are several related screencasts on drupal.org that may help:

https://drupal.org/project/colorbox


How to use expert class settings for display suite for images?

Have you tried  Image Class.

  Extends the Image formatter by adding an option to add an element
  class.

It does not work in combination with Display Suite unfortunately as per this post: Merge Image Class into Display Suite


You can't add html to the t() function.
A quick (and maybe dirty way) is to just do something like this:

   '#title' => t('Selected'),
   '#options' => array(
      0 => t('No') . 'Markup',
     1 => t('Yes') . '

Markup

',


In Chrome right click on the text and choose 'inspect element'. Find the css selector for that element. Then go into the stylesheet for your theme, and add a rule there to add margin-left to the text.

It sounds like it might be a javascript problem if you can't click a certain link. Check javascript errors in the console.


How to output all taxonomy field values on a node in views?

You can use the views distinct mode.

Drupal 7: Query Settings > distinct
Drupal 6: Distinct

Either that or hook into the view and do some extra processing through a custom module.


Cache page based on cookie value and URL

You can do it without .htaccess rules.

Drupal core cache; modify in your settings.php file (apache only). From http://drupal.org/node/361832#comment-4204294

<?php
// Check if cookie is set.
if (!empty($_COOKIE['my_cookie'])) {
  // Add cookie value to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['my_cookie'];

}
// Disable page cache if cookie not set so your magic code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}
?>

Memcache
http://drupal.org/node/942914#comment-4477150


How to get rid of CKEditor and recover access to admin pages?

I have to ask, did you properly uninstall CKEditor?  As in disable the module first (in admin/modules) and then uninstall (admin/modules/uninstall)?

It sounds like you just deleted the folder without uninstalling it properly...


Create image style options, when user is uploading an image

Insert

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

more details Upload images style


There is a nice module to handle visibility of menu items. You can use the module or see code in side the module.

May be It will help you. I am not sure :P

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


How to create a translation and get author and post date copied from the original node

The Synchronize translations module, part of the Internationalization (i18n) package, allows you to synchronize fields and other node elements.

After enabling it, have a look at admin/structure/types/manage/your-content-type  options, in "synchronize translations", and check the boxes author and post date


How to do I stop product URLs changing each time I delete and re-import?

There are two ways:

Don't delete them. Import them and let Feeds update them.
If you can't use above (for example no proper UUID on them), after node deletion, go to http://example.com/admin/config/search/path/delete_bulk and delete old aliases as well - that will free addresses for reuse.

Flipping "published" on and off is the way Drupal is designed to work, not deleting and re-uploading.
On the other hand, path module implements hook_node_delete() - hook called for each node deletion by node_delete_multiple() and node_delete() to delete aliases of deleted nodes. If it isn't, it's a core bug , or incompatibility between modules. You can fight to have it fixed, or try to implement hook_node_delete() on your own. Code of original implementation is very simple:

function path_node_delete($node) {
  // Delete all aliases associated with this node.
  path_delete(array('source' => 'node/' . $node->nid));
}

Of course to get it to work you may need to use some code from inside path_delete() to get query work properly, or to omit call to hook_path_delete() if one of it's implementation is buggy.


It's in dev but the Epub module is probably your best starting-point.

  The new epub module for Drupal 7 provides displays for file entity and file fields and enables users to read epub/ibooks files inside their browsers like pdf module.

It doesn't import as a node, but you can take a lot of code from that module to build your own node-import version.

Interestingly, the reverse operation has already been implemented in Epub export, so you might want to have a look at the code for that one too.


How to find whether the term is first or last in a vocabulary?

First, you need to obtain one level of your taxonomy terms. Use either taxonomy_get_tree($vid, 0, 1); for top level ones, or taxonomy_get_children($tid) for children of a known element.

It should be sorted the way you want it, as both functions contain this in their code:

$query->orderBy('t.weight');
$query->orderBy('t.name');

Now you can use standard PHP functions reset(array &$array) and end(array &$array) to get first and last object from that array for comparison. Note that this will move internal pointer around, so don't use them lightly on arrays you also use elsewhere already.


Send Email when node has been updated with specific term/selection

In rules Add Condition >> Data Comparison >> node:field-[name of your field goes here]

Add Action >> Send Mail


In D8 the handling of active links is split between php and js, so that the menus can be cached independently from the page they appear on. A solution in php or twig is only possible when you switch off caching of menus, but this is not good for performance. So a better approach is probably in javascript.

Remove the link tag by selecting the links with the class is-active:

mytheme/js/remove-active-links.js

(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.removeActiveLinks = {
    attach: function (context) {

      $(context).find('a.is-active').contents().unwrap();

    }
  };

})(jQuery, Drupal);

You need to define a dependency on the core active-link.js, which sets the class is-active, so that your js file runs later:

mytheme/mytheme.libraries.yml

remove-active-links:
  version: 1.x
  js:
    js/remove-active-links.js: { }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.active-link

Background information

The js code above is the most basic solution, but it loads jQuery also for anonymous traffic, which is not a problem if you already use it.

If you want to avoid jQuery see ActiveLinkResponseFilter, which is a response subscriber adding the class is-active for anonymous requests.

You can then alter the result in a custom response subscriber with a lower priority, similar to the js code above.


Yes, definitely something with rules together with http://drupal.org/project/mimemail (I would also recommend http://drupal.org/project/phpmailer together with mimemail), if you want to mail them, or use the https://drupal.org/project/messaging framework and notifications or similar.

You can use rules scheduler to do this on a schedule or use rules events such as "After saving a new term" to trigger the lookup when a term is saved. The tricky part is the conditions/actions of looking up.

You can use the data comparison condition together with a php evaluation to lookup the user profile/term and then generate an action of sending a mail.

Or you may need to use fetch entity by id/property depending on what you have available to the situation to load the node and the same for the user profile, and then compare those results in a php custom action.

The last option is to use views bulk operations to do the lookup for you and then load the list in the rule using the views bulk operations action.


Show node's content moderation state in a view

In Drupal 8.5 this has gotten a lot easier.

Pre-requesities:

1) Enable content_moderation (which enables workflows).

2) Set up a workflow with content moderation states.

3) Create a new view with the base table "Content Revisions".  This is important, as the main content out of the box is based on "Content" which refers to the default revision.  We want to see the latest revision.  I made this mistake at first where I took the default content view and added a relationship to Content: Moderation State.  This is the moderation state of the default revision, which is not what we want to see.  We want to see the moderation state of the latest revision.

4a) Under "Filter Criteria" add filter "Is Latest Revision".

5) To display the moderation state, under "Fields" select "Content Revision: Moderation state".

6) To filter by moderation state, under "Filter Criteria" add filter "Content Revision: Moderation state" and expose it.

7) Save your view.

8) You'll need to update your content so that it has moderation states.  This can be done by resaving it.

For example you could run:

  $article_nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->execute();

  $articles = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($article_nids);
  foreach ($articles as $article) {
    $article->save();
  }

Now your view should show moderation states.

It looks like Drupal 8.5 also adds a subtask on the system.admin_content route that shows a link to a page that displays moderated content.

If you'd like to turn off these subtasks:

/**
 * Implements hook_menu_local_tasks_alter().
 */
function mymodule_menu_local_tasks_alter(&$data, $route_name) {
  if ($route_name == 'system.admin_content') {
    if (!empty($data['tabs'][1]['content_moderation.content'])) {
      unset($data['tabs'][1]['content_moderation.content']);
    }
    if (!empty($data['tabs'][1]['content_moderation.moderated_content'])) {
      unset($data['tabs'][1]['content_moderation.moderated_content']);
    }
  }
}


Send personalized email to a particular role

Try using the views_send module instead. This powerful module acts like views_bulk_operations in that it lets you create a view to execute an action using Drupal's batch API for processing. For your case (roughly following the directions on the project page):

Create a view of users and add the user email field to the list
Add the field 'Global: Send e-mail' to activate the Views Send functionality
Add any other fields that you want to include in your customized email as fields in the view (ex. User: First Name, User: Last Name)
Finally, add a filter to filter by the particular role(s) you want to filter on.
You probably also want to secure the views permissions so non-authorized users can't use the view to send to your users.

If that's all setup then when you visit your page, you will see a list of all users in that role with the option to send an email to them. When you select your users and are ready to send your email, you will then see on the next page the option to use any of the fields you've selected above as tokens in your email (thus the customizable option):


How to use autocomplete text field in fieldset?

finally got the solution
here is updated code

$form['profile_2_type']['field_test_auto_cmplete']['und'][0]['value']['#autocomplete_path'] = 'user/autocomplete';

and "user/autocomplete" only works for admin users


How to send an automatic reply using webform?

Yes you can do that in the following way:

Add an email field in webform. Set that field to get the users email by clicking "User email as default" option in the field's edit page.
Configure your forms to send emails by going at node/%nid/webform/emails and choosing "Component value", then choose your component.
After you add this "rule" you can then configure the actual email send to the user.

PS if you are not sure what the capabilities of a module are you can try it out at https://simplytest.me/.


How to add a time picker in datetime form elements

Your code renders a time type input for the second field, which will invoke the standard time widget for browsers that support it (most modern ones do).

For all browsers that I know of, that's a simple input mask and placeholders, not a dropdown picker like the date field. If you need such a picker, you'll have to find and integrate a JS library to get it.

You could do it yourself, but there's a contributed module, Datetime picker, which integrates 3 different time picker libraries so you can choose your favourite. If that doesn't give you exactly what you want, the code should at least give you a good starting point to implement your preferred solution.

In case you still need it, you can remove the seconds from the time input by setting #date_increment on the element to 60, which sets the step attribute on the element. That causes Chrome at least to only include placeholders for hours and minutes.


How to make a block only appear for a certain content type?

This can be done in a few ways.

If your content type always has a unique URL (such as /news) you can set the block to only show when on a page matching that URL.

Or this can be managed in a variety of ways using different plugins that allow for the manipulation of displaying content types and their corresponding views/blocks.

Are you currently using any plugins like that or have any themes installed?


How can I set a 'global' Exposed filter rewrite for taxonomy terms on a view

Found a excellent module Token formatters. Can be used in various places, but for this application it's spot on.

Once installed, the formatter for a entity reference field on a view gets and addition in the dropdown 'Tokenized Text'. That in turn allow for a a wider range of token us. [see all your tokens at Admin -> Help -> Token ].

Drop the Token of your choice and swap out between fields or Taxonomies.

In my case I has an additional field on my Taxonomy terms. All the regular places I tried to reference it only gave termID or termLabel as options. Now I can use the build in features of taxonomy terms, but on one of their custom text fields.


Generate consecutive number as title using auto_nodetitle?

If you haven't installed Token module, do so.

From there, you can insert the token [node:nid] into the auto title field. If you don't want to use the nid, you can install the Serial field module, add a field to the content type, and insert that into the title via [node:field_machine_name]. For most purposes, nid should suffice.

You can browse & insert token values via the supplied token browser ui.


Fivestar appears on content type, but can't vote

When adding the FiveStar field,

If you choose "Rated while viewing" , that means all users can rate the node (with permissions) can rate the node. This is ideal to allow users to rate how well the article was writtem etc).
If you choose "rated while editing", it will make the rating field disabled (static field) for other users than the node author. This is ideal for review nodes to allow the reviewer to leave their ratings while making the node or any other entity.


How to present a field or another in a content type, depending on context

For the module approach i recommend to evaluate this one: Conditional Fields.

  Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.


Due to talking from comments, there answer that help:

You cann't alternate node/add/nodetype via Test.
You can create alias Test for node/add/nodetype or you can write custom function, that call node/add/nodetype form via drupal_get_form with some node preparements function.
After this you can apply Panels and so on

First answer was incorrect:
Enable Page manager module (part of CTools), then goto admin/structure/pages and add 'Add custom page', set path to test, save it. Now you can use your Panels that fire for Test page.


How to display form element and label inline

The label placement is something set by the theme you're using, and should be consistent across your site. If all labels are above the corresponding element, you should think twice about changing that position just for one or only a few form elements. If you want all the labels next to the element instead of above, the proper place to change that is in the theme.
But let me answer the question as posed:
There is no need to complicate the document structure by adding container elements for the sole purpose of adding a class. The Form API already wraps input elements with a div, and adds standard classes to these divs, so the trick here is to target the existing div and put your class on that existing div.
You can add your class to the div surrounding the form element by using the totally undocumented property #wrapper_attributes. It is used like this:
'odt-filter' => [
  '#type' => 'textfield',
  '#title' => 'Filtra',
  '#wrapper_attributes' => [
    'id' => 'odt-filter',
    'class' => ['container-inline'],
  ],
] ,

Note this is Drupal 8 so I have changed your example to use short array syntax and I have changed your 'id' attribute to be a string, not an array. You may use both the #attributes and the #wrapper_attributes properties at the same time, in case you wanted to add the class to the div and the id to the input, for example.


Add extension .csv to file created with Views Data Export

In the view settings click on Format: CSV File > Settings

In the dialog box that appear, be sure that Provide as file is selected. In the Filename field that appears when that option is selected, leave the default value (%view.csv).

%view, which adds the view machine name to the filename, is only one of the available replacement tokens. As visible in the screenshot, the other ones are:

%display
%exposed
%timestamp-full
%timestamp-yy
%timestamp-yyyy
%timestamp-mm
%timestamp-mmm
%timestamp-dd
%timestamp-ddd
%timestamp-hh
%timestamp-ii
%timestamp-ss


Multilingual menu's are quite nasty sometimes. I suppose you use i18n menu? Then have a look at the following:

Make sure the Menu link enabled only for the [LANGUAGE] language, on the menu tab of the node edit page is disabled. That makes sure the entry is shown on all pages.

Also make sure the menu entry is language neutral by going to admin > structure > menu's > [MENU NAME] > [MENU ITEM] and check the language drop-down.


Can a Drupal view show some fields for one role and other fields for another role without having two page views?

You can add all the fields to the view and than hide some of them in either a hook, a preprocess function or a template file.

There views module provide many hooks for you to use i suggest the views view pre render hook.

If you choose the preprocess route than you will need to find the correct template first. Go to the view configuration page and look for a link called theme info. That link will be placed in the advanced column at the very bottom.

After you know which template you need add the corresponding preprocess function to your THEME.theme file.

Fit the views-view-unformatted.tpl.php a function called THEME_views_view_unformatted_preprocess will work.


How do I find out which module loads which javascript file?

"If you look at the source of the page you can see the path for each script. This will identify where the script is."

Example

Typically the script located at...

sites/all/modules/contrib/panels/js/panels.js

...would more often than not only be used by the module of the same name

sites/all/modules/contrib/panels/panels.module

...or possible an include file

sites/all/modules/contrib/panels/includes/SOME_FILE.inc

Obviously bare in mind that Drupal uses the jQuery library so references to errors might fallback to these files just because its been implemented wrong by the developer in the module. Its more than likely never going to be something wrong with the libraries.

/misc/jquery.js
/misc/jquery.once.js


Complete clueless how does Facebook OAuth (FBOAuth) work

The message comes from the FBOauth module:

function fboauth_login_user($account) {
  global $user;

  if ($account->status) {
    $form_state['uid'] = $account->uid;
    user_login_submit(array(), $form_state);
  }
  else {
    if ($account->access) {
      drupal_set_message(t('The account with username %name and email %mail ' .
        'is blocked.',
        array('%name' => $account->name,
        '%mail' => $account->mail,)), 'error');
    }
    else {
      drupal_set_message(t('The account with username %name and email %mail ' .
        'is not yet activated.',
        array('%name' => $account->name,
        '%mail' => $account->mail,)), 'error');

    }
  }

  return !empty($user->uid);
}

So the user you're trying to log in with has not yet been activated within Drupal. Once the administrator has activated the account, the user will be able to log in using Facebook.

This is the correct behaviour; un-approved accounts should not be accessible just because they've been signed up through Facebook.


I'd use Views to create a View of Users, and then you can add fields as you like.


How to create file field instance that allow teaser and full description and not allowed extensions but denied extensions?

The second part of your question is easy with the File Entity module - it turns file uploads into fieldable entities, so adding your teaser/description field is just like adding a field anywhere else in Drupal (make you sure you read the README file - it's not overly clear at first).  The module is also on an unstable release, but Dave Reid is pretty damn awesome so I can't imagine it'll be that way for long :-)

Off the top of my head, I can't think of an answer to the first part though I'm afraid.

EDIT

There's an issue here that has a couple of patches for Core that give you a radio box to either Allow only these file types or Allow everything EXCEPT these file types.  I've not tested the patches as I don't really want to patch Core for something that I personally don't need, but definitely give it a read!


Different favicon for local version of site?

Do you use any versioning like Git? If so, you can just upload the real favicon to your live site, then change the favicon locally and add it to your .gitignore afterwards.


thank you pobtastic, this is the answer:

within the .module file you put your hooks and shared functions. Usually in the callbacks, you get to declare 'file' to point to an include for your functions to reside in a nice separate place. See api.drupal.org/api/drupal/modules%21system%21system.api.php/… and api.drupal.org/api/drupal/modules%21system%21system.api.php/… –  Pobtastic 1 hour ago


Is it possible to combine RSS feeds and other stories in the same view?

Can you give more details? Do you mean importing a feed into your website and then displaying its contents alongside your own? You'd need the Feeds module to do that.

UPDATE: Yes, this is possible. You need the Feeds module, and to create a content-type to hold the feeds. When displaying your view, use Filters to narrow it down to just your user-entry content-type and the Feeds-info content-type, and they will both display (in whatever order you set, the default is posted date).


Custom actions not appearing in the Trigger/Action settings page

To allow a new action to appear on the triggers page, you need to visit the administration page at admin/settings/actions, or call actions_synchronize().


The Libra theme is a sub-theme of the Omega theme, but seemingly the Omega theme is not present (otherwise, omega_theme() would be defined). Make sure that you have placed the Omega theme in /home/itcom/public_html/sites/all/themes/omega and try again.


How do I enable PHP extensions on CentOS to finally finish installing/configuring Drupal?

On CentOS, you should have an icon in cPanel for "PHP Selector":

In CloudLinux:

Make sure all of the PHP extensions installed by Yum are enabled & save the settings. Then create or open the info.php page for your domain to confirm the configuration. The problem should be fixed on the Drupal 8 status report.

Note: If you are having problems with installing PHP extensions for a web server running Drupal, consider installing Composer on CentOS. Composer is designed to streamline dependency management in PHP and manages the particular download files required by Drupal 8 modules specifically.


Drupal 8 - Bootstrap paragraphs not rendering color and width classes

From your screenshots, it looks like it is adding template suggestions back in for the width and color fields. That makes it ignore what we are specifying in the Paragraphs bundle level templates, to print the content without those two fields.

My guess is that comes from the Field Layout module.


Monthly change images directory Drupal 8

I solved this problem using this module: https://www.drupal.org/project/filefield_paths
You can change path for every field type and use tokens like /[date:custom:Y]/[date:custom:m] to achive what I wanted...


Move "Log in or Register to post comments" to the bottom of the page

You need to change the fields order in Manage display /admin/structure/types/manage/page/display (replace page with your content type machine name e.g. article). Change Links after Comments.

If you don't want to show this information in lists, then in teaser view mode drag links under Disabled. Note that this will also disable the default read more link. If you don't have teaser tab available, then you need to enable it under Custom display settings.


How do I update a field value in hook_entity_insert()?

From this solution we can able to do like below to update an field on hook_entity_insert

$entity->field_range->value = 'test';
drupal_register_shutdown_function('_cc_custom_post_insert',$entity);

function _cc_custom_post_insert($entity) {
    if($entity) {
        $entity->save();
    }
}


Add class to views row instead of replace system classes

Your question is simply a PHP programming question, and not entirely Drupal related. But here goes:

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image)) {
      $old_class_values = $vars['classes_array'][$id];
      $vars['classes_array'][$id] = $old_class_values . ' has_field';
    }
    else {
      $vars['classes_array'][$id] = $old_class_values . ' has_no_field';
    }
  }
}


How feasible is a Drupal 8 with a different language depending on its subdomain

Multilingual has seen a big improvement for Drupal 8. All you need can be done with Drupal 7, so it it's possible with Drupal 8 too.

You have to set Language Negotiation to subdomain. This way Drupal sets the content language depending on the domain accessed. For example, example.com/en/node/1 is English content and example.com/es/node/1 is Spanish content (you can also configure so no subdomains maps to a certain language).

Regarding performance Drupal 8 has a very good caching system that is much better than Drupal 7 (specially when we talk about cache invalidation).

What I don't recommend in any case is to have two separate Drupal installations one for each language. No benefits from this approach and lot of issues instead. Just think on content sync, user sync, config sync, etc. Drupal can manage two and much more languages without having performance issues.


How to alter inline entity form fields on node edit drupal

Actually documentation of module in readme file the hook was written and i was using that hook but only problem was the custom module name. if your custom module name is two parts like custom_websitename then this hook did not work in my case, so after one day i changed module name to single word and hook worked.. I am sharing code incase someone need to update lineitemform in node edit for drupal commerce.

function customruba_inline_entity_form_entity_form_alter(&$entity_form,   $form_state){
$entity_form['commerce_price']['#access']=false;
$entity_form['field_commerce_saleprice_on_sale']['#access']=false;
$entity_form['field_commerce_saleprice']['#access']=false;
$entity_form['status']['#access']=false;
}

this worked for me to hide some information on inline entity form


How do I use the #autocomplete_route_name property?

Users are entities so they're treated generically. The route is system.entity_autocomplete, with some parameters, but you don't need to get your hands that dirty. You can use the "entity autocomplete" form element type instead, which should be as simple as:

$form['project']['users'] = array(
  '#type' => 'entity_autocomplete',
  '#title' => t('choose users'),
  '#target_type' => 'user',
);

It's derived from a TextField, so you can use all the usual properties. Examples do seem to be a little hard to find other than in the core files (it's early days), but you can see all the available properties the entity_complete adds in EntityAutocomplete::getInfo(), and how they're used within other methods of the class.


Webforms: Is it possible to set a delete field button?

This link seems to have some solution. Clear upload file input field with jQuery

The relevant js is given below.

  The HTML of any element can be reset with jQuery using the following
  function and passing in the id of the element's parent. This will
  reset the HTML within the parent to its original state; it will lose
  any binding you'd added after the DOM was loaded (such as adding an
  event handler in $(document).ready). Here's the Javascript for doing
  this:

function reset_html(id) {
    $('#'+id).html($('#'+id).html());
}

  In $(document).ready we can now add a div around every  element with a clear button, binding a function to it
  which will reset the HTML of the div like so:

$(document).ready(function() {

    var file_input_index = 0;
    $('input[type=file]').each(function() {
        file_input_index++;
        $(this).wrap('

');
        $(this).after('<input type="button" value="Clear" onclick="reset_html(\'file_input_container_'+file_input_index+'\')" />');
    });

});

Note : I have not tested this out myself.


How to log and display all the users that have edited a node (without revisioning)?

The Activity module does some user activity logging that may covert your need.

  The Activity module keeps track of the things people do on your site
  and provides mini-feeds of these activities in blocks, in a
  specialized table, and via RSS. The module is extensible so that any
  other module can integrate with it. The messages that are produced are
  customizable via the admin interface and are context sensitive. Some
  theoretical example messages include:

  You wrote a comment in response to "example comment title"
  Jim wants to be your friend. Approve this friendship here
  Nancy is Phil's latest fan


Where all are the hooks defined in a contributed module?

The convention is to park all core hook implementations in .module.
.inc files are used to break off different groups of code like custom class definitions & administration form handlers. Some have their own naming convention for contrib hook implementations (e.g. .views.inc, .rules.inc, etc.).


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'semaphore' doesn't exist

I also got the same problem.
Then i realizez that when migrating, i copy and paste from old server. And when i opend the database on my new server and choose a table in it, it was emty giving me error: "table does not exist". So check out if it is importing the content of the data firt before continuing with your search.


Field widget do not save values in database!

So it turns out Shyghar ran into an issue that I've run into more than I care to tell – which is that hook_field_is_empty() was returning FALSE by checking the wrong data (or something along those lines).


In Drupal 8, you cannot anymore disable modules: You can just install or uninstall them. Uninstalling a module has the same effect it had on Drupal 7 and previous versions: It removes the database tables the module installed.

On /admin/modules, Drupal shows you which modules are not installed, and which modules are installed. You can click the checkbox shown for the modules that aren't installed; clicking on Install at the bottom of the page will install them.

For installed modules, clicking on the checkbox shown before the module name doesn't have any effect. In fact, the checkbox is disabled.

To uninstall a module from the user interface, you just go to /admin/modules/uninstall (or click on the Uninstall tab visible on /admin/modules).

Select the modules you want to uninstall, and click on the Uninstall button shown on the bottom of the page.

Keep in mind that Drupal can still not being able to uninstall a module for various reasons, for example because the module implements an entity and you created those entities on the site.

You could also use Drupal Console for uninstalling a module, but you would need to install it (on the server). After you install it, and open a terminal window on the Drupal root directory of the site, with drupal module:uninstall <module_name> you would uninstall the <module_name> module.

From the user interface it's easier. It's the only possible way, if you are working on a remote site for which the provider doesn't allow you to use an SSH shell.


If you are creating the form with the help of a custom module, you can sort the options in the form at the time of db query before displaying them. You can do something like this.

$query=db_select('table name','n');//here your table name
 $query->fields('n', array('title'));//SELECT the fields from table
 $query ->orderBy('title', 'DESC')//ORDER BY create
 $opts=$query->execute()->fetchAllKeyed();

$form['courses'] = array(
    '#type' => 'select',
    '#title' => t('courses'),
    '#multiple' => TRUE,
    '#options' => $opts,
);


How to select FROM {commerce_product} p WHERE p.field_TERMFIELD = $given_tid and the resulted p.product_id is referenced on a given nid

I think I got it figured out:

$query = db_select('commerce_product', 'p');
$query->join('field_data_field_TERMFIELD', 't', 't.entity_id = p.product_id');
// This is the product reference field table. This field is attached to our node.
$query->join('field_data_field_product_reference', 'pr', 'pr.field_product_reference_product_id = p.product_id');

$query
  // This is the product_id we are looking for.
  ->fields('p', array('product_id'))

  ->condition('field_TERMFIELD_tid', $tid)
  ->condition('pr.entity_type', 'node')
  ->condition('pr.entity_id', $nid);

 $result = $query->execute();


Why am I getting undefined is not a function when using jquery?

(function ($) {
  $(document).ready(function(){

  your code here

  });
})(jQuery);


How to show votes in view results by node id?

You can use hook_query_alter() in your custom module. Your code should look like this:

function MODULENAME_query_alter(&$query) {
  if(!empty($query->alterMetaData['view']->name) && $query->alterMetaData['view']->name == 'VIEWNAME'){
    $query->groupBy("node.nid");
  }
}


"Cannot use a scalar value as an array" error

Sometimes these error messages come up on my sites if cron is run while the site is in maintenance mode. I'm guessing the maintenance mode template for our site has something to do with it, but it could be a variety of things.

When cron runs, it is still running through Drupal's theme system, so you probably have something awry in either your theme or one of your custom modules. Does this happen every time cron runs, or just sometimes?

A final troubleshooting step would be to install elysia_cron and run each cron task individually to see which one might be causing all these errors.

See also: Warning: Cannot use a scalar value as an array


How to get the uncached version of request headers?

Concerning CDNs or Varnish you need to ask in a different place. In Drupal you find two caches for requests/responses:

The Internal Page Cache, which is implemented in a kernel middleware, and you need to define a middleware with a higher priority to handle the uncached request.
The Dynamic Page Cache, which is implemented in a kernel request subscriber, and you need an event subscriber with a higher priority to handle the uncached request.

By the way, when you implement one of these methods, don't send the response, return it or set it in the event.

Example for a redirect middleware: https://drupal.stackexchange.com/a/247478/47547


I use HybridAuth Social Login for login system via social networks


I will try and provide you a general direction which I think might serve you well:

Create a text field, with label something like this "Please add tags of your choice if you dont find adequate options".(purpose is explanatory from the label)
Create a content type, "Proposed Taxonomy Terms". Let it have only title and body field.
Now on saving a node of the content type in which we had the suggestion field, grab the value of the proposed taxonomy terms from it, create a node of type "Proposed taxonomy term" and clear the value of the field in the first content type.
Now the nodes in the content type "Proposed taxonomy Term" will be your basis which you need to set up such moderation. it will initially remain unpublished. Upon validation, write custom code, to grab the title on its save and create a taxonomy term in the vocabulary(which was used as term referance field in the first content type), and delete the node (or you may choose to keep it).

So next time when user tries to create the node of the first content type, they will have it as an option. this is a complex workflow. The logic parts you can do custom code better, employing drupal hooks or you may choose to use rules module (not sure it will serve the purpose exactly though).

Hope this long answer did not confuse you.


Try this token instead:

[current-user:name]


How do I sort a view based on when a specific field was last updated?

Such attributes are not available on fields, but they are available for nodes, and it sounds like that's all you need.

Views already provides a Sort Criteria for "Content: Updated date."

To sort by node statistics, make sure that the Statistics module is enabled (it's part of Core). That will provide additional Sort Criteria in Views. Add a Sort Criteria and filter by "Content statistics" to see three new options.

If you really need to use similar attributes on fields, you can use Rules to update extra fields based on whichever events you desire, and filter Views with those values.


CCK select list and default values from array without writing custom module

How about this:

global $user;
return array(
  0 => array( 'value' => $user->uid )
);


I dont know of anyway to sort a view buy the arguments it receives. So this may not be really what your looking for but currently there's no other answers here and hopefully one of these alternative suggestions will help you.

Suggestion 1)

On your questionnaire submit function use views_get_view_result http://api.drupal.org/api/views/views.module/function/views_get_view_result/7 send the arguments to your view as normal you'll get back your 5 top hits but not sorted correctly. You can then reorder the results and manipulate the order the results appear in and print out your manipulated view.

Suggestion 2)

Using Views PHP module http://drupal.org/project/views_php you can create your own sorting with php. You can pass your view the data you need with url's or $_POST get that data in your view and create the sorting using that.

In a nut shell, I dont know how to do what you want, heres a couple of avenues I would probably try..


I don't know if you've been hacked, or just accidentally copied those folders to root, but they shouldn't be in root by default.


Unable to save field collection order of collection that includes entity reference anymore

Actually found that this was caused by a JS error on the page. That explains everything. Fix the JS error, fix the problem.


View fields from the same database column

I finally found the answer.

  $data['uc_orders']['data2'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Arrival Date'),
    'real field' => 'data',
    'help' => t('Arrival date choosen by customer during checkout.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_arrive_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

  $data['uc_orders']['data'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

The solution is to add 'real field' => 'field name', and change the $data id.


Sumit Madan was spot on.  Several blocks were hard coded as front page only in the page.tpl in the contributed theme.

For other newbies caught out by hard coding, the cues are:

The visibility settings for a block behave erratically, i.e., in a pattern not consistent with your expectations
When you inspect the regions (/Structure/Blocks - at the top), some of the regions do not appear. Yet, you can put a block into them and the show up when you inspect under Firebug. Now I understand the problem, a quirk that had puzzled me is fully explained.

To find the hard coding in page.tpl, look for ($is_front) and change that to ($page != 0).

page=0 refers to pages like lists of taxonomies. So this edit means the relevant blocks will be available to all pages including the front page and can be managed using the block visibility as usual.

Thanks everyone.


How to use value passed to views_embed_view as a filter?

The value you pass as last argument to views_embed_view is not passed to the Views' filters, but to the view's contextual filters  (also known as arguments). Contextual Filters are like filters, expect they take external input (from the URL when viewed as a page or from the arguments passed to functions such as views_embed_view). You can learn more about contextual filters here: http://drupal.org/node/1578558


How to implement decoupled user registration with React / jsonapi?

To register user using core Rest Module you need 5 steps:
Step 1: Download and enable Rest UI module, this module provides a user interface for administrating Rest Endpoints. Using this module's configuration (admin/config/services/rest) Enable User Registration

Step 2: Then in account setting configuration you should allow user to create account, and if you want user to be added using user name and password you will need to uncheck require email verification else leave it checked.

Step 3: Now you need to allow anonymous user to access user registration (admin/people/permissions/anonymous):

Step 4: Another step to take is to get a xcsrf token from drupal cause you need to use a post method for user creation and post methods are unsafe methods, so drupal protects them using token, to get a XCSRF Token simply call /session/token endpoint.
Step 5: Now final step is to ask for user creation:
Method: POST
Endpoint: user/register?_format=json
Header:
Content-Type: application/json
Accept: application/json
X-CSRF-Token: "XCSRF TOKEN PROVIDED BY DRUPAL"

Body:
{
  "name": [{"value": "USERNAME"}],
  "mail": [{"value": "EMAIL"}],
  "pass":[{"value": "PASSWORD"}]
}

and that's it.
PS:
Remember that if you have not unchecked "require email verification" in account settings form then you should exclude pass from your request body. in this case user needs to navigate to your drupal site for email verification which in case of decoupled scenario it sounds wired. so I highly recommend to uncheck this option in account settings configuration.
Another PS:
If you need to require user to confirm his/her email, then you can use a simple solution, like add a verify code to user (prevent user access to this field using Field Permissions module) then in hook_user_presave you can assign a code to it, send user an email containing this code and finally deactivate user) , finally you will need a custom Rest endpoint so user can fill a form containing email field and code and if code matches the one you sent you can activate user's account.


How can I untheme a fieldset provided by theme_fieldset()?

You need to alter the form that contains that fieldset. You could do it using code similar to the following one.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Only alter user forms if there is more than one language.
  if (drupal_multilingual()) {
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      if (isset($form['locale'])) {
        foreach (element_children($form['locale']) as $id) {
          $form[$id] = $form['locale'][$id];
          $form[$id]['#access'] = $form['locale']['#access'];
        }
      }

      unset($form['locale']);
    }
  }
}

The code I wrote removes the fieldset from both the registration form, and the user profile form.
For the user registration form, the language fieldset is normally hidden to the users that don't have the permission to administer users. There could be a module that shows that fieldset to every user.
If you want to be sure that your code doesn't create problems to other modules, you should be sure it is executed after all the other modules that add fields to $form['locale'].
Usually there isn't any reason to remove a fieldset. It is convenient for the users to have related fields grouped together; in that way, if they don't need to edit them, they just collapse the fieldset.

To be sure the code of your module is executed after all the other modules, you could do proceed with two methods:

You can alter the module weight, and increase it. In this way, the hooks implemented in your module would be executed for last.
You can implement hook_module_implements_alter() to alter the order some hooks are executed.

function mymodule_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move mymodule_form_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

The documentation for hook_module_implements_alter() reports the following notes:

  Note that hooks invoked using drupal_alter() can have multiple variations (such as hook_form_alter() and hook_form_FORM_ID_alter()). drupal_alter() will call all such variants defined by a single module in turn. For the purposes of hook_module_implements_alter(), these variants are treated as a single hook. Thus, to ensure that your implementation ofhook_form_FORM_ID_alter() is called at the right time, you will have to have to change the order of hook_form_alter() implementation in hook_module_implements_alter().

Between the two methods, I would use the latter, as it doesn't change the order other hooks are executed, differently from the first.


Update the from name in workbench email template

I'm pretty sure that $message['from'] shall be an email address.

Try to set the From header instead, like this:

$message['headers']['From'] = 'Full Name <email@address.com>';


Best way of including a View without extra modules as Panels, CTools, Context, etc

views_embed_view is a common method of doing it with highly degree of flexibility. Make sure that the type of the view's display (of the embedded view) is Embed. This display type can be made accessible in views UI by enabling it inside view's advanced settings.


Yes a bundle is always, always necessary for entities.

If you don't define your own bundle(s), the entity system will assign a default one with the same name as the entity type for you, and that one will be used.

If you've only got one bundle, and only ever plan to have one bundle, then you don't need to have a specific field in your entity table for it. As you suggest in your question it would always be the same, so would be redundant and just add extra overhead (however tiny) to your db queries.

If you think you might need to distinguish between different sub-types of your entity at some point though, it would be worth building that in right from the start; it really depends on your use case.


To revert a very simple commit, this is enough:

git revert ba24a3fdeae4a3a034691308171d798d2ddbf93e

here that long string of characters is the ID of the commit you are reverting.

To get the ID of the commit see the git log.


How to use $language array in region--header.tpl.php

$language; is a global variable in drupal 7. You can get this variable in region--header.tpl.php as shown below:

global $language;


In Drupal Commerce, what Rules need to be set to go directly to checkout after Add to Cart button is clicked?

Since this isn't built into Drupal commerce itself, you have to create a new custom rule (admin/config/workflow/rules). The event would be called:

After adding a product to the cart

and then the action would be:

System > Redirect Page

URL should be: checkout


Drupal 7 chosen module use ajax to fill the select

I'm not completely sure about this, but have you tried triggering "chosen:updated" after updating the options? See Updating Chosen Dynamically

$("#form_field").trigger("chosen:updated");


Using Drupal 7 Rules, how to react to a file upload and change a node field?

Workflow

  This module allows you to create arbitrary Workflows, and assign them
  to Entities.

  Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).

How we use workflow module

Creating a Workflow

Editorial workflow with Rules


Image shows on home page, but not on article page

When contrib images are missing in drupal the cause more often than not is that you have permissions problems with regards to your filesystem.

Make sure that your webserver can write to your files and files/styles directories.

If permissions are ok then drupal will create your medium_large directory and subdirectories.

Check the drupal setup documentation here (see the paragraph "Create the files directory").
As mentioned there make sure that you have write permissions on your sites/default/files directory.


Image preview not generated on node edit page

There should not be any blank line before opening or after closing php tags. The chances of having it with index.php, template.php,settings.php etc. files


With a view of flaggings, how do I get the flagged entity?

Whoops, this is a work in progress to be added to Flag at some point.
In the meantime, this can be worked around using an entity reference field.
First, add an entity reference field to the flag.
Next, set the entity reference using hook_flagging_presave().
function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
  switch ($flagging->getFlagId()) {
    case 'MYFLAGTYPE':
      if ($flagging->isNew()) {
        // Set entity reference for new flaggings.
        $flagged_entity_id = $flagging->get('entity_id')->value;
        $flagging->set('field_myflag_entityreference', $flagged_entity_id);
      }
    break;
  }
}

Finally, you can use the entity reference to the flagged node in your view in the same way as any other entity reference.
Because the flag module patch to solve this issue is in flux, it seems to me a bit dangerous to apply the patch to a production site, because the ultimate direction of the flag module may differ from any given patch. So, using an entity reference has the advantage of achieving the desired solution now (get access to the flagged entity in the flaggings view) while still allowing the future flag solution to be used (when flag becomes able to support this, you can simply delete the entity reference field, as it will no longer be necessary).


Display Suite: how can I generate a render array for a field that is not being displayed

I got it worked out, so here is my new code that actually renders the image fields instead of relying on them being prerendered for me:

/**
 * Implements hook_ds_fields_info().
 */
function MY_MODULE_ds_fields_info($entity_type) {
    if ($entity_type == 'node') {
        $fields = array();
        $fields['generated_cover'] = array(
            'title' => 'Generated Cover',
            'field_type' => DS_FIELD_TYPE_FUNCTION,
            'function' => '_MY_MODULE_ds_field_generated_cover',
            'formatters' => array(
                'standard' => 'Standard output',
            ),
        );
        return array('node' => $fields,);
    }
}

/*
 * Generate the output for the generated cover image field
 */
function _MY_MODULE_ds_field_generated_cover($field) {

    // Get information about the entity being rated and the formatter we're using.
    $entity = $field['entity'];
    $image_style = ($field['view_mode'] == 'teaser') ? 'list_view_cover' : 'medium';

    if (!empty($entity->field_doc_cover)) {
//        $output = "cover";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_cover', $display);
        $output = render($to_render[0]);

    //    $output = render(entity_view('doc_publication_files', $entity->field_doc_cover, 'teaser', $entity->language));
    } else if (!empty($entity->field_doc_pub_files)) {
//        $output = "preview";
        $display = array(
            'settings' => array(
                'image_style' => $image_style,
            ),
            'type' => 'pdfpreview',
            'label' => 'hidden',
        );
        $to_render = field_view_field('node', $entity, 'field_doc_pub_files', $display);
        $output = render($to_render[0]);
    } else {
        $output = "";
    }
    return $output;
}


How to move the login form to the header?

from the website/user. I need the logon to place on the header content
  area and be able to style it.

All you have to do is edit your theme's page.tpl.php

Since the form gets displayed as the page content:

in the header section of your template file add:

<?php if (current_path() == 'user'): ?>
     <?php print render($page['content']);?>
<?php endif; ?>

Then find the original <?php print render($page['content']); ?> and add:

  <?php if (current_path() != 'user'): ?>
     <?php print render($page['content']);?>
  <?php endif; ?>

OR... do the if (current_path() != 'user') { for everything inside the #main-wrapper

OR... use the if statement to add a div class that will colour your #main-wrapper background to red.


Add custom permission to specific module "group" on permissions page

As already said, it would not be a good idea to list a permission implemented by a module together the permissions implemented by another module; it would difficult for users to find the permissions implemented by, for example, custom_module.module, when it is listed together the ones implemented by user.module.

If you really need to change the order used to list the permissions (but then, is it really necessary), then I would suggest to change how the list of permissions is shown: instead of listing them basing on the module implementing it, you could list them basing on different criteria.
To do this, you would need to:

Implement hook_theme_registry_alter() to alter the theme function called when theme('user_admin_perm') is invoked.
Implement your theme function looking at the code of theme_user_admin_perm().

Is it worth doing it? It could be, depending on your customer.
Considering that the first official release for Drupal 7 has been released, and the code for Drupal 7 would change, it is probably not worth doing it. I would rather try to understand why the customer wants to change the order of the permissions listed in the administration page, and explain the reason why changing it is a bad idea; if the customer insists the code needs to be implemented for their own purposes, then I would make him understand that the code should be rewritten when the site passes to Drupal 7, and it is not worth spending time for such changes, when it is possible to use the same time to implement something that  it is really necessary.


D7 - db_select: order by most recent, commented status

You have a classical case, that requires using 'HAVING' SQL operator. Suppose, we have 2 related tables:

| table1 |
|--------|
|   id   |
|--------|
|    1   |
|    2   |
|--------|

table2.f_id is the FK for table1.id

|         table2        |
|--------+------+-------|
|     id | f_id | order |
|--------+------+-------|
|      1 |    1 |     1 |
|      2 |    1 |     2 |
|      3 |    2 |     3 |
|      4 |    2 |     4 |
|--------+------+-------|

And you want to get all the records from table1 with MAX of the related table2.order. And sort them by table2.order. You must use this SQL to get the data:

SELECT
  table1.id AS id1,
  table2.id AS id2,
  table2.order
FROM
    table1
INNER JOIN
    table2
ON
    table1.id=table2.f_id
GROUP BY
    table1.id
HAVING
    MAX(table2.order)
ORDER BY
    table2.order DESC

And you will get:

| id | id1 | order |
|----+-----+-------|
|  2 |   3 |     3 |
|  1 |   1 |     1 |
|----+-----+-------|

Fiddle

Converting this SQL to Drupal, we'll get this:

$query = db_select("table1");
$query->innerJoin("table2", NULL, "table1.id=table2.f_id");
$query->addField("table1", "id", "id1");
$query->addField("table2", "id", "id2");
$query->addField("table2", "order", "order_field");

$query->groupBy("table1.id");
$query->having("MAX(table2.order)");
$query->orderBy("table2.order", "DESC");
$result = $query->execute();
while($row = $result->fetchAssoc())
{
      var_dump($row);
}

So, for your case, this query must work:

$query = db_select("statuses", "thread");
$query->innerJoin("fbss_comments", "comment", "comment.sid = thread.sid");
$query->fields("thread", array("sid", "sender", "created", "message"));
$query->fields("comment", array("created"));

$query->groupBy("thread.sid");
$query->having("MAX(comment.created)");
$query->orderBy("comment.created", "DESC");
$result = $query->execute();


This is in the docs  with every download  of  Drupal...

http://api.drupal.org/api/drupal/UPGRADE.txt/7


Make block render right after enabling the module

After some trials I found an easy workaround:

function mymodule_enable() {
  _block_rehash();
}

It's function which get called then one visits /admin/build/block. It rescans blocks provided by modules.


Edit the token values submitted by webforms

Have a look at the Field Permissions module. From its project page:

  ... allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Since users are entities also, it should work for any of your fields.


Is there a function to get the current user object that avoids accessing the global variable?

The function you could use is user_uid_optional_load(); without arguments, it returns the user object for the currently logged-in user. It still uses the global $user, and loads the full object from the database, including the fields associated to users, but it avoids your code accidentally change the content of the global variable $user, as it is not referenced from your code.

function user_uid_optional_load($uid = NULL) {
  if (!isset($uid)) {
    $uid = $GLOBALS['user']->uid;
  }
  return user_load($uid);
}

If you don't need the full object, then you can use the code already reported in the other answers. If you want to be sure you don't alter the global object, you can copy the global variable into a local variable, as in the following snippet.

$account = $GLOBALS['user'];
// Use $account.

In Drupal 8, you simply use the static method \Drupal::currentUser() to get the equivalent of Drupal 7 $GLOBALS['user'] and \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()) to get a fully loaded object with all its field API fields. There isn't anymore the risk of overriding a global variable with all the consequences.
In the case you need to switch the current user with, for example, the anonymous user, the code you use in Drupal 8 is the following one.

$accountSwitcher = Drupal::service('account_switcher');
$accountSwitcher->switchTo(new Drupal\Core\Session\AnonymousUserSession());

// Your code here.

// Eventually, restore the user account.
$accountSwitcher->switchBack();


PHP Fatal error: Cannot call overloaded function for non-object in /var/www/html/includes/database/query.inc on line 331

On the requirements page there is a "Version specific notes on PHP requirements" section that gives information on supported PHP versions.

Notice that it doesn't mention PHP 5.4 anywhere.
I take this to mean that Drupal 7 is not guaranteed to work with PHP 5.4.

In addition to this there is no hard requirement for any contributed modules to support PHP 5.4 yet.
Some modules will work and some will have problems.
Some modules have already had these problems fixed and I have seen in some cases, maintainers saying they will not support 5.4 if the fix causes problems for older versions, because php 5.2 & 5.3 are the main target versions of Drupal 7.

I would recommend if possible to not use PHP 5.4, and if you do you will quite probably be having to debug more of these issues as you encounter them.

Also, your version of drupal is 10 versions (more than a year) old. If you want to use the cutting edge version of PHP you have to also use the latest versions of all modules as this will give you the best chance of these kinds of issues having been fixed.

Not to mention that there have been some security fixes since 7.12 that you would benefit from having.

Is it an option for you to stay on PHP 5.3?


Solved

Finally I solved the problem with following codes

$eid = $row->id; // a variable to store row id
$sql = "SELECT SUM(field_past_std_date_value2 - field_past_std_date_value) as psd, field_std_pin_target_id as tid
FROM field_data_field_pas_std_date d JOIN field_data_field_std_pin p ON d.entity_id = p.entity_id
WHERE field_std_pin_target_id = $eid";

this bring me the total duration of past study of each student listed in my view. Although the problem is solved there may be better way to writer above squl. if anyone can give comments it will be highly appreciated. I'll continue improving my Drupal skills.


Did you create a Data Overlay with the fields you need in Views? In Views, when you create a Data Overlay that you decide to later use in your map, you define the fields you want to pull from the node (Title, location, etc.) and then assign them inside the Data Overlay dialogue.


How to override the /taxonomy/term/% for specific terms?

In D6, the taxonomy term page is themed by default with a function, but it can be overridden by creating a template in your theme called taxonomy_term_page.tpl.php (or of course writing your own function if you want).

In D7, it provides a default taxonomy-term.tpl.php that can be copied to your theme and modified.

So, you would have to look to see what term is being displayed and if it's one of the ones you want customized, embed your view output for it; otherwise, let taxonomy do it's thing by default.

There is good commentary in the D7 template that should make that pretty straightforward.  In D6, there is a Crazy-Awesome Taxonomy Pages Video with Bob from Mustardseed Media that I found to be quite helpful but there you basically have a $tids array that you can look at to decide what to do.


Why am I not seeing CKEditor buttons on prod?

Which version of Drupal are you running?
Since the new button appears in admin/config/content/formats/full_html I guess the Config Import/Export worked but the connection between the new config and the CKEditor in the content didn't update?
I will try that on my setup since im working with drush cex and drush cim regularly.


In your view's row style options you can rename any exposed field's label. The form labels those fields as alias.

This is screenshot from another view I was working on, but should give you an idea.


Instead of "... save the differences in an Excel table ...", you might want to consider saving these data in an external database (MS SQL, MySql, Oracle, some PDO compliant database, etc).

And then use the Forena module to build custom queries to retrieve the data (directly from such database) and create custom reports from them. Those reports can then be exported in PDF or Excel. For that you just have to enable the desired Forena report options called "document format".

Refer to my answer to "How to download Database results as PDF or in EXCEL" for more details.


How to get current route in the midst of a Views AJAX request

use Symfony\Component\HttpFoundation\Request;

if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $fake_request = Request::create($previousUrl);
    $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
    if ($url_object) {
      $route_name = $url_object->getRouteName();
      // Do something with $route_name;
    }
  }


Deploying code to multiple front end servers

You should probably look into Aegir, which is by far the most flexible and powerful Drupal site management/deployment system. It is able to manage 'platforms' that span acros multiple web heads, or 'clusters', as well as a variety of other configurations.

I'd suggest having a read through of their community documentation which is generally pretty good, as well as reading through mig5's excellent overview and introductory article and some of his other articles like this one.

You can also get good support in the #aegir IRC channel.

It'll be a bit of a workflow change, which can definitely take some time to get your head around, but once you're there you won't look back.


How would you incorporate a log out confirmation screen?

Use jQuery

Pop-up

(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function(e){
            if(!confirm("Are you sure you want to log out?")) { e.preventDefault(); }
        });
    });

})(jQuery, Drupal, this, this.document);

Or text replace

(function ($, Drupal, window, document, undefined) {

    $(document).ready(function(){
        $('a[href="/user/logout"]').click(function() {
            $(this).removeClass('confirm');
            $(this).text("Are you sure?");
            $(this).unbind();
            return false;
        });
    });

})(jQuery, Drupal, this, this.document);

Simple Middle Page

One very simple way to accomplish this would be to create a new page with a simple confirmation message.

For example: Are you sure you want to log out?

Then link to your new page in whichever menu the log out link belongs.

Rules Link

There is a Rules Link module that can create links with JavaScript confirmations, as well as links that use confirm_form()  You could automatically attach a log out link with confirmation to the User entity.

The l() Function

You may also be able to implement the l() function to generate the link you need.

$logout_link = l("Logout", "user/logout", array( 'onclick' => 'return confirm( "Are you sure?" ); ' ) );

Form API

You could use the Form API with a custom submit handler/redirect.

$form['logout'] = array(
    '#type' => 'submit',
    '#value' => t('Logout'),
    '#attributes' => array('onclick' => 'if(!confirm("Really Logout?")){return false;}'),
);


How much memory and storage does a website take on a server?

You should be fine with 1GB server ram, and 256M set for PHP. Keep in mind you won't be running a huge site with it, so also invest in getting caching like memcache and something like varnish going as well. I'm not sure if memcache is PHP7 ready yet - but using php7 will gain some performance increase as well.

However if you're looking for free hosting, I think you could also try Acquia Cloud Free.


Add custom text as a label in front of RSS feed icon

You can see feed-icon.html.twig

you need copy feed-icon.html.twig in core/modules/system/templates/feed-icon.html.twig to themes/yourtheme/templates/feed-icon.html.twig

in file themes/yourtheme/templates/feed-icon.html.twig

{#
/**
 * @file
 * Default theme implementation for a feed icon.
 *
 * Available variables:
 * - url: An internal system path or a fully qualified external URL of the feed.
 * - attributes: Remaining HTML attributes for the feed link.
 *   - title: A descriptive title of the feed link.
 *   - class: HTML classes to be applied to the feed link.
 *
 * @ingroup themeable
 */
#}
<a href="{{ url }}"{{ attributes.addClass('feed-icon') }}>
  {{ 'Subscribe to News Feed'}}
</a>


When I save a user account as an admin, I get logged in as that user

Can you re-produce the problem from CLI?

Using drush scr, bootstrap, login as user 1, save a new user, check if your ID changed.

If you can do this from CLI, git bisect can be very helpful in finding the commit that caused it.


Rule conditions may be negated by checking the Negate checkbox ("If checked, the condition result is negated such that it returns TRUE if it evaluates to FALSE.") You can't negate a rule event or an action.


Removing Duplicates with hook_views_prerender

You do not need to do this - simply use Distinct.

Edit the View, open the Advanced section -> Query Settings -> check the "Distinct" checkbox and save the view.

Edit:
In case you do use Distinct already, there are some cases where this can occur. Here is an issue discussing this - https://www.drupal.org/node/1765730, and this one has a code example that manipulates the result similarly to what you are trying to do - https://www.drupal.org/node/1223448#comment-4757898


Can't find migration when running drush migration:status

Did you try clearing drush cache with drush cr drush?
Also, the correct notation for checking the status is drush migrate-status demo_user_migration


You may use Panels module.

Using that you can place comment form any where as your specification.

For more info go through project documentation .


Display single field from argument taxonomy term in Views header area

I've included my original response below but it turns out I'm an idiot: All you have to do is create the taxonomy-term as a relationship and then you can just pick out the field you want. D'oh!

~~~ my original answer

Yeah, so this is a problem that is currently unsolvable without code as of Drupal 8.6.0. Unless you deploy Display Suite, which is using a sledgehammer to crack a nut.

There's a lot of discussion on drupal.org about the lack of control on title fields in respect to nodes but the issue goes deeper. It applies to Taxonomy as well: You cannot stop the title field from appearing in any view mode because that's the way the template works.

The only solution is to create a new template that doesn't display the title (in my case taxonomy-term--book-series.twig.html) plus the supporting hook_theme() and hook_preprocess_taxonomy_term__book_series() all of which is a PITA.

Even then it's not great because there are no (default) theme suggestions for taxonomy terms that include view modes. It would have been much nicer if I could have designed a view mode called "description" and then had a theme suggestion of taxonomy-term--description.twig.html because that would then work in all cases. Instead I have to create the same template and support code but for a different vocabulary.

All-in-all, not the best experience.


How do you export configuration from configuration module

Enable Configuration Management UI submodule

Goto yoursite.com/admin/config/system/configuration/migrate

There is links for Export & Import


If you run drush make --contrib-destination=sites/mysite, then modules will be placed in sites/mysite/modules.  rsync is going to be faster than Drush make. (Edit: This speed comparison presumes roughly equal transfer speeds between the endpoints. I can see how make might be faster if you have a fast connection from the target to d.o, but a slow connection between the source and the target.)

If you want to create a makefile for an existing site, you may use drush generate-makefile, or build a whole installation profile with drush generate-profile.


There is also the view unpublished module which will allow anon users to view the unpublished node they just completed.


Error when trying to edit and save a user field

element_validate_number() was added in Drupal 7.6 (or 7.8, I can't quite remember) so it may be that you have an older version of core that doesn't contain that function.

If you can't upgrade your version of core, try adding this into a module file, it should save you the headache:

if (!function_exists('element_validate_number')) {
  function element_validate_number($element, &$form_state) {
    $value = $element['#value'];
    if ($value != '' && !is_numeric($value)) {
      form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
    }
  }
}

In case you're interested element_validate_number() is the replacement for the deprecated _element_validate_number().


How do I dynamically fill a textfield with #ajax?

After messing with this for a while, I discovered that I needed to unset the textfield. Once I did this default_value started to work with ajax, below is the final code I had.

unset($form_state['input']['profile_name']);

$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper',
    ),
);

$profile = isset($form_state['values']['profiles']) ? _get_profile_info($form_state['values']['profiles']) : NULL;

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '
',
    '#suffix' => '
',
    '#title' => 'Profile Name',
    '#default_value' => $profile == NULL ? '' : $profile[0]->{'name'},
);


Node reference field share between two content types

I'm not sure you can do it with Conditional Fields, so I did it with a custom code. You have to :

Hook on your form
Get referenced node
Get its taxonomy value(s)
Check this values in your term reference field.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "page_node_form") {
        $form['field_OUTLETS']['#prefix'] = '
';
        $form['field_OUTLETS']['#suffix'] = '
';
        $form['field_STOREREFERENCE']['und']['#ajax'] = array(
            'callback' => 'MYCALLBACK',
            'wrapper' => 'mytaxofield',
            'method' => 'replace',
            'effect' => 'fade',
        );
    }
}

function MYCALLBACK($form, $form_state) {
    if(!empty($form_state['input']['field_STOREREFERENCE'])) {
        $nr = node_load($form_state['input']['field_STOREREFERENCE']['und']);
        foreach($nr->field_OUTLETS['und'] as $delta => $value) {
            // Add term to default values
            $form['field_OUTLETS']['und']['#default_value'][] = $value['tid'];
            // As it's not enough (I might need help on that one), I force it with the '#checked' value
            $form['field_OUTLETS']['und'][$value['tid']]['#checked'] = TRUE;
        }
        $form['field_OUTLETS']['und']['#default_value'] = drupal_map_assoc($form['field_OUTLETS']['und']['#default_value']);
    }
    return $form['field_OUTLETS'];
}


Should I use the Workbench Access module to implement the workflow we have in mind?

The Workbench Access module seems to only partially cover your needs.
If it was up to me to implement a solution for the challenge you're trying to solve, I'd go for another approach, as further detailed below.

Have a look at my answers to either of these questions:

How to implement a multi step approval with webforms/entityforms based on form components?
How can I allow anonymous visitors to submit content?

These answers explain how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access.

And by using such approach, it does not require modules like "Webform" or "Workbench" (modules that are typically involved for these kinds of workfows).


Is there a way to allow an authenticated user to add to another users post?

You can use the Content Access module to give the users permission to content level.


Simple Sitemap using default instead of website URL

This happenes when generating the sitemap via CLI cron without --uri parameter. Either pass the Domain into the CLI
drush --uri=https://www.example.com simple-sitemap:generate

or use the web interface to generate the sitemap.


What is causing this duplicated node issue?

The function node_submit() contains the node_save() function. So you call it twice.


How do I return the output from a callback function unthemed?

This is really easy: instead of returning the output in the page callback, just print it and exit.

Drupal 6

function foo_callback() {
  print theme('foo');
  exit();
}

One thing to keep in mind when doing this is that hook_exit() will not be invoked, as you'll be ending the script before Drupal reaches that point, so make sure you don't need it. If you do, you can invoke it yourself before calling exit():

function foo_callback() {
  print theme('foo');
  module_invoke_all('exit');
  exit();
}

Drupal 7

drupal_exit() was added for this use-case, and will call all the shutdown stuff before exiting. So you just need:

function foo_callback() {
  print theme('foo');
  drupal_exit();
}


Best practice two domains on one codebase and database

It really depends on what you need to do with the Blog vs. the regular site. For Flocknote, we decided to use www.flocknote.com/blog for the blog (so it would be easy to maintain as part of the rest of the website), but also have blog.flocknote.com redirect to the /blog URL (we set that up through a simple .htaccess rule, but you could also set up the redirect through your DNS provider).

If you really don't want the blog running within the same interface/site as the main site, but still want it running on Drupal, you can do that with one of the methods you mention. Just install another drupal site at blog.example.com using a database prefix (see Sharing a single database across multiple sites). Domain Access is a great solution if you plan on setting up more than a few subdomains on the same codebase, but it's overkill if you just want to run a blog. subdomain.

Or, if you want to set up another database, you could create a folder blog.example.com in the sites folder, point the blog subdomain/virtualhost to the same directory as the main site, and then use the separate database when installing Drupal.


How to edit Menu primary nav tab in Drupal 8

You may wish to use hook_local_tasks_alter() and/or hook_menu_local_tasks_alter() to hide/rename local tasks.


Is it possible to migrate taxonomy terms when having only the term name?

I probably will use feeds module and hook_feeds_presave to manually re-import taxonomy name and reset the node associate your that taxonomy.


How to work with caching and conditional rendering in a template?

Here are some solutions I can think of:

Solution 1: Use CSS (easiest)

Make sure the slogan has some classname you can refer to. Example: site-slogan. Use body classes to change slogan visibility. Here's some rough CSS to get you started.

/* Hide slogan for all pages */
#block-site-branding .site-slogan {
  display: none;
}
/* Show slogan for front page */
body.path-frontpage #block-site-branding .site-slogan {
  display: block;
}

Solution 2: Use 2 block instances (not recommended)

Setup one block instance, say block-site-branding-front for the home page and configure it to show the slogan. Make this block visible only for <front> page.
Setup another block instance, say block-site-branding-inner for the inner pages and configure it to hide the slogan. Make this block visible for all but <front> page.

You can also define a custom block in a custom module, but that would be an overkill. I think the first solution should do the trick.


The Superfish module does that. It integrates the Superfish jQuery script into Drupal. It has two responsive menu options for small screens; either rendering it has an accordion or a drop-down. I strongly recommend using the Dev version as it is 'production ready' and has multiple improvements over the older release.


Use Field Collections and add two fields to field collection and enable field collection field on your content type... Or Create two fields Flag and Flag date...

Flag
Flag Date

OR

You can use revisions to track these changes in Drupal. When ever you change above field make content as a new revision so that you can track dates too...

OR

Create a few more date fields, each for possible values to track the dates... use form api #states property to hide display fields based on selection of flag value..

Flag
Draft Date
Sent Date
Approved Date
Rejected Date


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

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

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

And that's it.


What are configuration entities used for?

I would like to add some additional general thoughts on the differences…

Content entities are generally external facing, meaning your site viewers will interact with your content – ie. they will read your pages & articles; they will look at your images, they will browse thru your product catalog, they will post comments and reviews, etc.

Config entities are generally internal facing, normally only site administrators & content editors interact with a config entity such as setting up a new view or adding a block to a page.

There are many, many, instances of content entities – think of a news website and how many hundreds or thousands of articles there are, but there are only a few instances of config entities – with the article, there may just be one content type (content types are config entities) needed for all those articles.

Content entities generally store data in their own database tables and fields though you don’t have to use hook_schema to create them, they are more often instantiated in the class annotations, with yaml files or by using the UI.  Config entities can have database fields, but by default they do not.  That is not to say they don’t have fields, they do have fields.  The content type entity has fields, such as name and description (you just won’t find them in the database as such).


I think you just need to parse out the query string, and then use XSLTProcessor::setParameter:

/* generate hook */
function _xml_import_generate()
{
  $p = $_GET['p'];

  $path = drupal_get_path('module', 'xml_import');

  $xsl = new DOMDocument();
  $xsl->load("{$path}/xml_import.xsl");

  $xslt = new XSLTProcessor();
  $xslt->importStyleSheet($xsl);

  $xslt->setParameter("", "p", $p);

  $xml = new DOMDocument();
  $xml->load("feed.xml");

  return (string) $xslt->transformToXML($xml);
}

Your parameter should then appears as a <xsl:param /> in your XSLT.


// Generate pdf card.
$file_path = $crm_card->generatePdfCard();
$filename = basename($file_path);
$headers = [
  'Content-Type' => 'application/octet-stream',
  'Content-Disposition' => 'attachment; filename="' . $filename . '"',
  'Content-Length' => filesize($file_path),
];

$binary_file_response = new BinaryFileResponse($file_path, 200, $headers);
$binary_file_response->deleteFileAfterSend(TRUE);

return $binary_file_response;


Value from ajaxified form field not passed to ajax callback

$form_state['values']['field_video_reference']['und'][0]['target_id'] looks wrong to me.

I would expect the value to be in $form_state['values']['field_video_reference'].

If you haven't already then install the Devel module and then use can use dpm($form_state); to output the array to the message area and inspect it to find the correct path.

Sometimes for ajax requests Devel Debug Log is also useful as it allows you to send a dump of a variable to a log so you can inspect it even if it is not possible to send content to the message area.