Error "Public files directory Not fully protected" Appears in Nginx?

In the security advisory referenced in the error, it describes the specific vulnerability as "Code execution prevention (Files directory .htaccess for Apache - Drupal 6 and 7)" and recommends updates to your htaccess files in your files directory. Part of the recommended htaccess update is the following text:

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</files>

The SetHandler string is what Drupal is using to determine whether you've made this change or not.  Even though you're using Nginx as your webserver, its still going to display this error until you've made this update. From the advisory again:

  To fix the code execution prevention vulnerability on existing Apache
  installations also requires changes to your site's .htaccess files in
  the files directories. Until you do this, your site's status report
  page at admin/reports/status will display error messages about the
  problem. Please note that if you are using a different web server such
  as Nginx the .htaccess files have no effect and you need to configure
  PHP execution protection yourself in the respective server
  configuration files.

I'm running a couple nginx servers as well and had to make these updates just to make these errors go away. I was curious how they were doing this check and found this in the
modules/system/system.install file at line 284:

// Check for the string which was added to the recommended .htaccess file
// in the latest security update.
if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file))
|| strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {
...


That theme is using a grid, looks like a base of 24. It's not the padding that's causing the blog to not display in the full page, but the grid (IE, the grid widths).

If your uncomfortable with updating the css of this theme, you may want to switch to a theme that's not grid based. Though it's not full page, business or something like it might be more suited to what you want to do.


I'm trying to solve the same problem and one part of a possible solution would be to assign every linked page (A2, B2, etc.) to taxonomy terms based on the menu structure. This way you can get a list of all items linked under A1. The problem is to bring it in the same order as the menu links...


I can use the exposed filter to manually select any matching nodes,
  but do not know how to automatically filter the queried RideShares to
  the current user's data in other bundle/content types. For example,
  whether the current user has entered a Flight into where the
  destination airpor catches one of the existing RideShares.

Views is a simple query builder. Typically this would be SQL like Select * From RideShares Where city = 'denver'. Your question cannot be expressed in single SQL expression you would need JOINs in SQL of PHP and multiple queries to arrive at an answer.

Your talking about relating a set of results with additional logic or data-sources.

This can be done in Drupal using a combination of Views Relationships perhaps Attachment Views to build results you want.

For example I might create a Nodequeue of uids that are users on the same flights as me and examine a View result that uses the Nodequeue as a Filter against the current user to see if that logic produces any results.

You could then place many view blocks on a single page that acts as a search results page. Each block can be a View with many view-attachments, etc.


You know that you want something from taxonomy module so first you need to look in Drupal\taxonomy\Entity -- or the corresponding directory -- you will find the Term class there. Now look at the annotation, it says @ContentEntityType and in there:

*   entity_keys = {
*     "id" = "tid",
*     "bundle" = "vid",
*     "label" = "name",
*     "uuid" = "uuid"
*   },

So, what you want is

$term = Term::create([
  'name' => 'test',
  'vid' => 'client',
])->save();

because the label entity key is name and the bundle entity key is vid. I added a ->save() call as well as I presume you wanted to save it too.


How can I get a user's language from their e-mail address in PHP?

I don't think there's an API function to do exactly that, but a single database query would get you that information:

// Query the database
$args = array(':email' => $email_address);
$lang = db_query('SELECT language FROM {users} WHERE mail = :email', $args)->fetchField();

// If there's no language string use LANGUAGE_UNDEFINED instead.
// This is also a fallback method to use the default language
// if the user is not found in the database.
if (!$lang || empty($lang)) {
  $lang = LANGUAGE_UNDEFINED; // Or whatever your default language is
}

If you need the user object itself for whatever reason, you can use a slight variation on the above:

$args = array(':email' => $email_address);
$uid = db_query('SELECT uid FROM {users} WHERE mail = :email', $args)->fetchField();

if ($uid) {
  $account = user_load($uid);
  $lang = $account->language;
}

You could also take advantage of the $conditions parameter of user_load_multiple(), but this method has been deprecated so it might not be the best idea to use it:

$users = user_load_multiple(array(), array('mail' => $email_address));
if (!empty($users)) {
  $account = array_shift($users);
  $lang = $account->language;
}

Last but not least, you could use an EntityFieldQuery, although this would probably be overkill for this particular task. It is a useful thing to know though:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('mail', $email_address);

$results = $query->execute();
if (isset($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
  if (!empty($users)) {
    $account = array_shift($users);
    $lang = $account->language;
  }
}


Making geolocated latitude/longitude values available to computed field in Drupal 7

I think I was assuming locations are geolocated on edit/changes and that's saved to DB, which appears to not be the case. At any rate, I was able to use the location ID from $field_info to load the location, which then has the lat/long data I need:

$loc = location_load_location($field_info['lid']);
$longitude = $loc['longitude'];
$latitude = $loc['latitude'];

That was annoying...


Can I publish something in my wall of facebook?

Set a session variable, or a cookie, when sent the first time; check that always.


You should be using hook_menu() to create a custom page from code. The hook_menu() allows to define a URL and page callback which will be called when user hit the url. Check the example below:

/**
  * Implements hook_menu().
  */
function [MODULE_NAME]_menu() {
  $items['MODULE_CALLBACK'] = array(
    'title' => 'My Custom URL',
    'page callback' => '_MODULE_NAME_page_callback',
    'access arguments' => array('access content'),
  );

  return $items;
}

function _MODULE_NAME_page_callback() {
  $image_name = (!empty($_GET['image']) ? $_GET['image'] : '');

  // Write code here.
  $data = $image_name;

  return $data;
}

The _MODULE_NAME_page_callback() callback will be called when user hit the URL as sitename.com/MODULE_CALLBACK?image=imagename.jpg.


Cloned site means that you copied the database instead of installing twice from scratch.

Drupal identifies two different sites as cloned sites by checking their uuid. If the uuids match, then it will assume that the sites are cloned instances.

Faulty configuration imports can lead to broken sites which we may not be able to restore. Hence to avoid this situation as discussed on https://www.drupal.org/node/2133325 a safety mechanism was introduced. And that mechanism was having a uuid for each Drupal site.

So if you know what you are doing and you are sure that you need to import the configurations, you can use the drush cget system.site command on source site and you can use drush cedit system.site on target website to change the uuid to that from the source.


How to use user_load() for user on $_GET[] request in Drupal way?

As said in the comment for the question, you should use placeholders in your menu definition.

function hover_card_menu() {
  $items['hover-card/%user'] = array(
    'title' => 'Hover Card',
    'page callback' => 'hover_card',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

Then you can pass the user ID for the currently logged-in user to the JavaScript code, instead of passed the module path, which is irrelevant.

function hover_card_init() {
  $module_path = drupal_get_path('module', 'hover_card');
  drupal_add_js($module_path . '/javascripts/hover_card.js');
  drupal_add_js(array('hover_card' => array('user_id' => $GLOBALS['user']->uid)), array('type' => 'setting', 'scope' => JS_DEFAULT));
}

The JavaScript code doesn't need to know the module path, since it will make an AJAX call to hover-card/%user which is not related to the module path in any way.


Can you get the node id you are aiming for? If so, try using drupal_get_path_alias()

$linknid = $fields['field_link_to_content']->content;

$alias = drupal_get_path_alias('node/' . $linknid);

<a href='<?php print $alias; ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>

UPDATE - this is how I did it, based on this answer:

<a href='<?php print drupal_get_path_alias('node/' . $row->nid); ?>' style='background-image: url(<?php print $output; ?>);'><?php print $row->node_title; ?>


Feeds import - If title has "=" at the end, check whether duplicate content exists

Set product title as unique

First, you'll need to set the product title as unique. This way, Feeds will only import one product per title.

Is the "=" at the end important to the product title? If not, you'll need to find a way to remove that sign from the product title. This way, Feeds will treat a product title with an "=" as equal to the same product title without the "=".

Find replace Tamper plugin (D7 and D8)

If you are certain that the sign "=" is only used at the end of the product title (or meaningless if it appears anywhere else), you can use the easiest solution: Use the Tamper plugin "Find replace" to replace "=" with "". This plugin is available for both D7 and D8.

Find replace REGEX Tamper plugin (currently D7 only)

If the "=" sign can appear elsewhere in the product title and is important there, you'll need to use the "Find replace REGEX" tamper plugin. In the field "REGEX to find", enter a regex that matches strings ending with a "=":

/\=$/

And replace with an empty string.

D7 or D8?

At the moment of writing, the Tamper plugin "Find replace REGEX" has not been ported to D8 yet (see https://www.drupal.org/project/tamper/issues/2975179 for the status). If you are using D8 and the Tamper plugin "Find replace" does not suffice, you'll to create a custom module and listen to the Feeds parse event in order to apply modifications on the product titles.

Example:

namespace Drupal\mymodule\EventSubscriber;

class ProductFeedSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[FeedsEvents::PARSE][] = ['afterParse', FeedsEvents::AFTER];
    return $events;
  }

  /**
   * Act on parser result.
   */
  public function afterParse(ParseEvent $event) {
    // Check if this is the feed we want to edit.
    $feed_type_id = $event->getFeed()->getType()->id();
    if ($feed_type_id != 'myfeedtype') {
      // Not the feed type we want to edit. Abort.
      return;
    }

    /** @var \Drupal\feeds\Result\ParserResultInterface */
    $parser_result = $event->getParserResult();

    /** @var \Drupal\feeds\Feeds\Item\ItemInterface */
    foreach ($parser_result as $item) {
      // Get product title.
      $title = $item->get('title');

      // Remove "=" sign from the end if there is any.
      $title = preg_replace('/\=$', '', $title);

      // Set title back on item.
      $item->set('title', $title);
    }
  }

}

Be sure to replace "myfeedtype" in the example above with the name of the feed type that you created for importing products.

An event listener always needs to be declared in your module's 'services.yml' file:

services:
  mymodule.product_feed:
    class: Drupal\mymodule\EventSubscriber\ProductFeedSubscriber
    tags:
      - {name: event_subscriber}

In the D7 version, you would need to implement the hook hook_feeds_after_parse() to alter the parsed result.


How to send mail with multiple images from node using Rules module?

<?php
foreach($node->field_name['und'] as $file) {
  echo  drupal_realpath(file_load($file['fid'])->uri);
echo ("\n");}
?>

This code worked for me!!!


Taxonomy VTN provide new pages for taxonomy terms, as described in its page it provide what you want by Terms of a parent: taxonomy_vtn/voc/xxx/xxx option

in Drupal 7 you can use views to show child terms in page when you click on parent term:

create new views for taxonomy terms (you should select taxonomy terms in creation form)
create page display
select taxonomy/term/% as path
use argument


How to force forms only through your own submit functions?

Since I suggested this in my comment (the first in the thread) I'll rephrase as an answer so that you can mark it as correct.

Rather than using drupal_get_form() to build the node edit form (which just doesn't work the way you tried to do it, as there is no such callback my_content_type_node_form as far as I know) and then modifying the $form array, my suggestion is to:

Let Drupal build your node edit form (you can do this by calling the appropriate URL /node/8/edit or /node/add/[type])
Then use the widely documented way of altering a form by implementing
hook_form_alter.

EDIT: Digging a bit more I did find a hook_form function callback for nodes, but it's standard for all nodes - it's implemented in the node.module as node_content_form(). The hook is invoked in node_form() but as far as I can tell (I did some trials) it's the same for all Content Types regardless of their machine name. I think this may be where the confusion started.


I need to store an array of integers for configuration of a custom module - which of these is right?

For saving module config settings, I use variable_set() in conjunction with the system_settings_form() function. Just also note that it and its companion variable_get() do the serialize/unserialize for you, so, there is no need for you to be doing it.


Is there any convention about the name to use for a file containing a class definition?

The only part of the Drupal coding standards that talks of filenames doesn't say how to name PHP files containing class definitions.

Files containing PHP code, which are not the main module file, or the installation file, usually use the extension .inc, in Drupal 7 and previous versions. As there isn't any possibility of conflict between files used from different modules, you can decide the rest of the filename.

Note that Drupal 7 uses a registry, which contains a list of files defining classes. If you have a file defying a class, you just add a line similar to the following one, on the .info file.

    files[] =

In this way, the file will be automatically loaded by Drupal when you reference the class, such as when you instance an object of that class, or you call a method defined in that class.

Drupal 8 uses .php as extension for PHP files containing a class, such as Node.php, Uuid.php, and Database.php.


Smart Paging have the option to navigation with previous/next links with numeric navigation see the below image and add a css style to prev/next class to achieve the button effect. See the demo

also worth checking this module Pagerer for providing a collection of pager themes to enhance Drupal and Views standard pagers. See Demo


Where are the RESTful module permissions other than `Administer REST resource configuration`?

This was introduced since 8.2.0

Accessing entities via REST no longer requires additional REST-specific permissions

  This was actually only meant to be a temporary measure, because we
  already have an Entity Access API that governs access/operations to/on
  those entities. And in fact, Entity Access is respected when accessing
  entities via REST. So, there was no more reason for this to exist in
  Drupal 8.0.x and Drupal 8.1.x, but it was simply forgotten to be
  removed before Drupal 8.0.0's release. The fact that you needed to
  grant both those permissions as well as Entity Access needing to grant
  you access, was a source of confusion and frustration with Drupal 8's
  REST API, which has now been fixed.

  So, as of Drupal 8.2.0, new installations no longer need those permissions to access entities via REST. Existing installations
  continue to have the old behavior. Existing sites can opt out of that
  behavior, and opt in to the new behavior, by modifying the
  rest.settings configuration from

  bc_entity_resource_permissions: true

  to

  bc_entity_resource_permissions: false

  (The latter is the default on new Drupal 8.2 installations.)


How do I PUT update on a node using services 3

What Services version do you use?

Since Services 7.3.4 we deen to set Cookie & X-CSRF Token on header for every (PUT/POST) execution

Please check this comment too
https://drupal.org/comment/6491362#comment-6491362


How do I remove the Title "Languages" from the Language Icon Module?

To remove the title 'Languages', configure the block, and set the title as <none>

To have the icons side by side and remove the list bullets you need to specify some css in your theme:

section.block .content .language-switcher-locale-url li {
  background: none; // in your case, you have background set
  display: inline-block; // to make them side by side
  list-style-type: none; // to get rid of listing bullets
}


Ways to have lots of blocks on a site which is easy to manage

You can use Nodeblock module - create a content type named "block", and then you can manage edit permissions like with any other node, using modules you want. It'll also support fields, translations et cetera. You can use taxonomy to keep track of what is where.


You should get the name with the getName method.
In your case :

$term[1]->getName();
$term->getName();

If not, you can load the term and after get the name:

$term = Term::load($term[1]->id());
$term->getName();


Safe string checkup against user-supplied suffix/prefix strings

Treat it like any other user input; that is, not to be trusted. Do you have a reason to allow HTML tags in the prefix/suffix? If not, output only after running through check_plain(). filter_xss() is quite permissive in its allowed tags so just be sure you're OK with that before using. See also the drupal.org documentation on handling text in a secure way.


Show/hide views on content-type based on taxonomy-terms

The general idea is the following:

You create a custom block (via custom module).
You place it through the interace to be visible only on nodes of type "A".

The code checks the value of field_tags.

if it is "tag1" -> views_embed_view('test_view_1', 'block_1');
if it is "tag2" -> views_embed_view('test_view_2', 'block_1);

You can see code below:

namespace Drupal\form_overwrite\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

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

    // Gets current node.
    $node = \Drupal::routeMatch()->getParameter('node');

    // Assuming only 1 value here.
    $tid = $node->get('field_tags')->getString();

    // If there are more values you have to loop through them. The format is.
    // $tid = $tag[0]['target_id'];

    // Loads the taxonomy term.
    $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);

    // Gets the label.
    $name = $term->label();

    // TODO: probably a better idea would be to use uuid of those terms, since
    // the names tend to change overtime.
    // TODO: Didn't test a case with translations.
    if ($name == 'tag1') {
      // Using the old but gold function views_embed_view() to get renderable array.
      // The render function spits the html, based on views_embed_view output.
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    elseif ($name == 'tag2') {
      $content = render(views_embed_view('test_view_1', 'block_1'));
    }
    else {
      // Case where there is not tag.
      $content = '.....';
    }
    $build = [];
    $build['default_block']['#markup'] = render($content);
    // TODO: Remove it after development. It is used only to invalidate the cache.
    $build['#cache']['max-age'] = 0;

    return $build;

  }

}


Clearing the cache has no immediate effect.

Then it's very likely that is not a caching issue and it's a set up issue.

This should work, is greater than 0 minutes


Architechture/ Foundation help for a drupal project

I'm not sure what you mean by "properties" in your question.  However, you can use the Fivestar module to add ratings to a content type. So your Camera content type could have a rating for each camera and your mobile content type could have a rating for each mobile.

Search will work across all content types. http://drupal.org/documentation/modules/search


Register for an event and create an account on one page

Based on this existing answer, I could find the Inline Registration module. It lets you register while creating a node at the same time (one form). Since this is node-specific, this may allow a "event registration" content type to be defined then assigned to the user registration form.


is there a way to change multiple tags at once?

If you changed the tag itself from taxonomy. It will change for all content that use the tag. The only issue you may run into is if your doing url paths based on any taxonomy terms.


Create a class to extend the systemqueue. I called mine Unique. This will serialise the data use db_merge to insert only if it doesn't exist.

class Unique extends SystemQueue {

  public function createItem($data) {

    // save doing this twice
    $serial_data = serialize($data);

    // ignoring expire
    $query = db_merge('queue')
    ->key(array('name' => $this->name, 'data' => $serial_data))
    ->fields(array(
        'name' => $this->name,
        'data' => $serial_data,
        'created' => time(),
    ));
    return (bool) $query->execute();
  }
}

You then add the variables to hook_install() or hook_enable().

variable_set('queue_class_[your queue name]', 'Unique');

matching [your queue name] to the queue name, e.g if you used this:

DrupalQueue::get('update_profile_tasks')->createQueue();

the variable would be:

variable_set('queue_class_update_profile_tasks', 'Unique');

Thanks to this for getting me on track. Updated answer to be cleaner thanks to comment suggestions.


Admin denied access to Ubercart Store when running Ubercart SSL

I would go with the Secure Pages module http://drupal.org/project/securepages and I've create a small write up on how to set up Secure Pages with UC http://drupal.org/node/1586258


How do I output a hidden password field as part of Drupal form?

If you don't want Honeypot module as mentioned by Jimajamma, you can do it with Form API #attributes all right:

$form['pass'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#maxlength' => 64,
  '#size' => 15,
  '#attributes' = array('style' => array('display:none;'));
);

Of course it's easy to catch display:none in bot's code. It's also common and not so much harder to find out that class applied is styled with it in CSS. There are two methods that are not yet so easy to catch:

Using box model and overflow to make element hidden under other HTML boxes.
JavaScript code to move it out of sight or apply display: none to it

In both cases you shouldn't use obvious identifiers in html, like .honeypot or .hidden, as this will be probably easily found by the bot, too. Also, z-index usually isn't the way to go, as it tells bot "this element is under other one", or "this element is over other one, hides something".


Another approach (if you don't want to run sql-statements directly) would be Queue UI:

  View queues and number of items
  Developers can define meta info about queues they create and process
  Process queue with Batch API
  Process queue during cron
  Remove leases
  Delete queue


You should read about the field_view_field(), something like this should work for you:

print render(field_view_field('node', $node, 'field_nazionalita_1'));


Just given it a quick test with VBO 1.10, and as you said, emails are not being sent. Also, got "Cannot use %author token in this context." error in log.

See this issue - http://drupal.org/node/1003354 - "Can't sent email (or 'send tokenized email') on a user view. Reverting to 6.x-1.9 works" - seems that 1.9 should work better, or - if dev is acceptable to you - 6.x-1.x-dev

Or use Views Send instead (http://drupal.org/project/views_send)


What are effective optimization techniques for Views 3?

You first should find out where the performance bottleneck is.

Is it the executing of the query
Is it the rendering of the view
Is it a specific function

See http://drupalperformanceblog.com/drupal-xhprof-profiling about the article.

Once you have the problem it's possible to fix it.
You wrote that you had enabled views caching: Which kind of caching output or query cache?


how to differ start date and end date in a table views

You can add a global php field where you have the end date available as a token, you can get the current time using now and then get the difference between the 2 dates in days.


Profile types with unique fields (Profile2?)

The profile 2 page states:

  Profile2 allows for creating multiple profile types, which may be
  assigned to roles via permissions (e.g. a general profile + a customer
  profile)

Did you set-up different roles for coach and player?


The module info page at https://drupal.org/project/calendar_systems claims it has webforms support. 4th last item. So I suppose it does not only work for content types.


How to investigate arrayFlip errors in Commerce

BTW, I think you're mistaken, inline conditions isn't a core module. In fact looks like the latest version is 7.x-1.0-alpha7. Also, notice that these are warnings, not errors. It's likely that they won't effect a site set up with production error handling.

The way I've dealt with that is through debugging on copy of the site running in a local environment with xdebug. If you haven't set that up yet there are a bunch of ways you can do it, here's a few:

Here's a link for how to do it using Homebrew. That's my reply but read the others there, they've got good info.
you can sign up for a free account on Acquia and use their dev desktop software. Here's some info on doing that. (Seems like I'm plugging my own posts, but thats what I know.) I've gotten
There's a similar app from Kalamuna called Kalabox that specifically is set up to work with Pantheon, but I was able to get to work standalone. Let me know if you need help with this, I'll try to get time to put more details up.

Be ready to be frustrated getting a local environment with debugging up and running, it takes some doing, but it's well worth the effort.

Once you've got debugging happening, you can put a breakpoint on line line 353 of
/sites/all/modules/inline_conditions/inline_conditions.field.inc. If you can reproduce the error, then just hit continue until just before you expect the error to occur. (If you can't, you'll have to do this each time it breakpoint is reached.) From the breakpoint, you'll be able to look at the parameters that are referenced on that line and see what's expected to be an array that isn't. My setup using Netbeans allows me to hop to earlier parts of the code by checking the stack. This will allow you to see just where the parameter was originally set.

Sorry this isn't just an easy answer, but getting yourself set up will be worth it in the long run.


Print the node author's full name on a custom node template

Your question doesn't indicate whether you are storing the user's full name anywhere. You can add fields to the user profile (at /admin/config/people/accounts/fields). Suppose you add a firstname field (field_user_fname) and lastname field (field_user_lname), you could then write a custom function in your template file, like this:

function _get_author_name($uid) {
  $wrapper = entity_metadata_wrapper('user', $uid);
  $fname = $wrapper->field_user_fname->value();
  $lname = $wrapper->field_user_lname->value();
  return "$fname $lname";
}

And then, since you already know the UID, you could call the function from your content template:

    WRITTEN BY <a href="/user-posts/<?php print $uid; ?>">
    <?php print _get_author_name($uid); ?>

You could also investigate the Realname module.


How do I control user generated contents published state?

There is a module for that™: Workflow module!

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

In your case you only need to workflow states: review and approved/public.


Radio button & Option list values migrate successfully with Feeds Importer but disappear in node edit

I don't have enough reputation to comment, so I'm posting this as an answer.

I'd suggest that you install and enable the devel module to compare the data structure of the field in question in these three situations:

when the data is input manually
when the data is loaded via feeds
when the data loaded via feeds is later edited

If you haven't used it, with Devel installed, you can get the 'devel' view of the node.


To get rid of inactive users, have a look at the Inactive User module.

User Stats will keep track of the IP's used by the various users.

The Spambot module is quite effective at blocking bots which create the inactive accounts. If you can take the time, it will let you report and delete spam postings to help block future attempts.

However nothing will stop them. One of my sites just came under attack over the weekend. Over 600 new user registrations in less than 12 hours (at times 3 per minute). I checked the IP's and found that I had multiple accounts created from a few IP's (between 15 and 45 users from the same IP). Manually blocking the IP's involved at /admin/config/people/ip-blocking and deleting the accounts was the only way to stop the attack.

Good luck.


Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this?

I have the same problem, what i have dug up so far is that the "form" html tag goes missing when the view exposed filter form is rendered within a node form. I am still trying to fix the issue as i haven't figured out why. I will update you if i get any further on this.


Possible to use tags/buttons as exposed filters?

It sounds like you want to have something like this, what is provided by the Facet API module (Drupal 7) or Facets For Drupal 8.

Image copied from: https://www.webwash.net/drupal/tutorials/intro-search-api-part-2-faceted-search (explanation of Facet API combined with Search API).  It should however also work with the Drupal core search system. (I only used it with Search API)

  The Facet API module allows site builders to easily create and manage
  faceted search interfaces. In addition to the UI components that come
  out of the box, themers and module developers can build their own
  widgets that can optionally be contributed back to Drupal.org. Facet
  API works with the core Search, Search API, and Apache Solr Search
  Integration modules (including Acquia Search) meaning that code and
  configuration can be reused as-is with the most popular search
  solutions available to Drupal. Refer to the documentation for more
  details.

Each facet will be exposed as a block, that you can place anywhere in your site from the block administration page.


Can the speed of my cron job be improved?

Does cron speed depend on the server machine?

Yes, to an extent. Maybe even a large extent, it depends on a lot of different factors.

  Can I make it do this faster?

Probably, but that's as much as anyone can tell you from here. Profile the code, see where the bottlenecks are, and fix them. There's no magic formula


Set path for favicon.ico and apple-touch-icon.png

use a symlink, I typically keep my main favicon in my root theme folder, and then in the terminal navigate to the site root and symlink to that icon

ln -s PATH/TO/THEME/favicon.ico

it makes the most sense to me to keep my theme assets in my theme directory, but then I also like to have the same favicon accessible from the doc-root as well


If your field is a reference field like node reference or term reference, then you can add an image field in the referenced entity for associating the image. Then in your node tpl file, you can load the referenced entity and print the image. If you do not want to write a custom tpl, then this can be done using the Display Suite module. But unless you need Display Suite for other purposes, the tpl way is better.


how can i change the "Create new Account" to Custom registration

Fields module should be enabled with Field UI and other.
http://YOURSITE/admin/config/people/accounts/fields - add field, mark "Display on user registration form." on field editing form.


switching language requires users to login again

Check out the issue here for i18n.

It seems that the Single Sign-On module should help you out.

  This module enables 'single sign on' between multiple web sites that
  share common user tables (see http://drupal.org/node/2622#advanced).

  Single Sign-On (SSO) means that if you are logged onto the master
  site, you will automatically be logged into any slave site that you
  visit.

  SSO needs at least two Drupal sites running in order to use it (even
  if you are using Domain Access module!). One is called Controller,
  second (third and others) are called Clients. See README for more
  information about setting this up.

I'd think that as the issue in the queue states the cookies are stored per language.  This should be amendable in settings.php.


Which Drupal functions can be called in hook_requirements('install')?

I've made severals tests and I found that depending on modules that you've installed or other things the list of available functions is quite different.

So, IMHO the best way to see which functions you can access at that moment its to list them with the PHP function get_defined_functions. Below it's the small code that I used to list all the functions you can use.

<?php
if ($phase == 'install') {
  $funcs = get_defined_functions();
  file_put_contents('./functions.txt', var_export($funcs['user'], 1));
}


Is there a way to trace PHP errors logged from Rules?

If Xdebug is installed in the machine, it dumps a stack trace to your Apache logs. That might give you a better hint at the context.

If that fails, look at all your Commerce rules and try to find the one with a execute PHP action.


Migrating sha1 user passwords into drupal 7

You can use the Migrate framework and easily import accounts into Drupal 7 and it will take care of this for you. Don't bother with separate tables and password lookups and all that.

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

https://www.jeffgeerling.com/blogs/jeff-geerling/migrating-drupal-7-users-site

I can't find an actual example of a class that handles users into Drupal 7,
but the Migrate docs are very thorough.

Edit - here is an example: https://cgit.drupalcode.org/migrate/tree/migrate_example/beer.inc#n212

But in your case you will want to define another database connection in settings.php and define that as the source of the migration.


drush make build script tries to download project itself from drupal.org

seems there were some wrong cached files.

I removed all ~/.drushrc/cache/git and downloads


Include content created through InDesign/RoboHelp

Looks like the correct term is HTML or static microsite. These can be managed via .htaccess as seen in Maintaining a static microsite alongside Drupal's docroot.


How do I add an additional sidebar to a Zen sub-theme?

You can do it with preprocess function at template.php template. I will write you just one example, and you can adapt it for your needs.

1.At Your template.php template.

function yourthemename_preprocess_page(&$vars, $hook) {
  $page = $vars['page'];
// if only left sidebar is present
  if ($page['left_sidebar'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforcontentwithsidebar');
    $vars['class_left_sidebar'] = t('yourclassforleftsidebar');
 }
// if no sidebar is present
  if (!$page['sidebar_left'] && !$page['left_sidebar2'] && !$page['right_sidebar']) {
    $vars['class_content'] = t('yourclassforfullwidhtcontent');
 }
}

You can find more variations here: php logical operators.

2.At your page.tpl.php, at all regions where you want flexible width, put extra class, for example for left sidebar:

   <?php if ($page['left_sidebar']): ?>
      <div id="left_sidebar" class="sidebar <?php print ($class_left_sidebar);?>" >
        <?php print render($page['left_sidebar']); ?>
      </div>
    <?php endif; ?>


Drupal Commerce payment  methods can usually be found at      /admin/commerce/config/payment-methods. They are rules in fact. If for any reason that menu doesn't exist, check your rules.

To get that menu you need ro enable Payment UI module.

You also need to properly enable and setup your checkout panes at admin/commerce/config/checkout


I found this solution:

        $('#main-stuff').append('

').css("cursor","pointer");
        $('#bgImgOverlay').click(function() {
            $("a[rel='gallery-all']").colorbox({open:true});
         });


Location Module fields are not available under Search api fields

As pointed out here, you can achieve that by means of a combination of modules:

Search API Location + Search API Solr + Location field (creating an aggregated location field).

You will need an extra step by implementing hook_search_api_solr_documents_alter() because the longitude and latitude need to be indexed with the right format.


How to get Q & A of a webform submission?

Try below code:

module_load_include('inc','webform','includes/webform.submissions');
$sid = 10; //Replace this value with your dynamic sid value
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;

$web_submission = webform_get_submission($nid, $sid);
$node = node_load($nid);
$output = webform_submission_render($node, $web_submission, NULL, 'html');

print $output;


How to hide label in customized contact form?

The Display settings are for the message that is sent.  Setting label visibility in this section would impact how it appears in the email body.

The Manage Form Display are the settings for the form - unfortunately there are no options for label display.  You can alter the form by implementing hook_form_alter() https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!form.api.php/function/hook_form_alter/8.2.x  OR if you just want to hide that label you could do it with CSS in your theme, a simple display: none; should work.


What is the right way to get number of items from a field?

Using count() on a field is acceptable because there is an implementation of Countable::count in the ListInterface implemented by ItemList class where it overloads the count method to count the items, from which FieldItemList and EntityReferenceFieldItemList inherit.

So you can use:

$paragraph->field_events->count()

or

count($paragraph->field_events)

synonymously.  They do the same thing.

From ItemList.php:

public function count() {
  return count($this->list);
}

If you'd like test this, you can play with this simple class.  If you remove the "Implements Countable" calling count(a) on object a doesn't return the count() method, but if you add it back, it does.  So on a low level, Drupal is using this so you can call count() on fields.


Editing a single field on a rendered node

Use whatever works for you. I've used the below modules to achieve this type of functionality before.

Look at Field Permissions:

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

And look at Editable Fields to easily edit a field when not on the edit page:

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

Or maybe Editable Views, modules:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.


While tracking the above issue is good for long-term success... if you need this functionality ASAP, here's a tiny bit of a hack to get it working with some custom javascript. Inside your theme's JS, add something like the following:

// Autosubmit 'view-class-here' views exposed form.
$("div.view-class-here").find("form.views-exposed-form").find("select").bind("change", function () {
  $(this).closest("form").trigger("submit");
}).end().find("input[type='submit']").addClass("visually-hidden");

This will do the following:

Look at any select item in a given views exposed form (for a view with a class .view-class-here), and trigger a submit whenever the select list is changed.
Hide the 'Submit'/'Apply' button associated with the exposed form.

If you want to trigger the submit on input fields, change the .bind() to use something like input:checkbox or input for any kind of input (though that might need more tweaking to make sure things don't go crazy!).


Assuming Drupal 7 here, which thankfully has more options for you that Drupal 6.

I don't recall the last time I fully traced this out (and it's complicated), but search_excerpt does call strip_tags and check_plain.

You can take a look at search-result.tpl.php, template_preprocess_search_result(), hook_node_search_result() to see what your options are.

Personally, I would build up my own entries in $variables in the preprocess, and display them in the template.  One option is to make a custom node view for the search results, uild it up with the UI, and then use this,something like:

function mytheme_preprocess_search_result (&$variables)
{
  $result = $variables['result'];
  $node = $result['node']; // not 100% positive that this is the right place in D7
  $variables['my_custom_search_result_view'] = node_view($node,
    'my_custom_search_result_view');
}

and then use $my_custom_search_result_view in search-result.tpl.php.

Not a full solution for you, but it should be a decent start.


Export set variables from site to include in install profile

A year or so ago I was working on a Drush command to export a working site as an installation profile. I haven't worked on it for a while, but it was my intention to use something like the Configuration Management module, or perhaps Drush CTools Export Bonus to include site configuration information with the installation profile.

If you are hand-generating your installation profile, typically you do write variable_set commands and put them directly into your installation profile.  When generating configuration information, though, I think it is typically the case that the config information is bundled in some other module.

Answering first question

By convention, variables in the variables table are  named after the module that defined them, so if everyone is cooperating, you know where the variables are coming from.  Install a fresh copy of Drupal, and make note of the variables that it defines, and their default values.  Compare these against the values in your site to find the ones you have changed.  Do the same thing for contrib modules, installing each module in your scratch site, and checking the default values.  Another option is to use Strongarm, which will show you the variables that changed (when they change), just like other features modules do.

The catch here, though, is that not all configuration is stored in the variables table.  Some modules define their own tables.  If you want to hand-code your configuration, you need to investigate the APIs for each module you use in turn, and figure out how to make settings programatically.  This is a difficult thing to do, which is why most people use features, or the configuration management module, or Ctools export bonus.  Even these modules are not always enough, as not everything supports exportables. It's a good thing that the CM initiative in D8 is addressing this problem.


Form validator and submit handler is not getting called

I think you should have an element of type submit in your form function.


In drupal 6, table will have sticky header by default. I did not see this because my table has few rows and my site has not any scroll :). its described on API: theme_table


How to provide option to select geographic part for content

Try the Location module. It will help  you to attach location info with nodes. More details from the module's project page:

  The Location module allows real-world geographic locations to be associated with Drupal nodes, including people, places, and other content. The Location module allows admins to collect addresses, geocode them (translate addresses to lattitude/longitude), and associate locations with Drupal nodes and users. Location data is automatically used to generate GeoRSS within your existing RSS feeds.


A block array has a 'subject' and 'content' key, it's just a convention. See hook_block_view() for details:

  Return value

  Either an empty array so the block will not be shown or an array containing the following elements:

  subject: The default localized title of the block. If the block does not have a default title, this should be set to NULL.
  content: The content of the block's body. This may be a renderable array (preferable) or a string containing rendered HTML content. If the content is empty the block will not be shown.


How to Create a Table of PDFs with Views?

Generally there would be two steps to this in Drupal 7.

Create a content type with the fields you need
Create a view to pull in that content

In your content type settings, manage the fields, and you can add a file attachment field (for uploading the PDF) and a text field for entering the job title. Date of upload is automatically created in the sense that your HR people will create a new piece of content (of this new type) when they want to upload a new job opening, and you can use that piece of content's date last edited data for that field. You can enable display of that info in the view settings under Fields.

Once you get your view correctly displaying all the content from your new content type, you can work on styling it as a table with CSS.


Clean URL in Exposed Filters in Drupal 7

You will probably have to split this off into two different views displays, one for the clean URL with contextual filters and one using the exposed filters.

The only other way I can think of is making the contextual filters optional, but that may not be possible.


How can I pass the loop.index from a view template to a node template?

This can be done using the preprocess function in my_theme.theme.  In the case above, the row was formatted in node--view--pagename.html.twig, so the preprocessor function name is mytheme_preprocess_node__view__pagename.  In the function, the view is iterated until the node matches the current node that is being processed, at that point, the row_index is determined and set and accessible in node--view--pagename.html.twig as {{ row_index }}.

function fu_preprocess_node__view__pagename(&$vars) {
    $view = $vars['view'];
    $node = $vars['node'];
    foreach($view->result as $key => $row){
        if($row->nid == $node->id()){
            $vars['row_index'] = $row->index;
        }
    }
}


Like Berdir mentioned in the comments and Greg mentioned in his answer, the following methods of adding path aliases should Just Work™:

Adding it on the node submission form during node creation/editing
Using Pathauto to automatically create aliases for nodes.
Adding aliases manually by going to Configuration → Search and metadata → URL aliases

That it's not doing that is weird. Try clearing your cache by going to Configuration → Development → Performance. This should rebuild Drupal's menus and get the path aliases to show correctly.


What's the correct format for submitting a null value to an integer field using metadata wrapper?

Have you tried to check if the value exists before setting it?

//.... (other fields in the form are here)
if (!empty($form_state['values']['field_salary'])) {
  $ewrapper->field_salary->set($form_state['values']['field_salary']);
}

This way you're not touching the value if it's not set.


Rules Redirect User at Login by Role to URL not working

Here is a working rule to redirect users to different URL's depending on user role, you will need Rules conditional module
to acomplish task, enjoy.

{ "rules_user_has_logged_in" : {
"LABEL" : "user has logged in, redirect based on role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "redirect" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "user_login" : [] },
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "6" : "6" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "5" : "5" } } } },
        "DO" : [ { "redirect" : { "url" : "pagos" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas" } } ]
      },
      {
        "ELSE IF" : { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "12" : "12" } } } },
        "DO" : [ { "redirect" : { "url" : "polizas\/todas", "destination" : "1" } } ]
      }
    ]
  }
]

}
}

and an img to see how my rule looks.


The solution is to use the hook_preprocess_page().

function my_module_preprocess_page() {

    // redirect drupal edit page to our own module edit page.
    if (preg_match('/^node\/(\d+)\/edit$/', current_path(), $matches)) {
      $code = _my_module_check_code($matches[1]); //check if the nid is of the content type we need
      if ($code) {
        global $base_url;
        $url = $base_url.'/my_module/'.$code.'/edit';
        header('Location: ' . $url);
      }
      // If the code is not from the content type we need, we do nothing
      // just leave drupal work it's way
    }

}

After clearing cache, all is working fine.


How to get block instance id in block plugin?

No there isn't.

Block plugins can also be used in e.g. page manager and then there's no block entity, it stores configurations for multiple block plugins in a single config entity.

So you shouldn't be relying on the existence of that and instead pass in the relevant configuration to your lazy builder.


Variables to theme functions must be named:

print theme('table', array('rows' => $rows));

See the documentation for more details.


Keep in mind Drupal 7 has a built in library for working with archive files.

Archiver Zip

See also system.archiver.inc

Perhaps you'll have more success using that.

Lastly, make sure the path to the uploaded file is correct for extraction.


Include View In Node That References Other Nodes Based On Joined Field

Create a View to show nodes of Content Type B, add a Contextual Filter for your field My List and save the view.

Install the Views Field View module and then in the Footer region of your View of Content Type A add the  Global: View (Views field view) and configure under the View settings the Name and Display of your B View and the token for the Contextual filters.

To use the value of the My List field as a token, you must have in the Fields of your view this field selected.

Edit after your comment ("I'd prefer to keep using the regular node page.")

You can use the EVA module, it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity, in your case the node of Type A. In the contextual filter of the view you need select the My List field in the Entity Content Settings of the View using a token.

"Entity Views Attach: Use Views Almost Anywhere" contains a great tutorial about it.


How to change theme colors based on time of day for Adaptivetheme (or other theme that allows user-selectable colors)?

Place the following code into your theme's template.php file.

/**
* Implements template_preprocess_html().
*/
function YOUR_THEME_preprocess_html(&$vars) {
  // Day / night background theming.
  $hour = date('G');
  $theme = 'day';
  if ($hour <= 6) {
    $theme = 'night';
  }
  elseif ($hour >= 6 && $hour <= 18) {
    $theme = 'day';
  }
  elseif ($hour >= 18) {
    $theme = 'night';
  }
  $vars['classes_array'][] = $theme;
}

Now your <body> tag should have the CSS class 'day' or 'night' depending on the current server time.

An example CSS code would look like:

body.day {
  background: #fff;
  color: #000;
}
body.night {
  background: #000;
  color: #fff;
}

for more info check this tutorial.


Adding another date using the date repeat API

If you select the repeat option in the field configuration, the Date module then declares to the Field API that it handles multiple values. There is a lot of discussion about it on drupal.org but sadly no patches for Drupal 7.


Contrib statistics: Reported installs and downloads

This is simply due to a bug with the statistics module - see Project Download count Decreased - that has affected Drupal.org infrastructure since the middle of April 2015.

Prior to that bug surfacing, I did not observe a single project where the number of downloads were less than the number of installs.

Just now CKeditor Link is reported to have 487 downloads.  That is 171 less than the 658 reported by the OP in the question (asked two days ago).

Until this bug is fixed, the download statistics should just be regarded as a random number.

As reported by Pierre.Vriens, another bug sometimes affect the installed statistic on the Drupal.org.  This affected many projects a couple of days ago, but seems to have been fixed for most of them today.


Shared Drupal 7 core and shared contrib libraries & modules

You can symlink the same core into several drupal installs. This works cross vhost.
You can also run several sites on the same Drupal Core in a multi-site fashion. This however requires you to keep a single vhost, so you need to restructure the server config for this.

Note that I recommend against clustering to many sites. If you break a single core, you break all of them. So you would do well to run, say 5, sites per core. Obviously the number should be adjusted depending on how much resources they require and how many sites you run in total.


How to make 2 Rules work that use the very same Rules Event?

2 separate Rules using the same "after update something" event, that's asking for problems.
You should try to rework/redesign those 2 rules somehow. Here are a few ways to do so:

If both rules don't have any Rules Conditions, then move all the Rules Actions of 1 rule to the other rule (and think of the best "order" to execute all Rules Actions).

If Rule 1 has a Rules Condition (say) "Condition1" and Rules Action (say) Action1, and Rule 2 has a Rules Condition (say) "Condition2" and Rules Action (say) Action2, then use the Conditional Rules module to merge both rules together (also), with a Rules Action (not Rules condition!) that looks like so:

Conditional
If Condition 1 then Action 1
Conditional
If Condition 2 then Action 2

Note: if appropriate, first perform anything related to Rule 2, then Rule 1


url() not providing links to correct language alias using i18n in D7

Use l() function to generate a link.

  Formats an internal or external URL link as an HTML anchor tag.

  This function correctly handles aliased paths and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.


Error message "responsive-utilities.less" not found

Found the issue, actually it was my fault, I missed to paste the Bootstrap source file in the sub-theme folder. Because responsive-utilities.less is coming from /bootstrap/less/responsive-utilities.less as you can see in error message. Hence, previously bootstrap was missing, so this was error did appear.


Add the pager to the build array in which you return the results:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
    ],
    'pager' => [
      '#type' => 'pager',
    ],
  ];

Or extend the theme with a variable #pager if you want to theme this in one place:

  return [
    'results' => [
      '#theme' => 'mytheme_news_archive',
      '#items' => $nodes,
      '#path'  => $path,
      '#pager' => [
        '#type' => 'pager',
      ],
    ],
  ];

Then you can print the pager in twig:

{{ pager }}


Does Entity Translation hijack i18n's operations?

It's not that difficult or complicated, you just need to know what to do, where and using what. Have a look at Drupal 7 Multilingual Sites book, it has pretty good explanation of the whole process. Essentially, yes, Entity Translation plus i18n modules would take care of most of the things for you.


How can I alter (theme) the default content feed?

The best way to do this if you're running stock D7 is in config: you'll want to change the default field dislpay settings by clicking "manage display" on the Article content type in admin/structure/type.

Click the gear icon to adjust the display type:


Add product image to drupal commerce cart form

This can be accomplished from the front end by simply editing your commerce_cart_form view and using relationships to "relate" your way backwards from the order item to the product display.
Edit your cart form view and click Advanced on the right side of the screen. Then under Relationships click "Add" then add and apply the following relationships in this order.

Product variation - Order item - "The purchased product variation."
This will give access to add any of the fields under the Product Variation you are relating. it will also give you access to add the product type relationship in step 2.

Product - Product variation - "The parent product." This will give access to add any of the fields that you have in the Product Type you are relating, (including the image field from your product display). This will also give you access to add a content relationship as seen in step 3.

Once you have added those relationships, you will be able to access and add any of the fields you want from both the product variation, and the product type under Fields.
If you are displaying with nodes and/or need fields that are in content types that have product references, you will also need to add the following relationship:

Content using field_YOUR_PRODUCT_REFERENCE - Product - "Relate each Content with a field_YOUR_PRODUCT_REFERENCE set to the product." This will bring in all the fields for the display node.
No custom code required. :)


Programatically redirect to node/nid doesn't redirect to url alias

Try using Url.

$url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
new RedirectResponse($url->toString());


Wrapping a rendered file from Media with a link

OK, here is the working code.

The Media module implements hook_file_formatter_info() to set up a callback for rendering images.

As is the Drupal way there is a hook_file_formatter_info_alter() to change the default behavior.  So, I took the default callback from file_entity.module and cloned it into a custom module.  I then wired this up with the alter.  My custom callback has some additional logic to check for an image style, and then wrap the element with a link.

The only real quirk is that the default implementation of theme_link() assumes it is a leaf element, so you need to render out the image element first.

As a side note, this is also how you would get alt/title text onto the images, which is missing by default.

function MYMODULE_file_formatter_info_alter(&$info) {
  if (!empty($info['file_image'])) {
    $info['file_image']['view callback'] = 'MYMODULE_file_formatter_file_image_view';
  }
}

function MYMODULE_file_formatter_file_image_view($file, $display, $langcode) {
  // Prevent PHP notices when trying to read empty files.
  // @see http://drupal.org/node/681042
  if (!$file->filesize) {
    return;
  }

  // Do not bother proceeding if this file does not have an image mime type.
  if (strpos($file->filemime, 'image/') !== 0) {
    return;
  }

  if (file_entity_file_is_local($file) && $image = image_load($file->uri)) {
    if (!empty($display['settings']['image_style'])) {
      $element = array(
        '#theme' => 'image_style',
        '#style_name' => $display['settings']['image_style'],
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
      if ($display['settings']['image_style'] == 'MYSTYLE') {
        $element = array(
          '#theme' => 'link',
          '#text' => drupal_render($element),
          '#path' => 'media/' . $file->fid,
          '#options' => array(
            'attributes' => array(),
            'html' => TRUE,
          ),
        );
      }
      else {
      }
    }
    else {
      $element = array(
        '#theme' => 'image',
        '#path' => $file->uri,
        '#width' => $image->info['width'],
        '#height' => $image->info['height'],
      );
    }
    return $element;
  }
}


CSS should be manipulated using hook_css_alter(), not in an HTML preprocess (where it's too late).

function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}


Correct format of data to send at services endpoint to create node

In the html code of node add form as provided by you, title field has name "title_field[und][0][value]". You have to use exactly this name/key in your POST request. Along with that, you also need to send a value with name/key "title". Both needs to be sent. However the value of "title_field[und][0][value]" will be filled as title in the created node.


What you obtain from that code is exactly what you should obtain.

The values you are getting from that control statement are:

$form['tid']['#options']['All'] is a string, and not an object. Trying to access $form['tid']['#options']['All']->option gives you a warning about accessing a property for something that is not an object.
$form['tid']['#options'][0] is an object, and it doesn't raise an error, but $form['tid']['#options'][0]->option is an array, and print $form['tid']['#options'][0]->option converts it in a string. That is why you see Array.
The same is true for $form['tid']['#options'][1].

To remove the array element that contains 'Age 12 - 14' from $form['tid']['#options'], I would use the following code.

foreach ($form['tid']['#options'] as $index => $tid) {
  if (is_object($tid) && !empty($tid->option) && is_array($tid->option) && in_array('Ages 12-14', $tid->option)) {
    unset($form['tid']['#options'][$index]);
  }
}

Notice that in_array() is case-sensitive. If you are searching for 'Age 12 - 14', but the string is 'age 12 - 14', the code doesn't remove the option.


As stated in my comment above, the issue is with pathauto and not with nodesymlinks.

Basically, pathauto is replacing the standard [node:menu-link:parent:url:path] or your [nodesymlink:menu-link:parent:url:path] with the <front> slug instead of just removing it when the parent menu item is the front page.

I have been looking into a fix and couldn't find any. This is why I wrote a custom module to remove the front slug from the paths generated by pathauto. I'm including the link to future proof the answer in case the post gets updated and I'll also copy/paste the full code at the end of this answer.

Also, if you're a beginner, follow the link for more info on how to create a custom module in Drupal 7 and the like. Otherwise, just drop this code into your custom module and it should fix the situation you're describing. The function's code is well commented in case you need extra info.

Good luck.

<?php

/**
 * Implements hook_pathauto_alias_alter().
 *
 * Needed so that we remove the buggy slug <front> from paths when their
 * nodes are a sub-menu-item of the front page while using this pathauto
 * pattern: [node:menu-link:parent:url:path]/[node:title]
 *
 * If the parent is the homepage, all menu child entries will get <front>
 * added to the beginning of their URL alias which looks really ugly and
 * doesn't work on all operating systems. We need to remove it.
 *
 * Pathauto 7.x-1.2 doesn't handle this properly. Maybe later versions will.
 */
function yourmodule_pathauto_alias_alter(&$alias, array &$context) {
    //Init the slashed front slug value
    $front_slug_slashed = '<front>/';

    //If the alias contains the slashed front slug, remove it
    //Note that pathauto will later check if the generated slug is a duplicate
    //and append an incrementing number to it so no need to worry about this
    if(strpos($alias, $front_slug_slashed) !== false) {
        //Save the non-modified alias for logging
        //Note: no better way to clone a string in PHP?
        $original_alias = $alias . '';

        //Remove the front slug from within the alias
        $alias = str_replace($front_slug_slashed, '', $alias);

        //Log to Drupal's watchdog as notice
        $msg = '';
        $msg .= 'Altered pathauto alias from "' . check_plain($original_alias);
        $msg .= '" to "' . check_plain($alias) . '"';
        watchdog('sk', $msg, array(), WATCHDOG_NOTICE);
    }
}


Insert bank detail in email if the user choose to pay with bank transfer

I solve with this code:

<?php
$payment_method = commerce_payment_method_instance_load($commerce_order->data['payment_method']);
echo commerce_bank_transfer_bank_details($commerce_order->order_id, $payment_method);
?>

commerce_payment_method_instance_load() function need in input a string like

'bank_transfer|commerce_payment_bank_transfer'

and it returns a paymente method with all data [ setting included ]


hook_form_alter() exposed filter form item #weight

Take a look at comments #3, #7 and #9  in http://drupal.org/node/893392

#3 (dereine):

  The problem is that there is some theming on exposed form. You would have to override it, sadly.

#7 (manatwo):

  Yes, all of it is handled in views-exposed-form.tpl.php, which you can override in your theme to print out your fields manually. IIRC, the extra fields are gonna be in the $button variable in that template, so you might want to do some preprocessing in template.php

#9 (PadreHomer):

  I was able to alter the order without overriding the template. I am using Views 3, but I think this will work in Views 2 as well.

  Alter the order of the filters in $form['#info'] in your form_alter and this should alter the order the widgets print out in the template without having to do any custom templating.


Content type node not overwriting the default node.tpl.php even if I have cleared all cache's

Initially, i say like not to override the original theme folder,

Create a sub theme of the base theme, in your case create a sub-theme of twitter bootstrap.
Then make the necessary changes in the sub-theme.

Enable only the sub theme.

And about overriding node.tpl.php file,
your approach is correct node--empresas.tpl.php, should over-ride the display of this particular node content.

Cross check machine name, Enabled theme, path of the overriding tpl.php file.


Yes in the stock module is a function for set stock level and you also need a custom xml-rpc client/server functions for both instances.


How can I give Ajax access to currently set fields on my form?

I have tried this on my local it works . So you can achieve the form values by using this . Please try this

    $form['filter_field'] = [
      '#title' => $this->t('Filter'),
      '#type' => 'select',
      '#options' => ['drupal7' => 'Drupal7', 'drupal8' => 'Drupal8'],
      '#empty_option' => $this->t('-select'),
      '#ajax' => [
        'callback' => '::updateWidgetAjax',
        'wrapper' => 'default-value-ajax-wrapper',
      ],
    ];
    $form['widget_type'] = [
      '#title' => $this->t('Widget Type'),
      '#type' => 'select',
      '#options' => ['pdf' => 'Pdf', 'ppt' => 'PPT'],
      '#empty_option' => $this->t('-select'),
    ];

    $form['wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'default-value-ajax-wrapper'],
    ];

    return $form;

//Ajax callback
  public function updateWidgetAjax(array &$form, FormStateInterface $form_state) {
   $widget = $form_state->getValue('widget_type');
    print_r($widget); //Print the value of the field
  }


Give a specific user role the ability to give a user a role but not the 'administrator' role

There is a perfect module for you - Role Delegation - and there is a stable 7.x release as well. Here is an excerpt about it from the module's project page:

... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.


How do I insert a   tag outside the   tag on my main menu

If you want your menu link to be like this
Link 1Description
, ie., the description is outside the  tags, then try the code below.

function motg_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $description = '' . $element['#localized_options']['attributes']['title'] . '';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . $description."
\n";
}

The reason your code didn't work was, you used the description tag within the l() function. In drupal the l() function always renders an  tag and so the description was inside the  tag.


Adding links on top of view rotating banner

Add a "Global: Text area" to the header of your view that includes the link. This way it will always appear.


How do I customize an article URL alias?

There are so many module for this you can check

Pathauto

Path redirect

Global Redirect


Drupal and Git workflow using Acquia cloud

Disclaimer: I work for Acquia

This library article you linked to originates from an blog post that was written 4 years ago to answer questions about deploying from Jenkins build servers, private Github repos, etc. There's nothing specific to Acquia Cloud per se and it's rather a Git strategy you need to come up with for your development needs.

Is the Bonobo Git Server going to be the 'origin' going forward?

If yes, then simply add the Acquia Cloud as a new remote (e.g. 'ac').
Git allows you to push to different remotes without any issue.
If not, then you should make Acquia Cloud the 'origin' and Bonobo a
regular remote (probably easier).

Since Git is decentralized, you 'own' the repo at any point in time and the main reason for keeping a remote is if you have a continuous integration system you need to pass your codebase through before you deploy code to Acquia Cloud. Another good reason is if you have a preferred Git workflow (think Github pull requests for instance) you wish to continue working with. But if you simply want to mirror your Acquia Cloud repo to (for instance) back it up, then I'd argue to just keep the Acquia Cloud repo and simplify your workflow.

The idea to keep in mind is you need only one checkout of your codebase. Having several remotes allows you to handle where to push to as described in the article.


Nested Image/Video Galleries in Drupal 7

The trick is information architecture. I suggest you use the book module to define the hierarchy. This is an underestimated core module, which works amazingly well and has good integration with Drupal. In a recent site I've architected, all the site navigation was built dynamically using views, book-related contextual filters, and the viewfield module (which allows to put a view inside view). Play with the setup below and enjoy!

Detailed instructions:

Enable the book module.
Define top galleries as toplevel books, without a parent:

Go to the node editing screen.
Click on the new 'Outline' toplevel tab created by the book module.
Click on the 'Add to book outline' button. This will create a new book.

For each child gallery, select it's parent gallery

The parent gallery may be one of the toplevel galleries created on the previous steps, or one of the previous child galleries created on this step.
The child gallery may either be selected on the on the 'Outline' tab (when editing existing nodes) or on the 'Book Outline' vertical tab  displayed below (when creating new nodes).

Create a new view, which will show your toplevel galleies. let's call it "top galleries"

Open a 'block' display
Make the view field-based.
Add the title field to show the gallery title.
Add a viewfield to show the sub-galleries of this book.
The viewfield will refer to a new view we will create in the next step.
And, most imprtantly, use a filter criteria of Book: Depth (=1)

Create a "gallery-inner" view.

Open the 'Advanced' setting
Create a relationship from the node to Book: Parent - the parent book node.
Set a contextual filter to "Content: Nid" taken from the parent book node.
Now the view show all children of it's parent book.
I haven't tried it but you may also try to add another viewfield here to show the children of those child views recursively, until there is a level with no more children (if it doesn't work, then create anorhter  "gallery-grandchildren" view for the 3rd level. Please report back here and write which way succeeds.

Notes:
- The screenshots were taken from a similar solution, where I've implemented all of the site navigation menus using the book hierarchy defined by the user. So please add an image field to each view where appropriate.


Allow user to use entity reference to nodes they own?

You can do it this way.

Create a view to list the nodes of particular type.

1a. Add a contextual filter of Content: Author Uid and provide default values as USER ID from logged in user

1b. Add a Entity Reference display to the view.
Now go to the Entity Reference field you have created in your content type and edit it.

2a. Under Entity selection select the Mode to Views: Filter by an entity reference view then you will get the view you have created above and select it.

2b. Save the changes.

This way the user will see only the node they created in the reference field. Read More

There is a second way also, you can implement hook_query_entityreference_alter() and alter the query. Read More


Send email when entity field value is changed

Yes, you can use Rules to achieve this.

Here's how:

Create new rule that will react on "After updating existing content" event.
Use the following conditions: data comparison: node:field-your-field and node-unchanged:field-your-field and select "Negate: FALSE"
Create whichever actions you want, e.g. send mail, show message, etc.


Programmatically render HTML in taxonomy term description

The taxonomy_term_data table, which is the entity table for taxonomy terms, has a format column which stores the name of a filter to apply to the description when rendered.

It's available as a property on the entity, so you can use:

taxonomy_term_save((object)array(
  'name' => $name,
  'description' => $t('
My description.

More info.
'),
  'vid' => $vocab->vid,
  'format' => 'full_html',
));


It won't work, if you give same path for different views/displays then it will load the view/display with the least id.

But why you want to give same path for all views?


redirecting midway out of a webform wizard

The logout is probably losing the user's session with the $form_state

A very simple solution is to redirect the form to /user/logout?destination=REDIRCT_PATH.


Form select type: setting default based on options' value

Default value should point to key, not a value.

In your example, default_value should be as in below.

'#default_value' => 3,

Hope below link will help you.

https://www.drupal.org/node/240783#comment-1794710


How to uninstall one site of a multi-site?

Nothing to it as long as they have separate databases:

Deactivate the virtualhost pointing at your site and restart apache
Backup and delete the database for that site
Backup and delete the site folder inside Drupal_root/sites where Drupal_root is your core Drupal repository

Then rebuild however you please.


Re-creating complex CSS footer layout in Drupal

I'd set up one region for those menus, in that region have 3 x menu blocks (http://drupal.org/project/menu_block), 1) Who Are You, 2) Quicklinks 3) Admissions.

CSS will be your friend to get the required layouts.

The "Who Are You" menu should be easy, float the menu block left and fix the width. The same for the "Admissions" menu.

The middle menu will be similar but all you need to do is have a wider fixed width menu block, fix the width of the menu items and float them left. Then you'll have to order the menu items to make them appear in the correct columns.

The text below the menus should simply be 2-3 more standard text blocks just styled appropriately.

I hope this makes sense. I'll be interested to see how other developers would attack this.

Cheers.


How do I correctly implement hook_bootstrap_colorize_text() to alter button colors in a Bootstrap sub-theme?

Well, I really thought I had tried everything before posting. I didn't think I'd be answering my own question, but I'll put it up here in the case it is helpful to others. Here is what eventually worked for me:

<?php
  //Implements hook_bootstrap_colorize_text_alter() to alter Bootstrap button colors.
  function methodstheme_bootstrap_colorize_text_alter(&$texts) {
    $texts['matches'][t('Request Rotation')] = 'success';
    $texts['contains'][t('Notify')] = 'success';
    $texts['contains'][t('Set')] = 'success';
    $texts['contains'][t('Mark')] = 'success';
    $texts['contains'][t('Assign')] = 'success';
    $texts['contains'][t('Report')] = 'warning';
    $texts['contains'][t('Request')] = 'info';
  }
?>

I had tried this earlier, and had no result after clearing caches. I had tried  placing the template.php file in my sites/all/themes/methodstheme/templates folder as well as the sites/all/themes/methodstheme (not the templates sub-folder) folder.

Regardless of the folder I placed it in, it was still not working - I had no result after clearing the caches initially.

Placing the file in the sites/all/themes/methodstheme (not the templates sub-folder) folder was part of the solution. I had brushed up on the Bootstrap Starterkit file structure, and I was fairly certain the template.php file should not be in the templates sub-folder, so I started trying other things. Using Drush I cleared the theme-registry cache, the theme list cache, then cleared all caches. I cleared those caches again a second time, and viola! My site is now functioning as expected.

Lesson learned - clearing caches multiple times is sometimes necessary/helpful!


Is there a flag hook (flag module) which is called when a flagged node is saved?

Is there an hook called when a flagged node is saved ?

No

However, you can use hook_node_update to trigger on a regular node save and check users who have flagged the current node ID.

You can also do most of the work without any coding using Rules, Views, Views Bulk Operations and obviously, Flag module.


How to delete field programmitically using hook_update?

We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Not quite - each instance exists in its own right, unaffected by any other instance of the same field on another entity type/bundle. Removing it from one bundle (content type) won't touch it on another bundle, regardless of which one it was originally attached to.

You won't need hook_field_delete_instance() for this, just a combination of field_info_instance() and field_delete_instance() in an update hook. Something like this:

/**
 * Remove old fields from the Basic Page content type.
 */
function MYMODULE_update_7100() {
  $field_art_image = field_info_instance('node', 'field_art_image', 'page');
  field_delete_instance($field_art_image);

  $field_art_country_tag = field_info_instance('node', 'field_art_country_tag', 'page');
  field_delete_instance($field_art_country_tag);

  return 'Fields deleted, data will be cleared up on cron.';
}


How to make specific field disabled on node submit, but enabled on node edit?

you can solve this problem in different ways.

The first is quite easy: you can show/hide the fields from CSS.

When you create a node, the default body classes contain this CSS class: "page-node-add". Instead when you edit a node you'll have the class "page-node-edit".

So you can add this CSS code:

.page-node-add .field_two{ display:none }
.page-node-edit .field_one{ display:none }

This solution is not elegant and it could be a potential security hole.

A better solution is to implement hook_form_alter() from your theme or from a custom module.

The code could be something like:

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'testtype_node_form' && arg(1) == 'add' ) {
    $form['field_two']['#access'] = 0;
  }
  if ($form_id == 'testtype_node_form' && arg(2) == 'edit' ) {
    $form['field_one']['#access'] = 0;
  }
}

Good work!


How to perform an operation every time a node is viewed?

You can use hook_nodeapi() in Drupal 6 and check that the $op argument is 'view'. In Drupal 7, this has been changed to hook_node_$op() where $op is replaced by the value you would have checked for in the Drupal 6 version. So you would use hook_node_view(). For more details about the changes from Drupal 6 to Drupal 7 see http://drupal.org/update/modules/6/7#remove_op.


How to create multi select list programmatically

In your submit handler add something like this:

$selected_countries = array_filter($form_state['values']['country']);

$selected_countries will contain the array keys of all the selected items in your Country select list. You need the array_filter to get rid of unselected items, which also come through to the submit handler but with a value of 0.


D7 you can try function drupal_add_js

function hook_preprocess_node(&$vars){
  drupal_add_js(drupal_get_path('theme', 'your_theme') . '/js/my_script.js');
}

D8 You need define one or more (asset) libraries, add a *.libraries.yml file to the root of your theme folder

library_name:
  version: 1.x
  js:
    js/my_script.js: {}

Attaching a library in a preprocess function

function hook_preprocess_node(&$variables){
  $variables['#attached']['library'][] =  'your_theme/library_name';
}


Why won't my images appear inside buttons?

I'd strongly advise to use CSS for this, it's much more easier to apply and you won't hit path related issues.


Handling of "Clean URLs" has changed from Drupal 6 to Drupal 7 in a way that affects Apache RewriteRule.

I'm not sure if that is what has bitten you since I don't recognise home/software?code=$1 as a typical Drupal URL. But I've found that in Drupal 7 I need to rewrite to a "unclean" URL.

For instance, the following will work in Drupal 6, but not in Drupal 7:

RewriteRule ^home/code/([^/]+) home/software/node?code=$1

In Drupal 7 you must not rewrite to a clean URL destination, even if you have clean URLs enabled.  The following will work in Drupal 7:

RewriteRule ^home/code/([^/]+) ?q=home/software/node/&code=$1


Shipping/Delivery Labels in Drupal Commerce

There are myriad number of ways that people want their shipping labels—some print them pre-cut sheets and other use label printers. Overall, every setup is a bit different.

Ultimately, your shipping label solution will be custom (although calling it hack is a bit much). You can use a view to create a single printable "page" (just use an argument to limit it to a single result) and then just use CSS to style it. If you're wanting to print a whole bunch of them, then leave out the argument and ensure that you're setting the proper page size and putting in your page-breaks properly.


7: How to cache $form[] elements in complex AJAX forms

You need to rebuild whole form, no way around it, but you can store expensive things in Drupal cache. I advise against storing parts of $form array if it can be avoided, but using cache_set() and cache_get() to keep things like options available for select B when there is X in select A, it should work like a charm. And it will work with APC and Memcache modules out of the box.

The key is, of course, careful selection of $cid building algorithm.

$form_state as cache

$form_state is kept in form cache bin, but it is not a "real" cache. Let's look at the definition from Wikipedia:

  In computer science, a cache (/ˈkæʃ/ KASH)1 is a component that transparently stores data so that future requests for that data can be served faster.

Now, that's pretty much what $form_state is not - it is kept to save temporary data that needs to be consistent, and that are never stored anywhere else during form processing. It means that when someone is using APC or Memcache, he needs to take extra care to prevent their "it can be deleted without any reason, for performance purposes" approach from corrupting forms. Most Drupal admins I know simply exclude form cache bin from them. And that is not what you want for your pre-built form parts.

Your pre-built form parts are real cache. So you want to keep them in bins that will be treated accordingly, you want to have speed over stability - you can afford additional rebuild once and then more than you can afford slowing down each request by pulling this data from database - slowest cache possible for Drupal.

Second reason not to use it is scope. $form_state exists only per one form session. So if user ends filling the form and access it again, $form_state is build anew. If hundred of users access he same form at one time, you have a hundred instances of $form_state. That's not what you want when your form elements does not depend on the user of your system. By keeping them in separate cache bin, keyed only by the things they depends on, you can have one copy, and use it for all hundred of users, every time they need it. It is impossible to loose anything, and you can decrease load (both CPU for generation and space for storage) to minuscule fraction of what it would be, if you would keep it in $form_state.

Algorithm for using cache (if someone happens to forget, of for newbies reading in future):

Check if data is in cache
If not, build it and save to the cache
Use either data obtained from cache in 1., or built in 2.


Other users cannot view content published to front page

Go to admin/people/permissions and ensure that "View published content" under the title "Node" is selected.

Also, if using OG go to admin/config/group/context and ensure that "Node" is enabled, and that if you have "Content" under admin/config/group/permissions that these permissions are also correctly selected.

Also ensure that the node you want all users to see has the two checkboxes Published and Promoted to front page checkbox ticked. You find these under "Publishing options" when you edit the node as the administrator.

The defaults for these are set per content type. If a user that is not the administrator is creating content, these must be set by default for the type. The built-in content type "Article" has these checked by default, so the user should create article of type "Article" (or another type that has these two boxes checked by default) for the article to be visible on the front page for non-admin users.


Check if the page is a node using arguments in D7

Actually, there is a function that is available in Drupal 6 too: menu_get_object(). With the default values, it will return a node object if the URL for the current page starts with node/[node ID] (where [node ID] is the node ID), and FALSE in the other cases; the function is particularly useful if, after verifying the current page is a node page, you also need to access the node object associated with the page, and the function that is calling menu_get_object() doesn't get a node object between its arguments.

In Drupal 7, there is also another function, but its purpose is just to verify if the current viewed page is the full page view of the node passed as argument: node_is_page().


How do I get the roles of the currently logged-in user?

You can access the current user in D7 via the global $user object
global $user;
$roles = $user->roles;


How to create a list of file fields with checkboxes selector?

Add 4 file fields to your content type with desired labels (ex. "Win 64bit"),
Then you will have this 4 fields in your add content form.

Now it's time to make them optional, first of all using hook_form_alter you can add 4 new elements of class "checkbox" to your form like this:

$form['dependent']['win64'] = array(
  '#type' => 'checkbox',
  '#title' => t('Win 64bit'),
);

and then for your fields add a #states like below :

$form["win 64 file field"]= array(
  '#states' => array(
    'visible' => array(
      ':input[name="dependent[win64]"]' => array('checked' => TRUE),
  ),
);


Safe way to authentication users with REST

Probably because you're a header, should be like this:

{
    "_links": {
        "type": {
            "href": "https://yoursite.com/rest/type/node/article"
    }
  },
  "title": [{"value": "test title"}],
  "body": [{"value": "test body"}]
}


/index.php/ appearing in generated clean URIs

In D7 Global Redirect was used for clean urls. In D8 this was moved to the module Redirect.

The global redirect options in Redirect are set by default to avoid unclean urls:


First off, we should define CRUD permissions for your entities in a correct manner. We will have to implement hook_permssion to define each of our crud permissions similar to the following:

function myentitymodule_permission() {
  return array(
    'view my entity' => array(
      'title' => t('View my custom entity'),
    ),
    'create my entity' => array(
      'title' => t('Create my custom entity'),
    ),
    'edit my entity' => array(
      'title' => t('Edit my custom entity'),
    ),
    'delete my entity' => array(
      'title' => t('Delete my custom entity'),
    ),
  );
}

The implementation of these newly created permissions should reside in your hook_menu implementation that is responsible for creating the CRUD pages you need.

function myentitymodule_menu() {
  $items = array();
  $items['my-entity/add'] = array(
    'title' => 'Add my new custom entity',
    'page callback' => 'myentitymodule_add_page',
    'access arguments' => array('create my entity'),
  );
  $items['my-entity/%entityid'] = array(
    'title callback' => 'myentitymodule_page_title',
    'title arguments' => array(1),
    'page callback' => 'myentitymodule_page_view',
    'page arguments' => array(1),
    'access arguments' => array('view my entity'),
  );
  $items['my-entity/%entityid/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['my-entity/%entityid/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'myentitymodule_page_edit',
    'page arguments' => array(1),
    'access arguments' => array('edit my entity'),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );
  $items['my-entity/%entityid/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myentitymodule_delete_confirm'),
    'access arguments' => array('delete my entity'),
    'weight' => 1,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );

  return $items;
}

Notice the "access arguments" key of each new page defined in the above function need the array keys of your hook_permission implementation. Please note that you will have to create appropriate page callbacks that (should) reside in inc files in order to do things like render the entity view page and render the creation, edit and deletion pages. These callbacks should (at least) take the ID of the entity as an argument.

If we were to compare your custom entity to that of the node entity, the ID that is used for nodes is the nid. That's why pages like node/321/edit exist and use "321" as that ID argument. I think you want to accomplish more or less the same thing.


Problem with views edit link not appearing

Found the answer to my problem. I had missed enabling access user profiles permission for authenticated users.


Deduping Views by forcing Views to add a simple GROUP BY to a query

It turns out that the solution is similar to what I tried: you do need to use hook_views_query_alter.  But playing with GROUP BY is useless unless you can guarantee that you will not be using ORDER BY at all (i.e., you will do no sorting beyond your GROUP BY key).  GROUP BY will contain not only the variable you want to group by; it will also contain every variable you use in ORDER BY.  This appears to be required by the current SQL standard.

The way to do this is this is build your view around the "parent" type ("Course" in my example), and do any filtering you need to do in hook_views_query_alter, using a correlated subquery.  This will look something like this:

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  if ($view->id() == 'course_listing') {
    $where_clause = <<<WHERE
    (
      SELECT COUNT(*)
      FROM {node__field_session_course} link_to_course
      WHERE node_field_data.nid = link_to_course.entity_id
    ) > 0
WHERE;

    $query->addWhereExpression(0, $where_clause);
  }
}

where node_field_data is the base table for Course.

Since there is no left joins or inner joins with the Session table, there are no duplicates, making the deduping problem go away.


How do I use the Cufón module to change the title of a view?

Edit the page.tpl.php template, and add the cufon class to the page title (<h1>). Alternatively add a h1.title rule to the Cufón module.

If you dont't use the Cufón module, add this to your template.php.

drupal_add_js('Cufon.replace('h1.title');', 'inline');


How to add a script to checkout (for affiliate partner programme)?

I would add the script by implementing hook_commerce_checkout_complete in a custom module. You also have access to the order in the function.

function MYMODULE_commerce_checkout_complete($order) {
  drupal_add_js(
   'https://track.adcocktail.com/...',
    array('type' => 'external')
  );
}

You need to debug the variable $order to find the values you stated, [commerce-order:order-number] etc.


Accessing contents of a node id not working in .theme file

First, you are using the wrong hook. peeprocess_node won't send new variables into the page template. You need preprocess_page for that. The page template is not the same as the node template.

Second you are not assigning any new variables. You have to add or alter what is in $variables array or they are not passed to the template.

$variables['vanilla_spice'] = "testing the variable";


Migrate d2d picture migration destination path incorrect

You may try to specify the destination_dir in the __construct() instead of passing the arguments e.g.

class FooUserPictureMigration extends DrupalPicture6Migration {

  public function __construct(array $args) {
    parent::__construct($args);

    // Add simple field mappings
    $this->addFieldMapping('source_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_SRC_DIR);
     $this->addFieldMapping('destination_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_DST_DIR);

Where MIGRATE_D6_USERPIC_SRC_DIR is your source dir and MIGRATE_D6_USERPIC_DST_DIR is your destination dir (e.g. public://pictures).

Alternatively you can fix the user avatars by the following one-time query:

UPDATE users u
SET picture = (SELECT fid FROM file_managed fm WHERE filename = (SELECT SUBSTRING_INDEX(picture, '/', -1) as filename FROM DRUPAL6_DB.users as d6u WHERE name = u.name AND picture <> '' AND fm.filename = SUBSTRING_INDEX(picture, '/', -1)))
  WHERE u.name <> ''
    AND u.name IN (SELECT name FROM DRUPAL6_DB.users WHERE picture <> '')

WHERE DRUPAL6_DB is your database name for Drupal 6.


What is the best practice to split up a long global.css in an Omega theme?

Have you subthemed Omega? I would say just modify your .info file and include an extra css file. I do it all the time, splitting them on function, i.e. styling for node templates etc. in one file and so on.