User menu page visible to the author user (uid)

Access arguments

  Understanding access arguments in Drupal's menu system can be a little
  confusing, but they are really quite simple. Let's take this example
  and work through the arguments.

<?php
  $items['foo/bar/user'] = array(
    'title' => 'Foobar',
    'description' => 'List, add, and edit Foobars.',
    'page callback' => 'foo_bar_function',
    'access callback' => 'user_access',
    'access arguments' => array('administer users'),
  );
?>

  Permissions Arguments, array('this_permission') Here access arguments
  is the key for an array that contains one item administer users. This
  means that the current user must have permission to administer users
  in order to access the page. Which page? Notice the first line gives
  the path to $item. The path is 'foo/bar/user'.

  In this example, 'administer users' is the string that drupal uses to
  reference permissions. If you go to the permissions page (Administer

      User Management >> Permissions), you can see a list of strings you might use for access arguments. Each permission can be used by your
      module.


Select fields with group names in Drupal 7?

You can do that if you use php to generate the allowed values, as you have already read in Select fields with group names?. However, that feature did not go into Drupal core when most of the CCK module for Drupal 6 was included in Drupal 7. The D7 version of CCK tries to provide this feature. As the module page says, it contains:

  some miscellaneous helpers to do things that core will not do, like maintain the PHP code snippets some fields may have been using to define allowed values (partially working)


How do I update Drupal 7 to Drupal 7 DEV via Drush command line?

drush dl is for downloading modules the first time, not updating.

To update core to dev version:

drush up drupal-7.x-dev


Specify a node type (bundle) in entity reference field

Try adding

->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]),

Source


This happens when you go into a product display and then edit the variations inline from there. To stop this happening go to the manage fields screen for your product display e.g.  "Structure > Content types > Product display > manage fields"

Then click edit on the "Product" field and you should see "Auto generate the product title" tick box. Untick that and it should stop the issue happening going forward


There are two workarounds that hit my mind, depending on the logic your UI could have.
1. If having no Group assigned could mean "assigned to all" - go for it.
2. Else: consider adding additional checkbox (boolean) field labeled "Fits all" (or whatever you like).


What is the 'Drupal way' to create a menu callback and display a rendered page of JSON?

Much simpler:

function _client_enquiries() {

  $var_to_output = caculate_value_to_return();

  drupal_json_output($var_to_output);
  drupal_exit();
}


How to detect modules enabled incorrectly?

The problem is that it depends on each module. When enabled, a module sets up its environment (create tables, variables, declare URL, etc) but this environment is not declared explicitly so you can't automatically check that the module has been installed correctly.

You may check the install file for the modules's scheme (tables defined by the module) and the hook_enable to see what tasks needs the module when is enabled.

I think best way is to uninstall modules and try to install them again, so all modules's environent are cleared when unisntalling and set up again when enabled again.

Using drush this tasks is very easy and handy.

Ah, and try to clear caches to see if modules works, but you won't be sure modules installed correctly...


Place output of a custom module in a specific region

If some variable you are looking for isn't available in the scope of your hook, there is a good chance that you are doing it wrong.

Title of the page can be accessed in your theme's page.tpl.php file (or its variants). You can use a hook_preprocess_page() in your template.php file and populate a new variable if the path matches (node add forms have node/add path) so you can put it in the appropriate sidebar in the page.tpl.php.

You cannot control stuff to be shown in the page with a form_alter hook.
For Drupal 7, you could use hook_page_alter() or hook_page_build() to inspect and set sidebar contents.

For an example:

template.php:

function mytheme_preprocess_page (&$variables) {
  if (arg(0) == 'node' && arg(1) == 'add' && arg(2) && isset($vars['page']['content']['system_main']['nid'])) {
    $variables['sidebar_title'] = t('Create new @type', array('@type' => arg(2)))
  }
}

Now, print the sidebar title in your page.tpl.php's appropriate div.

if (isset($sidebar_title)) {
  print $sidebar_title;
}

Drupa.org article: Setting up variables for use in a template (preprocess and process functions)


How to read data from nodes and display in this complex table?

You'll have to flatten the data yourself, as you're grouping by date (you'd have to regardless of the double header and colspans), but yes, theme_table can accommodate that.

I haven't tested this but it should be at least near to working. The key points to note are colspan, which does what you'd think, and header, which will mark a cell to be rendered as <th> rather than <td>. Meaning you can stuff the second row of headers into the body. Not ideal, as they'll be inside a <tbody>, but I suspect good enough.

$header = [
  [
    'data' => '',
    'colspan' => 2,
  ],
  [
    'data' => 'Type',
    'colspan' => 3,
  ],
];

$rows = [
  [
    [
      'data' => 'Day',
      'header' => TRUE,
    ],
    // Other header rows here, with 'header' => TRUE
  ]
];

// Loop through your grouped data
foreach ($data as $item) {
  $rows[] = [
    $item->date,
    $item->colours,
    $item->type_a,
    $item->type_b,
    $item->type_c,
  ];
}

$build = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];


get the list of menu items that are valid possible parents for the given menu item using menu_parent_options()

Try this and see if it helps

<?php
$menu_arr = menu_get_menus();
echo '<pre>';print_r((menu_parent_options($menu_arr, 23)));
?>


How to assign user with civicrm membership to specific role?

Can't think of any better way to say this than the docs: http://wiki.civicrm.org/confluence/display/CRMDOC/CiviMember+Roles+Sync

makes it really simple and straightforward.

Good luck :)


Command option to ignore errors during drush dl

Sorry... Found out how to work around such a situation:

By skipping the explicit download function dl and just using the enable encommand

cd module path

drush en file list

you get an automatic download option, which I think by adding -y you can automatically answer yes to all pompts. It's just a problem that sometimes the module names won't always match the package name.


Consider the benefits and drawbacks of reusing fields:

Performance: There's a slight performance gain from reusing fields. However, for most sites with moderate numbers of fields, it's a negligible difference.
Maintainability: In theory, if you re-use the same field for the same purpose on multiple content types, then if you decide to change its functionality later, you only have to change it in one place. Similarly, if you want to theme it the same way across entities, you only have to use a single selector. In practice, this rarely happens, and more often the converse is true- you've used the same field in multiple places, and then realize that they actually need to behave differently.
Setup: Obviously, it takes less time to re-add an existing field than to add a new one.
Portability: If you export fields with Features, it's best to not reuse them between entities unless absolutely necessary. Technically, there's nothing wrong with reusing fields (since you can export field bases and field instances separately), but in practice it tends to just lead to confusion and circular dependencies. If you choose not to reuse fields, then you have the luxury of being able to prefix them with the content type / bundle they are attached to, e.g. "field_article_image", "field_page_taxonomy", etc..., which eases portability and maintenance.

In case it's not clear from my tone there, my preference is to never reuse fields unless it's totally, completely, 100% clear that they really are, and forever will be, used for the same purpose.


Don't change they tag name, just access_check:

services:
  cunn.saverecord:
    class: Drupal\cunnotification\Access\CUNAccessCheck
    tags:
      - { name: access_check, applies_to: _access_cunn_saverecord }


How to disable views pager programatically in certain cases

Piggybacking off How to set views pager item size programmatically? and looking at PagerPluginBase.

To change values

if ($disable_pager == FALSE) {
  $view->setOffset(0);
  $view->setItemsPerPage($items_per_page);
}

Now to answer your question

  How can the pager be disabled in above code?

You can disable it by setting items per page to zero.

$view->setItemsPerPage(0);

If you want to limit the amount of items without pager, all you have to do is unset it.

   $view = Views::getView('content_list');
   $display_id = 'embed_content_list';
   $view->setDisplay($display_id);
   $view->setItemsPerPage(12);
   $view->execute();
   unset($view->pager); // must put this unset after the $view->execute();
   $variables['content']['content_list'] = $view->buildRenderable($display_id, [$filter_args]);


Cannot deal with multiple iterations of same form on one page

You could also add something like this to your form class

 /**
  * Keep track of how many times the form
  * is placed on a page.
  *
  * @var int
  */
protected static $instanceId;

/**
 * {@inheritdoc}
 */
public function getFormId() {
  if (empty(self::$instanceId)) {
    self::$instanceId = 1;
  }
  else {
    self::$instanceId++;
  }

  return 'my_form_id_' . self::$instanceId;
}


Assuming the inserts are taking place on field tables (e.g. field_data_body, field_data_field_MACHINE_NAME), you shouldn't insert NULL into the *_format columns. Rather, you should be inserting the machine name of your desired filter format (e.g. filtered_html for Filtered HTML or full_html for Full HTML). See the filter_format table for all available machine names for your installation.


How do I print the node add form in block.tpl.php?

The drupal_get_form approach is correct. Make sure you use

print drupal_get_form(....

Edit:

Take a look at function node_add().
You also need a $node parameter for this form. So like

<?php
  global user;
  $node = array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'foo', 'language' => '');
  print drupal_get_form('foo_node_form', $node);
?>


I need to disable the Bartik theme completely to make the sub-theme work.


hook_menu wildcard auto-loader for webform submission?

It is looking for a _load() function. In the case of node, user, or taxonomy term arguments (eg %node), it is looking at node_load, user_load, etc.

If you passed %mymodule_foo as the wildcard, then it would look for mymodule_foo_load().

Therefore, if there is a webform submission _load function that loads a submission, thats what you want to use as the wildcard.

The wildcard you want to use is %webform_menu_submission. Webform has a corresponding _load function for it:

/**
 * Menu loader callback. Load a webform submission if the given sid is a valid.
 */
function webform_menu_submission_load($sid, $nid) {
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission = webform_get_submission($nid, $sid);
  return empty($submission) ? FALSE : $submission;
}

Note that this function also needs a $nid argument to work.

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named mymodule_abc_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments

See:

https://stackoverflow.com/a/13788403/295112
https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7.x
http://cgit.drupalcode.org/webform/tree/webform.module#n342


Drupal 8/9 modules often use events to take the place of alter hooks like this one found in Commerce 1.x on Drupal 7. You have to do a little digging to find the place in the code that executes it, but you can look it up with the following info:

An Add to Cart form in Commerce 2.x is an order item add form governed by the "Add to Cart" form mode (a new concept in Drupal 8).
Looking at the configuration for the default order item type, you can see that the "Purchased entity" reference field uses a field widget called "Product variation attributes."
You can find that widget's definition in the ProductVariationAttributesWidget.php plugin contained in the product module, and its formElement() function shows you that it invokes an ajaxRefresh() function on the object to process the Ajax response when attributes are updated.
That class extends ProductVariationWidgetBase where the ajaxRefresh() function is located. You can see that it builds a response array using an Ajax renderer and gives other modules the opportunity to add commands to the response array via the PRODUCT_VARIATION_AJAX_CHANGE event (using a constant defined in the ProductEvents.php class).

If you're still following, the solution then is to create your own event subscriber that subscribes to that event and appends your own commands to the event's $response array. I've created an example module showing how to do this: https://github.com/rszrama/commerce_example3


Best way to backup and restore the databases of a Drupal 7 multisite using Drush?

This is how I do the restore on a site-by-site basis:

drush @site1 sql-drop -y && gunzip -c /path/to/backup/file1 | drush @site1 sql-cli

You could maintain a list of site aliases to database name and write a shell script to automate the process.

The database name for an individual site could be extracted as follows:

drush status @site1 --fields=db-name --field-labels=0

Unfortunately, there's no all-in-one solution for restore.

An alternate solution would be to use the Backup and Migrate module, which has drush integration. There are bam-backup and bam-restore commands which might be easier to work with.

As @Duncanmoo mentioned, it's also good to run drush rebuild-registry after the restore.


How to get a link to entity_reference in ListBuilder?

One possibility is to use the Link render element, and by using the canonical link for the Adherent entity. This assumes that the Adherent entity type definition has a canonical link, and that the route is defined in your module's routing YAML.

$row['adherentid']['data'] = array(
 '#type' => 'link',
 '#url' => Uri::fromRoute('entity.adherent.canonical', ['association_adherent' => $id]),
 '#title' => 'My link',
);

Another possibility is to render the field, and use the display mode that provides a link to the entity using the entity label. However this is less accessible in the documentation to look up within a reasonable time.


How to get a view result programmatically without exposed filters respected

Thanks to 4k4 (see comments). The solution is to set some dummy exposed filter data:
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->setExposedInput([
    'dummy' => ''
  ]);
  $view->execute();
  $result = $view->total_rows;

In this way it works.


I don't really use multi-site, so my answers here are hypothetical.  I recommend using a separate Drupal root for each site, unless you have a very strong reason to share code.

drush @sites sql-dump is not a good idea.  This is going to run sql-dump in turn on each of the databases of each of the sites.  If this worked correctly, you would either get all of the databases concatenated together (e.g. if you sent the dumps to stdout, and saved the result via output redirection), which you could never hope to restore, or, each database would be saved into the same result file, each overwriting the previous.  Drush does not support dumping multiple databases to a single dump file.

drush @sites pm-update will do redundant work.  It will run the code update on each site sequentially; the projects for each site are shared, so sites that are updated after the first will have most or all of their projects already updated.  After updating the code, pm-update runs updatedb on each site, which does need to be done for each site's database individually.  Note, however, that the most important part of an update is testing, so you might as well update each site individually.

If you want to update only Drupal core, use drush pm-update drupal.  To update everything except core, use drush pm-update --no-core.


How can I skip the current password validation on the user form?

A working code example for this is the No Current Password module.
Here's the relevant code:

/**
 * Implements hook_form_FORM_ID_alter().
 * Remove the current password field from the user_profile_form form (user/%/edit).
 */
function nocurrent_pass_form_user_form_alter(&$form, &$form_state) {

  // Get the module's configuration
  $config = \Drupal::config('nocurrent_pass.settings');
  $nocurrent_pass_disabled = $config->get('nocurrent_pass_disabled');

  // If the Current password is disabled
  if ($nocurrent_pass_disabled) {

    $account = \Drupal::service('current_route_match')->getParameter('user');

    // If this is not the Superadmin's edit page
    if ( !empty($account) && ($account->id() != 1) ) {

      // Turn off Current password field's validation
      $form_state->set('user_pass_reset', 1);

      // Hide the Current password fields
      $form['account']['current_pass']['#access'] = FALSE;
    }
  }
}


error: Fatal error: Class 'Drupal\syslog\Logger\SysLog' not found in /lib/Drupal/Component/DependencyInjection/Container.php on line 272

If this is a local install, you could install Drush, and then: drush dis module. Or you can go here for more sophisticated solutions.


It seems like you updated the CSS semi-correctly.  Semi because, it does look like Zircon's CSS is built using SASS/Compass and not directly. You might want to look at how to set this up properly.
You are also correct that you really need to set up a sub-theme first.  The reason to do this is that when updates to the Zircon theme come out, you will need to figure out what you changed, save it, update the theme and then re-merge your changes.
See the documents on how to set up a sub-theme.
As to why your CSS change did not take effect, these are some possibilities:

First, your rule was added, but is being overridden by a more specific rule.  Inspect the element and see if the rule shows up but it's red lined.
A quick hack is to just add !important to your rule.  This should make it most specific, unless someone else added it to their rule.
The best way would be to get SASS/compass set up, find where the .site-name is themed in the SASS files, change it there, and rebuild the CSS with Compass.

If it's not a CSS rule thing, it might be an external caching system.  First, I assume you did a FULL reload of the page (Generally Shift F5) to clear the local browser cache.

Next, did you set up Varnish with your site?  If so, you might need to clear the Varnish cache, or set up some rules so that logged-in users don't use cache.

Are you using something like Cloudflare? This can also cache CSS. You can check for external caching by using Chrome's Network tab (inspect something on the page or select the Network tab). Look for the CSS file that you modified, click on it, then check the headers. See if there are any tags like CF-xx or X-varnish with values like hit or miss. (A hit means it was served from cache).

That said, while you are developing a site, you probably want to do what you did:

Turn off all aggregation
Turn off caching (Config -> Devel-> performance)

This might seem a bit daunting but it's really not.


@Luism, you should use field widget for it. field_attach_form attaches fields to form, field_attach_form_validate validates all attached fields, field_attach_submit prepared entity to be stored. Regarding values in $form_state['values'] you will have big structure inside $form_state['values']['FIELD_NAME'][LANGUAGE][INDEX] but you need only $form_state['values']['FIELD_NAME'][LANGUAGE][INDEX]['fid'], it will contain File ID from file_managed table (with status=0) for uploaded files and after profile2_save() file will be activated or deleted otherwise.


Have you tried Entity Tokens? It's part of Entity API module.

There are long discussions about date tokens: Date issue about date tokens and Entity Token issue about multi-value field tokens.


Extracting a specific data part of a Field Collection Item

I use Entity API when work with Field Collection Items. See: Programmatically create and update field collection with Entity API

To work with field collections can do smth like this:

// Wrap node with Entity API
$node_wrapper = entity_metadata_wrapper('node', $node);
// Get the first item from the muli-value field collection
$raw_collection = $node_wrapper->field_video_collection[0]->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
debug($collection->field_video_file_col->value());

If you already know your field_collection id you can just do:

$collection = entity_metadata_wrapper('field_collection_item', $fid);
//dsm the old value
debug($collection->field_video_file_col->value());

UPDATE:

use the code above in MYTHEME_preprocess_node

UPDATE 2:

So in your case it will be:

function MYTHEME_preprocess_node(&$vars, $hook) {
  if (empty($vars['nid'])) {
    return;
  }
  // Wrap node with Entity API
  $node_wrapper = entity_metadata_wrapper('node', $vars['nid']);
  // Get the first item from the muli-value field collection
  $raw_collection = $node_wrapper->field_video_collection[0]->value();
  // Wrap field collection with Entity API
  $collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
  // print value
  $fid = $collection->field_video_file_col->value();
  debug($fid);
}

Also you can find answer at Understanding Field Collection Values


how to get the region (the menu is rendered in) or block name/ID in hook_preprocess_menu

hook_preprocess_menu is missing a lot of variables that other preprocessors have so I finally solved my problem using hook_preprocess_block (which I think would not have been possible in earlier versions of drupal)

New solution since people have been reporting that $vars['configuration']['region'] is empty

function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            $block = \Drupal\block\Entity\Block::load($vars["elements"]["#id"]);
            if( $block->getRegion() == "navbar")
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

NOTE if using in a recursive function/twig MACRO (which probably you are) you should  removeClass all the classes you don't want in inner UL tags in a way similar to this

{{ menus.menu_links(item.below, attributes.removeClass('nav','in-navbar'), menu_level + 1) }}

old solution

function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            if($vars['configuration']['region'] == "navbar"){
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}


File to media migration: use node title for media title

Without knowing your content model, you can't answer this question directly, but what you'll need to do is query your node title for every fid entry for your source file entities table. You can do that in many places (e.g. source/process plugin) with your existing source plugin being a good place.

Using your custom file_entity source plugin as an example, you'll need to update the query() method so  its DB query joins the node table based on how you're content is modeled (e.g. entity/paragraph references) then selects the title column so it's included in the row data. You can follow that up with updating the fields() method so your source plugin will provide the title field you need.


Commerce checkout form all pane errors to be displayed on top of form

As Ryan mentioned, it's difficult to change that behaviour server-side, however you could move the error messages to the top of the page with JavaScript instead.

e.g

style.css

/* Hide checkout messages by default to show with JS later */
body.page-checkout .messages{
  display:none;
}

script.js

Drupal.behaviors.moveCheckoutMessages = function (context) {
  $('body.page-checkout form .messages', context).each(function () {
    $('.region-content').prepend($(this));
    $(this).css({"display":"block"});
  });
}

A client-side approach like that should work.


Can I connect via REST services with a mobile app I will develop?

yes you can exposes entities and other resources as RESTful web API by activating the core RESTful Web Services module

  /admin/modules


host static files (images) to 3rd party host such as Amazon Cloud. Any modules can facilitate this?

I would go with the CDN module, also checkout the AmazonS3 module.


Zen subtheme: no sidebar on a given page

After some tests which involved using arguments in page.tpl and CSS trickery to clean up after, I couldn't manage to have a proper working solution.

Although I would have prefered to find a way to do this at a template level, easiest and quickest solution I finally found, was to use Context module

Basically I created a simple context with a Condition on path option and a Reaction on regions of the concerned theme. Checked the sidebar I wanted to exclude Saved and it was done.

Good thing doing this through the Context module is that, it removed the concerned regions, but most importantly it removed also the corresponding classes from <body> which were the pain in the butt to begin with.


Constraint on paragraph field not working

On your addConstraint() your second parameter is an empty array - if you do not want to add any options leave that empty or use NULL


Because you are already using Views, consider using the Rules with Rules Link module.  This kind of setup could be done quite easily and even stored in a Feature so that the changes could be maintained in a git repository.


How to actually set a maxlength for textarea field in contact form

The Form API does not allow to set a maxlength on textarea field types [while plain HTML does]

That's not strictly true....HTML5 introduced a maxlength property for textareas, previous versions do not have it (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

The default templates that come with Drupal 7 all use XHTML, so the lack of explicit support for HTML5 makes perfect sense.

As long as your doctype is HTML5, this will probably work:

$form['element'] = array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 200),
);


image field point to another image field

What you need is a change in the way the content is displayed, so it is much better to do it in theme layer rather than content level.

I would recommend using template preprocessing for node.

Add this function to the template.php file in your theme folder:

<?php

/**
 * Implements hook_preprocess_node().
 *
 * Replaces the node's image field with anbother node's image field
 */
function YOURTHEME_preprocess_node(&$variables) {
    $node = $variables;
    // Make sure we only alter nodes that we intend to!
    if ($node->type == 'article') { // assiuming your article content-type is 'article'
        // Get the view mode for this node, e.g. full or teaser
        $view_mode = $variables['view_mode'];
        // Get the group node
        $another_node = get_another_node($node); // Somehow!
        // Retrieve the image field of that node using the same view mode of the current node
        $another_image_field = field_view_field('node', $another_node, 'field_image', $view_mode); // assiuming it is called 'field_image'
        // Replacing the other field with the current node's field
        $variables['content']['field_image'] = $another_image_field; // assuming it is called 'field_image'
    }
}

You will need to update the code to retrieve the node object for the group and also make sure that the field names are correct for your case.


You can get the cookie domain this way using the session_configuration service.

$sessionConfig =\Drupal::service('session_configuration');
// Get the current request.
$request = \Drupal::request();
// Get options from the request.
$options = $sessionConfig->getOptions($request);
$cookie_domain = $options['cookie_domain'];


How will speed be affected by entity_metadata_wrapper()?

Entity API does a lot of things, but most of them are cached.

For example, entity_metadata_wrapper() calls entity_get_info(), which uses the cache to retrieve the data. If the cache is empty, other functions are called:

drupal_schema_fields_sql()
cache_set()
...

Other modules may be involved through hooks:

module_invoke_all('entity_info');
drupal_alter('entity_info', $entity_info);

But note that no data is fetched from the database, this is because when you call entity_metadata_wrapper() you already have the entity loaded -it's a parameter to the function, indeed.

So if you are running critical or long processes such as importing data or running thousands of iterations inside a loop, you should better use entities directly. But even then, the cache should help a lot.

Look how Drupal looks without Entity API:

$field = '';
if (isset($entity->field_name[LANGUAGE_NONE])
    and isset($entity->field_name[LANGUAGE_NONE][0])) {
  $field = $entity->field_name[LANGUAGE_NONE][0]['value'];
}

It's ugly. This is why I use Entity API almost everywhere, and I haven't had any performance issues so far. For the benefits, I think it's worth using it.


How do I call an object in a prepressor only once

If you want to call the preprocess hook on nodes only you can use template_preprocess_node().


Is there a module for creating a web directory like Dmoz?

You could use taxonomy_menu module. It is compatible with D7. You can arrange the taxonomy in whatever style you want and embed it in views/pages/blocks.


How to change access callback for content create?

Absolutely. Just replace original access callback with your own function, and then in your function do both your checks AND call the original callback function.


As a comment suggested, sounds like your server does not have a writable files folder. That folder should and is by default excluded from git, you need to create it and make sure that the apache user (or whatever user the processes run as) has write permissions to that.


How to display drupal user page tabs on 3 different page

One quick solution to hide the tabs is to change the menu type form tabs to callback:

/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $items['user/login']['type']    = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;
}

You could render the user register form whatever you want with this:

$elements = drupal_get_form("user_register_form");
$form = drupal_render($elements);
echo $form;


How do I deal with serialization unsetting object members?

__sleep() works by returning properties that need to be serialized. A private property is invisible, won't show up in $vars and therefore is also not serialized and just silently dropped.

Either don't use private (it only serialized services, I assume data is not a service), or override __sleep(), call the parent and then add data to the list of properties to be serialized.


How to Post JSON data to Cart service in Drupal Commerce Services

I found JSON structure for Cart or Order Services. It's something as below:

{
   "type":"commerce_order",
   "commerce_customer_billing":"10",
   "commerce_line_items":
       [
           "11",
           "13",
           "14",
           "15",
           "16"
       ]
}


How can you hide modules form all listings without deleting them

Use this module to Hide.
Hide Module
This will hide the module based on role.

Hide Modules allows selected modules not being listed at the module administration page except for selected roles.
It enables administrators to safely grant 'administer modules' permission to other roles and keeping at the same time some modules out of the list to avoid untrusted users enabling or disabling them.


Only show the cart block if it contains items

Here is the solution. Add these lines in template.php file of a theme you`re using. Change THEMENAME on the name of your theme.

function THEMENAME_commerce_cart_empty_block() {
  return '';
}


If this was purely about just views accordian, then the rendering output you show would not be showing a div with a class of panel-heading. I see this as more likely about trying to have a views accordian rewrite into a panel and probably panels accordian at the same time and having the anchor tag reduced to a single line output when the html is stripped out. So without knowing what the full details are I can only suggest trying the rewrite as:

[field_event_date_1]
[title]

[field_time_slot_1]

or if only the div tags are being stripped out then try:

[field_event_date_1]

[title]

[field_time_slot_1]


Having required (*) show up on the component itself and not the label

Have you tried Form Placeholder? It will hide the label and add the asterisk on the select field.


How specific do you need to be with the name of your template file? You should be able to create a page--branch-locator.tpl.php that gets picked up by Drupal's auto-detection mechanism. At least, that would have worked in D6 (minus the extra hyphen after page).


Javascript related problems when using old versions of IE and a proxy server

This was seemingly a server specific issue regarding a server I am not the maintainer of so I never got to the bottom of the exact cause (which is annoying because I like to know), however I eventually got around it by using the jQuery Lazy Load plugin to load the images.


Add text above the registration form on user/register page

The simplest way would probably be to create a block that is only displayed for that page, and position it above the content.


Adjusting the month being viewed on the Calendar Block to match the month of the Day being viewed

Have you tried to set "track current date in session" under admin/config/date/calendar?

This should do the trick...


Load a user object via login form name field

For user_load function in D6 you have to use pass the $user_info array like ,

 $account = user_load(array('name' => $form_state['values']->name))


How to change the delete Message "Are you sure you want to delete" in Drupal 7

One option (that requires no coding) is to use the String Overrides module.

It allows you to replace any string with another string that is passed though the t() function, though a nice easy to use GUI.

The other option is to use hook_form_alter(). For more details on that see the question that Rupesh linked to.


This issue is referenced in Dkan developpers Google group.

You probably have updated Feeds modules in Dkan profiles folder? Read the above post carefully and consider trying proposed solution :

Keep the Dkan profile original code in place
Download Feeds 7.x-2.0-beta4 to sites/all/modules/contrib
Rebuild registry

EDIT : I browsed both Feeds and Dkan feeds.module history. I couldn't find any implementation of feeds_node_prepare() in Feeds, while Dkan contrib feeds.module does implement it.

Seems that Feeds in DKAN profile contrib modules directory is a fork, not official release.


How can i add WYSIWYG editor for my custom form textarea?

Drupal 7 introduces the form element #type text_format, which is a text-format-enabled version of a textarea.

To integrate WYSIWYG into your custom form, just modify the attribute #type of form as:

'#type' => 'text_format'

Note: Tested it with CKEditor v 7.x.

In case if it doesn't work for you, please check your WYSIWYG configuration.

To hide format options, see: How to hide Input Format Options and help text under a textarea?

Above text field type works in Drupal 7 and 8.


Up-to-date solution for cloning commerce product-variation types and their product displays

After trying out all above modules, I can clearly say for my usecase the winner is:
bundle_copy for cloning product displays in combination with bundle_copy_commerce for the product variations.
Cave: I didn't use the clone/copy feature of both moduls because of errors and poor cloning (fieldgroups weren't copied) – instead I used the export/import feature:

Export the entity
Replace in the code from step 1 all occurences of the bundle name with a new name
Import the code from step 2 again.
When using fieldgroups you have to make sure, you rename the fieldgroups in step 4 with a unique name (add the bundle name as a suffix, for example).


How to get formatted total amount programmatically?

I had the same issue. I solved this issue by dividing the total by 100. You can see the total amount in the field_revision_commerce_total table. After dividing, I used commerce_currency_format($amount,NULL,NULL) to get the currency format.


When doing a page preprocess, how do you know if the page is a form?

Since I wanted to apply a change to the page.html.twig template based on if it was a form, I looked first for the form suggestions I was given. Since I couldn't find a way to generically apply a template to all forms, I instead created a template that I would then tell all of the forms that I have to use this template. I used a hook_theme_suggestions_HOOK_alter to add my new template and check the existing suggestions to see if the forms I want to use are part of the current suggestions:
function listed_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $forms = [
    'page__user__register',
    'page__admin__people',
  ];
  foreach ($forms as $form) {
    if (in_array($form, $suggestions)) {
      $suggestions[] = 'page__forms';
    }
  }
}

From here, I can add additional forms as they are needed to use this single template. So, this solution doesn't exactly answer my original question, but it solves my original problem.


I have a similar setup using Pressflow, changing

$base_url='http://www.yourdomain.com';
$cookie_domain = 'yourdomain.com';

in sites/default/settings.php seems to get boost cache cleared.


Advantages of using drupal mobile technology over mobile middlewares

You can do everything in Drupal. My recommendation is to run an m.site.com domain (either to a different multi-site or with branching logic in settings.php) that not only changes to a mobile theme, but also switches to an alternative anonymous page cache bucket and sets a few variables for later use.

Then, whether you are using panels or not, you can set ctools page_manager overrides for your homepage, content listings, node views etc. and have these only kick in for the mobile domain. This way you can potentially hit the database less for logged in users by showing simple pages, and you can also switch imagecache/'image styles' to be more appropriate to the device and save on bandwidth.

That way you can get all the output you'd get from Diazo or Kurogo but keep it all in Drupal. Which is you are working in a team of Drupallers, is surely a good thing

Hopefully that little ramble described the approach well enough to be useful ;)

I think the http://drupal.org/project/mobile_tools module contains ways of doing this if you don't know how to write it yourself.


The "content revision : content" relationship in that view needs to be based on the nid rather than the vid. Remove that existing relationship and add back the one that has the same name but uses the nid.

Then you'll need to fix the relationships that have been broken since a number of the fields, filters, and sort options relied on that relationship.  You can just step through each of the fields and filters, open their settings, then click "apply" to re-save them to fix the relationships.

In the settings for the title field you need to switch it to link to the revision rather than the node, in order to avoid an error.

And I also noticed that, for some reason, the exposed "published" filter got switched to having a default value of "no" after doing these steps.  I have no idea why that happened, but switch it back to "any".

Here's an export of the View you should end up with: http://pastebin.com/a9tXXCqP


After both your field and your field instance are created, you need to enable it in the related form:

entity_get_form_display('node', $bundle, 'default')
  ->setComponent('field_custom', array(
    'type' => 'string'
  ))
  ->save();


How to insert a new column into mysql field data table?

For adding new column in table, please check this discussion Correct way to add custom column to user table?.

Please check this discussion also https://www.drupal.org/node/2616250


Variables available on display suite php field

You can get access to the node via the $entity variable within the "Field code" text area.

This will only work for the Display Suite "Code Field". If you are using Display Suite 7.x-2.x, you'll have to enable the "Display Suite Format" module.

If anything is setup properly, you should see this help text below the "Field code" text area:

  You may post Display Suite code. You should include  tags when
  using PHP. The $entity object is available.


You can use Menu per Role module.

Project page says:

  This module allows you to restrict access to menu items based on user
  roles. It depends on the Drupal core menu.module just activate both
  modules and edit a menu item as usual. There will be a new fieldset
  that allows you to restrict access by role. The fieldset also appears
  in the node edit form.


Drupal 7 with Media: YouTube only embeds static image

Media 7.x-1.x only embeds images via WYSIWYG.
I would always recommend media 7.x-2.x for anyone unless you have a strict security policy of only using full releases. 2.x has many great new features.

With Media 7.x-2.x:

The media module currently only has support for embedding images via WYSIWYG.

What version of media are you using? If you use media 7.x-2.x you can get it to work by using this sandbox module - http://drupal.org/sandbox/DevinCarlson/1823634 (note that you also need separate http://drupal.org/project/issues/file_entity module with 2.x because it has now been split out of media - it was part of media in 7.x-1.x)

That sandbox module allows configuring which view modes are used for different file types when embedding via WYSIWYG.

There is a related issue for the media module here http://drupal.org/node/1792738 - It has been decided in that issue that the sandbox module will be integrated into the media module. So you can safely use the sandbox knowing that the functionality will eventually be in the media module, at which point you won't need to rely on a sandbox project.

When using that setup of modules I find that in a lot of cases it is also good to use http://drupal.org/project/entity_view_mode - which allows you to create new view modes (the file_entity 7.x-2.x module doesn't provide many view modes out of the box).


How to integrate Lockr encryption key with Ubercart credit card payments

A kindly developer wrote a patch for Ubercart that integrates Lockr key. It's working great for me.

You can find the patch here: https://www.drupal.org/node/2842813

Note: it's written for version 7.x-3.9 which isn't the latest, so it may have to be modified and rerolled for the current version.


Finding FORM ID without installing module

Finding the Form ID is very easy no need to install modules and all

STEP 1: Open you from go to its edit page(OR inspect your form).

STEP 2: if its a node form find "node-form" in the inspect element

 check you are in the form element.

STEP 3: see attached image the highlighted green text is the ID of the form

STEP 4: IMPORTANT Finally if you want to use it in hook_form_alter() replace the hypen with underscore

For example: yourform_id_with_content_type_name_form

Like wise you can find id of any form in drupal all you have to do is inspect->find form element and search for the ID attribute and use it

Hope it helps :)


Multiple condition in Conditional Field doesn't work

I was in the same trouble.

I just found that you can use one condition and use "Values input mode" to  Only one of these values (XOR) and Set of Values to the ID or Text of the value of the field you want.

Check that : http://www.interworks.com/blogs/gbivens/2010/06/04/tricking-drupal-webforms-allowing-multiple-options-same-key-value

EDIT : Here a picture


How to ajax changing date field on _node_form?

I found a solution but not why, if someone knows and says I will mark as the correct answer.
Phone type behaves similarly to the decision to date and it is the same.

First of all this was hard to debug. For this I add in ajax callback the line

ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),

And now all code

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'order_node_form') {
    // Date (Unix timestamp)
    $form['field_date']['#prefix'] = '
';
    $form['field_date']['#suffix'] = '
';

    // simple text line input
    $form['field_some_text']['#prefix'] = '
';
    $form['field_some_text']['#suffix'] = '
';

    // Phone number module field
    $form['field_phone']['#prefix'] = '
';
    $form['field_phone']['#suffix'] = '
';

    // Taxonomy reference select list
    $form['field_category_name']['und']['#ajax'] = array(
      'callback' => 'category_name_callback_func',
      'wrapper' => 'field-some-text-replace',
      'method' => 'replace',
      'effect' => 'fade',
    );

    if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
      $form['field_some_text']['und'][0]['value']['#value'] = 'after change';
    }
    else {
      $form['field_some_text']['und'][0]['value']['#value'] = 'before change';
    }

  }
}

/**
 * AJAX callback for 'field_category_name' form
 */
function category_name_callback_func($form, $form_state) {

  if (!empty($form_state['values']['field_category_name']['und'][0]['tid'])) {
    $form['field_phone']['und'][0]['number']['#value'] = '999999';
    $form['field_phone']['und'][0]['country_codes']['#value'] = 'gb';

    $form['field_date']['und'][0]['value']['date']['#value'] = '01/01/2014';
  }
  else {
    $form['field_phone']['und'][0]['number']['#value'] = '';
    $form['field_phone']['und'][0]['country_codes']['#value'] = '';
  }

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#field-date-replace", render($form['field_date'])),
      ajax_command_replace("#field-some-text-replace", render($form['field_some_text'])),
      ajax_command_replace("#field-phone-replace", render($form['field_phone'])),

      // remove comment (//) on next line for debuging
      //ajax_command_prepend("#field-date-replace", theme_status_messages(dpm($form_state)), 'status'),
    ),
  );
}

The difference between all the examples I've seen, and this decision is that the values change is made in "ajax callback" but not in hook_form_alter.


How do I display individual date display nodes of a commerce event with recurring dates?

Repeating Dates in Calendar are single nodes that store all the occurances of the event, so for this to work you may have to create single events instead of one that is repeated. Good reading on that issue found here: http://drupal.org/node/298334


How to display most recent node in different Panel

You can use Views module to have custom content or links and show as a separate page or a block.

check this link:
http://drupal.org/project/views


Adding CSS class to flagged node teasers

The preprocess code looks reasonably correct.

Make sure you're printing out the $classes variable in your custom node--content-type.tpl.php

e.g, in the wrapper div here:

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

<!-- Node template content ... -->

</div><!-- /.node -->

If curious, $variables['classes_array'] is flattened into $variables['classes'] in template_process with

// Flatten out classes.
$variables['classes'] = implode(' ', $variables['classes_array']);

In D7, process functions are introduced, running after preprocess functions.


Yes, as you mentioned, you can do that reasonably easily with Panels / Page Manager

Enable the "Custom content panes" module to add arbitrary HTML content to Panels regions.

Note, when using Views in your Panels content try Views Content Pane type displays, which are designed for embedding into Panels and provide some useful settings in the View.


Theme are different between different user

Go to /admin/people/permissions
Enable the "View the administration theme" permission for the appropriate role.
Save the form.

Users with that role will now see the admin theme (as set at /admin/appearance) wherever applicable.


How to produce a dropdown filter by year of post date isn't as immediately obvious as you might think - but it doesn't need any custom code when using Drupal 7 with views.

Within your view add a new filter. You might think you need to choose 'Content: Post date' but this will not give you the options you need. You should actually choose 'Date: Date (node)'. For data selection form element choose 'select' to create your dropdown. Set Filter granularity to 'year'. Give a starting year e.g. '-10 years from now' and an ending year e.g. '+ 0 years from now'. Then in 'date fields' you select where the date(s) are drawn from, it is here that you choose the 'content: post date'.

It is worth noting that other date fields are exposed here, so you are not limited to the post date.


How to write a simple test case for users by using drupal_mail() function?

Finding documentation about the SimpleTest module has never been obvious (also because using the Read Documentation link on the module's project page causes a 404-error ...).

Here are some pointers I've found so far:

The article about A Drupal Module Developer's Guide to SimpleTest (not sure right now how accurate it still is, but at least it outlines the main steps). Note this part in it: "... make a simple list of things that your module does. This list will translate directly to SimpleTest tests.".
The article about "How to: Write Automated Tests for Drupal", in one of it's comment near the bottom it says:

  As of now, it's the same API for the Drupal 7 core module and the Drupal 6 contributed module (http://drupal.org/project/simpletest), so this tutorial should work for both.

The SimpleTest Example that comes with the Examples module, and also includes a .test file (something you refer to in your question also). In other words: the best available documentation on this is "read the source".

Be aware:

Make sure to you take into account what's written in API.txt, i.e.:

  ... Provides a reference of the API changes between SimpleTest 7.x-1.x included with Drupal 7 core and SimpleTest 7.x-2.x.

  Modules that provided 2.x compatible tests are required to add the following attribute to their info file: testing_api = 2.x.

So SimpleTest requires a version number in the .info file, which you specify by adding that testing_api = 2.x in your .info file.
This module has Maintenance status: Unknown, Development status: Unknown

Note: As of D7, there is the PHP Unit Testing Framework module (namespace = testing). Refer to the Community Documentation about Testing (D7 and D8) / SimpleTest (D6) for quite some more details on all this.


What file or data I should NOT give outsourcing developer for security when they need a copy site of my site?

Deleting the user table might break features that rely on node authors or some other user information. Try setting every user's email to email@mail.com and their password to 'password'. You shouldn't give the settings.php file, since it has your database credentials and the cryptographic salt Drupal uses to hash users' passwords.


Apply conditionally an image style on an User Profile page

This module auto image style, is also available for drupal 8.

It describes:

  Allows to apply an image style depending on whether the orientation of original image is portrait or landscape.

So it might be what you want.


No results because of relationships, unless "Bypass content access control" is selected

https://www.drupal.org/project/commerce/issues/1276450

The above link solved it for me (#5: Disable SQL Rewriting).


https://docs.drupalcommerce.org/commerce2/user-guide/products/manage-product-structure contains documentation for Commerce 2.x, which is based on Drupal 8.

You're using Drupal 7, which is Commerce 1.x, so you need to find and follow the Drupal 7 documentation. That should be as simple as clicking "Commerce 1.x" in the left-hand navigation panel.


hook_form_alter or overriding the routing and UserLoginForm class

I would definitely go for the second option. In my opinion the form_alter hooks are reserved for 'minor' changes to a form. I always use custom forms as much as possible (extending the original form).


PDO Deadlocks Galore on the Semaphore table

It appears that once we implemented memcache the problem began to dissipate. It appears the database was writing very frequently to the cache tables, specifically the cache_form table. These deadlocks would appear when there were just too many commands running on the box.


Application form and fee for Drupal Commerce

The new line item type and adding it to the order was the way to go it seems.  My code is posted in this post.

That code worked, however, I kept getting an access denied when trying to check out. DC runs a hook called hook_commerce_checkout_order_can_checkout().  The order is passed to this hook, and you can determine if you want to allow access.  I did on all instances and didn't need to write any logic, so I just returned TRUE, and everything worked.


drupal 7 Views: output a field with views php

Indeed, views PhP doesn't always get the processed field and only gives you the nid instead. You have to use $data as you tried (by the way, easier is to dpm($data) than print_r).

if it doesn't give you any info on what you're looking for, you can simply obtain your content:path by using drupal_lookup_path :

$path = drupal_lookup_path('alias', 'node/' . $data->nid);


Show entity reference content with a field other than the title

I've done this before:

You can override the Autocomplete field widget, so instead of title, it will give you back something else! You need to inheritance the existing one and after 2-3 of other inheritance you will be able to reach the autocomplete ajax functionality and rewrite it. It's pretty complex, but not impossible!


Error running a PHPUnit test only under run-tests.sh

@Berdir is completely correct here:

  I'm not sure but you might not be able to have a non-test class in the tests/src location, try moving that to module/src/... and change the namespace accordingly (Drupal\module...

While PHPUnit doesn't mind if a test class uses a trait that's in a Drupal\Tests namespace, the simpletest test runner run-tests.sh will be unable to find the trait if you do this.

So don't do that.

Even if a trait is used only with your test classes, if you want your code to get past the Drupal testbot, the trait needs to live somewhere in your Drupal\your_module\ namespace. Do this, and both phpunit and run-tests.sh will be happy.


Conditional statement in custom template file using Display Suite

First, you have a syntax error. Your server might not have been configured to allow short tags.

Try using <?php echo instead of <?=

Second, you could either use the Field formatter conditions module to add display conditions to your fields or create a custom code field in Display Suite.

EDIT: How to  add a Display Suite custom code field in your own module:

1- Create a new module and add this code in it (remember to change MY_MODULE with the desired name):

/**
 * Implements hook_ds_fields_info().
 *
 * We add the code fields to Display Suite here.
 * Then we specify a callback function that will handle the display logic.
 */
function MY_MODULE_ds_fields_info($entity_type) {
  $fields = array();

  // Add a new custom code field. It should be available in Display Suite.
  $fields['node']['tags_custom'] = array(
    'title' => t('Tags (custom)'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'MY_MODULE_ds_field_tags_custom',
  );

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }
}

/**
 * Callback to show the tags field only if it has a value.
 */
function MY_MODULE_ds_field_tags_custom($field) {
  $node = $field['entity'];

  // Get the tags field value.
  $tags = isset($node->content['tags'][0]['value']) ? $node->content['tags'][0]['value'] : NULL;

  // Return a string or nothing, depending on the tags field value.
  if (!empty($tags)) {
    return t('Category: ') . $node->content['tags'][0]['value'];
  }
  else {
    return NULL;
  }
}

2- Now, if you go to admin/structure/ds and click on the Manage display link, you will see your new field Tags (custom). Set its label to hidden and publish it in the desired area.


Allow authenticated users to update submissions

You might want to implement an application evaluation workflow and the Webform module includes a 'Webform Demo: Application/Evaluation System' module.

The demo has an evaluation form attached the application form using a block.

For the email routing, you should be able to use a user entity reference token in email handlers 'To' field.


How do I render the 'user_picture' of a user account?

Just like every other render array, render it.

If you print it out in twig, that just works, in PHP, use \Drupal::service('renderer')->render().


FontAwesome tags removed when switching between Source and Wysiwyg

As Vic Nicethemer pointed out - the solution (for me) was to add &nbsp; within the <i> and </i> like so: <i class="icon-facebook">&nbsp;</i>.

CKEDitor removes elements that do not have any internal content...


How are .inc files actually utilised in a module?

There are multiple ways .inc files can be included.

Hooks in general should all be included in the .module file, as that is the only file loaded on every page load by default, and hooks should always be available. However, hook_hook_info() can be implemented, telling Drupal that the hook should be looked for in another file. For example:

function hook_hook_info()
{
  return array
  (
    // Tell Drupal to look in a different file
    // for hook_form_alter:
    'form_alter' => array
    (
      // Tell Drupal to look in MODULENAME.forms.inc
      // for hook_form_alter:
      'group' => 'forms',
    ),
  ),
}

Next, you can use hook_menu() to look for a callback in an .inc file:

function hook_menu()
{
  $menu['some/path'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $menu;
}

The same can be done with hook_theme():

function hook_theme()
{
  $themes['some_theme_hook'] = array
  (
    ...
    'file' => 'includes/some_file.inc',
  );

  return $themes;
}

.inc files can also be directly included with module_load_include():

// The extension is given in the first argument, and
// left off the last argument:
module_load_include('inc', MODULENAME, 'includes/some_file');

Though in forms, form_load_include() should be used rather than module_load_include():

// The extension is given in the second argument, and
// left off the last argument:
form_load_include($form_state,'inc', MODULENAME, 'includes/some_file');


If you are on shared hosting your hosting company should be responsible for keeping the time correct. If that's not happening contact them and ask why. If you are on VPS or your own private server you can set up a NTP client as tostinni recommended.


Overriding template without killing the page?

Because the Node Edit page is a form, it is recommended that you use hooks for theming it.  You can create custom template file for it, but theming it within template.php is the most common solution.

Theming Node Forms in Drupal 7 is the best resource I've seen so far for this.


How to check in a Rules Condition if a specific value of a multi-value field is selected?

I ended up creating a "Check a Truth Value" condition with the Rules module. The code below is the one I used.

if ($node->field_area_51[0]['value']) {
  foreach ($node->field_area_51 as $key => $value) {
    if ($value[value] == 'b') {
      return TRUE;
    }
  }
}


How do I get a double top boostrap nav with bootstrap template?

You can create a region in yourtheme.info or use Block Group Module.
If you're using Bootstrap theme for Drupal, you can simply write code for your Top Links Navbar in page.tpl.php and use CSS to design it as you wish. Now in the template code, include your navbar if not empty:

if (!empty(primary_nav)||!empty(top_links)||!empty(user_nav)||!empty(navigation))
{ //..Code to include your top_links navbar .. /}

You can also hard-code your menu in page template of your theme but it's not the best practice.

Plus: Always use the child theme.

If you want to add hamburger menu then use JQuery pluggin for same and remove the default responsive behavior of bootstrap from the menu you want to display hamburger on smaller screen. I advice JQuery plugin as it's open source, clean and very beautiful.

Play here.


Can we pass argument to a form from a Twig template

I think the most elegant way is to modify your controller so all the logic happens in the controller and only the markup in twig. If you have that option that's the way to go.

That being said, there are ways to get what you want.
The most convenient way I know is the twig_tweak module and use the function

{{ drupal_form('yourmodule\\namespace\\Form\\yourForm', sourceid) }}

I have not tested it myself but it should work.


Webform theming field labels through webform-form.tpl.php

You can simply hide the label from date field setting and add like this :

  Label here

    <?php print drupal_render($form['submitted']['birthdate']['day']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['month']); ?>
    <?php print drupal_render($form['submitted']['birthdate']['year']); ?>


Month and year to display based on content post date

You haven't explained the context of this date. Is it representing results coming out of views like "this post was 5 days ago" or do you just want todays date on the upper right?

This will print the current date on your theme template.

<?php
echo date('Y M D');
?>

Share some more info on what this date is giving the user exactly; Drupal has some very helpful code for this kind of thing, such as format_date().


How to not show user signatures in comments?

There is feature in admin panel of Drupal to disable signature option directly.
Follow the below steps:

Go to admin/config/people/accounts (admin > configuration > account
settings)
Uncheck "Enable signatures" checkbox under Personalization section.
Once finished, go down to the bottom of the screen and click the
Save Configuration button.


Module to turn on/off the whole block region

I don't have a single great suggestions. Here are a few things that come to mind.

Wrap all the blocks in a single block. This way you could make a few "block groups".
Just don't use the block system. It's not very good. My personal favourite block handling mechanism is Panels (Everywhere) and Page manager
Panels Everywhere is capable of killing the entire block system. A peek into it's codebase could probably reveal how to do it on a region by region basis.


How to programmatically publish/unpublished node using flag link and without using Rules?

Any module may react to a piece of content being flagged by implementing hook_flag(). Here is the relevant do so:

mymodule_flag($action, $flag, $content_id, $account) {
  if ($action == 'flag') { // Or $action == 'unflag'.
    // Do something in response to the flagging.
  }

  if ($flag->name == 'yourflagname') {
    //Your custom code to unpublish/publish the content goes here.
  }

}

Source: "Responding to a flagging", located within the Flag's community documentation.


I think it's because there is a problem in your template.php. Indeed drupal should save your file only temporarly. You have to save your file permenantly with this code

$file = file_load($form_state['values']['background_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);


I disabled the Organic Groups Field Access module and the missing fields appeared.

Related to the OG issue: https://drupal.org/node/1743332

In summary, for some users, disabling/re-enabling this module while clearing the cache resolved the issue.


Usually there are two situations: your hack may be useful for other users or your hack is very very custom and is not likely to be useful for other users.

In the second case you can go with arpitr answer.

If your hack can be useful for other users (like this case) you should open a new Feature request or bug issue in the module's issue queue where you can share your hack as patch to the module. This way:

Other people can evaluate and discuss your code and solution pointing out any mistakes or bugs you are not aware of, improving your changes.
Maintainers can commit your patch to the module so in next upgrade you don't lose your changes as changes are included in the new release.
Any ohter module's user can benefit from the new feature.

The drawbacks is that your code must fit the general usage of the module, so your feature should not break others module's functionalities or usages. This may imply more work but benefits are good enough.


I finally resolved it.
The hook is called during the indexing not during the search.


Comments not displaying for node that was added to a custom page

My suggestion is to use the default 'Basic page' content type to create page and allow comments there. If you need to have custom path for it, you can setup url alias.
Also for additional customization or theming, you can opt for node specific template.

I hope my answer applies to your situation :)


How to edit the label color for published or not published in Admin?

There are some ways to do that, one may be the implementation of the following preprocess function: hook_preprocess_views_view_table. Here is a code sample:

/**
 * Implements hook_preprocess_views_view_table.
 */
function my_module_preprocess_views_view_table(&$vars) {
  $view = $vars['view'];
  $results = $vars['result'];
  if ($view->name == 'my_view_administration_nodes' ) {
    foreach ($results as $row => $result) {
      $vars['field_classes']['status'][$row] .= $result->node_status ? ' published' : ' not-published';
    }
  }
}


There isn't a way to do this without writing your own formatters. However, could you open a feature request in the core issue queue as this is a worthy configuration option for the existing formatter.


How can I block an abusive person who endlessly tries to register more accounts?

Instead of trying to prevent the user from registering, which is a game for trolls and hackers alike, make the site annoying for him. Make him want to leave, as opposed to making him want to win the trolling game.

What I've done in the past, not specific to Drupal, is to let the user register. I then sabotaged his specific account:

I sprinkled if ($someuser) { sleep(rand($base, $base*2)) } in the code, where $base would increase daily. I made sure that he had lots of timeouts.
I would drop N% of his posts, where N started above 50% and only increased from there. If the post had certain keywords, it would be dropped immediately.
I would randomly drop CSS rules so the page would display poorly. Again, the severity would increase in time.

This required more effort on my part, but as per Sun Tzu's advice I was conditioning the user to hate my site. I wanted him to feel not that he was annoying us, but rather that he should be annoyed by the delays and apparent bugs. It took less than a week for him to give up on us.

EDIT: In the comments, user rooby mentions the Misery module which is based on the same concept:

Delay: Create a random-length delay, giving the appearance of a slow connection. (by default this happens 40% of the time)
White screen: Present the user with a white-screen. (by default this happens 10% of the time)
Wrong page: Redirect to a random URL in a predefined list. (by default this happens 0% of the time)
Random node: Redirect to a random node accessible by the user. (by default this happens 10% of the time)
403 Access Denied: Present the user with an "Access Denied" error. (by default this happens 10% of the time)
404 Not Found: Present the user with a "Not Found" error. (by default this happens 10% of the time)
Forms don't submit: Redirect back to the form during validation to prevent submission. (by default this happens 60% of the time) Note: Occasionally certain forms validate based on which button was pressed, this won't work in those cases.
Crash IE6: If the user is using Internet Explorer 6, this will crash their browser. (by default this happens 0% of the time)
Spam: Replace node content with a set word. (by default this happens 10% of the time)
Logout: Log the user out. (by default this happens 10% of the time)


Drupal prevents file save on chunked upload because of php.ini max upload size

Just a guess, but this may have something to do with max_file_uploads in php.ini. Perhaps chunking it counts as multiple files?


Drupal Less cache keeps generating cache file that does allow access to the apache server

I do three things.

I put myself in the apache group.
Set my umask and the httpd process to 0022
chmod sites/default/files to 2775

The first step lets me write to the directory. The second step makes sure that files I create have group write permission, and that apache does the same.  The third step tells the OS to always use the group of the directory owner.

You should then be able to drush cc all and have Apache create the LESS files.

For your initial fix, you may have to fix up the perms recursively. Eg,

chown -R apache.apache docroot/sites/default/files/
find docroot/sites/default/files/ -type d -exec chmod 2775 {} \;
find docroot/sites/default/files/ -type f -exec chmod 664 {} \;

I would also suggest reading Securing file permissions and ownership.  The comments have a good duscussion about the setgid bit and potential downfalls.


How to pass Javascript variable with form on submit?

Create a field for that variable, like this:

$form['_my_vars'] = array('#type' => 'hidden', '#default_value' => $_my_vars);

Whenever you are changing variable, update field's value.

Do not use

'#access' => FALSE

The Form API Reference clarifies it:

  when FALSE, the element is not rendered and the user submitted value is not taken into consideration.


How to get total number of results in Search API View?

So after a day, here's the result:

As J. Reynolds suggested, I finished up using $view->total_rows, but:

To populate $views->total_rows, you have to use a pager in your view - that was not an option with the attachments.
If you don't use a pager, you could force populating $view->total_rows by altering the View query before its execution like this:

    function mycustommodule_views_pre_execute(&$view) {
      $view->get_total_rows = TRUE;
    }

And after that you have that $view->total_rows!


I'm not sure you could easily implement ConfirmFormBase with the config form. It might be easier to turn your form into a multistep form and have step 2 with a simple submit button/message for confirmation rather than trying to implement ConfirmFormBase

That should achieve essentially the same thing


How to combine views exposed filter with search?

Finder module will do your requirement exactly, You can select taxonomy term as well as node title, body, fields, ..etc to perform the search.

  There are many ways to put together finder's functionality to get the
  sort of search form you need. There are also many hooks and theme
  functions allowing full customization of finder's output.

It is used for these purposes:

As a search tool to find a group of nodes or users.
As a way to navigate to a specific node or user page that matches criteria.
As an alternative to exposed filters for a Views module display.

See the below screen shot, In the finder field you can choose taxonomy terms as well as node body to perform the search in auto-complete exposed field, even you can perform multiple keyword search separated by comma. Read the Finder documentation for more information..

Once you added the element you can select the finder fields from the list, hold the

Ctrl key to select the taxonomy term as well as Node: Body


How to give to the creator of a node the option to hide the name of the author?

There are a few things in the original version of this question that really need review ...

  Content may add only authorized users on my site.

In Drupal you cannot have content that adds users, so I'm going to assume it's rather the opposite you're looking for, ie: "Content may only be added by authorized users on my site".

  I need to implement the functionality (option) of hiding a user name (author of сontent) if user wishes it.

Unless you have special customizations in place in your site, Drupal allows for multiple (authorized) users to author (change) content. So your "if user wish it" is a not clear enough: maybe you mean "the original author" (who first created the node), or maybe you mean "the user who last edited (changed) the content". For the sake of simplicity, I'm going to assume "the original author".

  That is, to make him/her "the anonymous author of" сontent.

If you agree with my above assumptions, here is a blueprint of how you could implement this:

Add a custom field to your content type, which is a boolean (true/false, yes/no, 0/1, whatever fits) that can be used when creating a node to have the original node author indicate if author should be shown (yes) or marked as "anonymous" (no).
Use the Rules module to ensure that the "Authored by" value always remains the "original node author" (who created the node). This basically ensures that attempts to change the node author (similar to what is suggested in codenext's answer) will be rejected. Only using Rules should be sufficient to implement this (rather basic) validation. But if needed (to further enhance these validations), add the Rules Forms Support module.
Use a preprocess function in your theme (similar to what is suggested in Zuzuesque's answer) to actually display the node author as requested by ... the original node author.

Note that if the original node author ever want to change his/her mind, that's still possible with this approach: just change the value of the custom field value as desired (after doing so, the logic in step 3. will ensure it's processed accordingly).


Show certain elements based on URL query string

You can create a hidden element called 'user' which can be prepopulated via the URL, then this hidden element can be used to conditionally hide/show other elements and even the submit button.

Below is the YAML source for a proof-of-concept.

user:
  '#type': hidden
  '#title': user
  '#prepopulate': true
customer_name:
  '#type': textfield
  '#title': 'Customer name'
  '#states':
    visible:
      ':input[name="user"]':
        value: customer
    required:
      ':input[name="user"]':
        value: customer
employee_name:
  '#type': textfield
  '#title': 'Employee name'
  '#states':
    visible:
      ':input[name="user"]':
        value: employee
    required:
      ':input[name="user"]':
        value: employee
actions:
  '#type': webform_actions
  '#title': 'Submit button(s)'
  '#states':
    visible:
      - ':input[name="user"]':
          value: customer
      - or
      - ':input[name="user"]':
          value: employee

Personally, I would change the 'user' from a hidden element to a select menu, just-in-case someone navigates to the form without any query string parameters, they would still be able to select the 'type of user'.


How do I hide a view's field based on role?

The most efficient way would be using hook_views_pre_view(), which allows you to alter a View at the very beginning of the process i.e. before any query is built/run and before any rendering takes place. You can remove the 'name' field handler from the View based on the desired logic.

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()->getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view->removeHandler($display_id, 'field', 'name');
  }
}

This solution assumes that you are only interested to serve this very specific use case - remove the field only from this specific View. Users might still be able to see the Display Names of users in other areas of the website.


why the search result shown in default language only ?

You should add a filter "Indexed node: language" and set it to "Current user language". This should be enough to ensure the results are shown in the current language.


use drupal's hashing in an external php fil

What you'll need is Drupal's password.inc file, located at: /includes/password.inc

Just copy this file to your project and include it in your custom php file. This way you can use the user_check_password() function (and many others).

here is a good example of something like you are trying to do in Laravel 4. http://www.goodbytes.be/blog/article/create-a-custom-drupal-7-authentication-driver-provider-in-laravel-4


set variable in user object Recommended practice

If efficiency is the goal, and your variables aren't too complex, you could take advantage of the data property of the user entity. It's stored as a serialised string in the {users} table and is available by default as part of the global $user object. As it's loaded from the database for any type of user load (even the bare minimum one) you can reduce the overhead to basically nothing.

The best example of how to use it comes from the docs for hook_user_presave():

function hook_user_presave(&$edit, $account, $category) {
  // Make sure that our form value 'mymodule_foo' is stored as
  // 'mymodule_bar' in the 'data' (serialized) column.
  if (isset($edit['mymodule_foo'])) {
    $edit['data']['mymodule_bar'] = $edit['mymodule_foo'];
  }
}

Then to retrieve the value at another point in code it's as simple as:

global $user;
$mymodule_bar = $user->data['mymodule_bar'];

Fields are great but as you know they do add overhead, so for small amounts of data I can't see any reason not to use the data property in this way.

I think using the variables table would get unmanageable quite quickly; you'd either end up with a different variable for each user, or having to store a single variable containing all users' data...neither of which are that desirable.


Execute cron job automatically after a specific interval of time in windows

Drupal supports two types of cron jobs:

Poormanscron

This is the default Drupal 7 cron, where at the end of a page request after a certain amount of time, hook_cron is called. This is controlled by the Run cron every ... setting at admin/config/system/cron.

This means that if cron is configured to run every 3 hours, the first user to visit the page after 3 hours will trigger cron. This also means on a low-traffic site that it can many more hours before cron is actually called.

Scheduled cron

This is a much more reliable method which does not involve the user. The principle is that the cron page is called from an external source (usually crontab on the server) at a set interval. As long as the server is up, it will run guaranteed every 3 hours.

In order to enable this, make sure to disable Poormanscron at admin/config/system/cron (set it to run never). And create a cron job (General and Linux manual).

In case of a Windows environemt, one can use Windows' built in scheduled tasks. Please refer to this manual page.

UPDATE
Be aware that the manual is a little outdated, since Drupal 7 the cron script is protected by a token (to prevent DDoS). So where you see to call http://www.example.com/cron.php, add your site specific token. This can be found on your site's status page and looks like this: http://www.example.com/cron.php?cron_key=xxxxxxxxxx.


After save empty cache of referenced node

You may specify any cache meta data directly in your Twig template. I suppose 'node_list' cache tag can help in this case.

{{ {'#cache': {'tags': ['node_list']}} }}

Another approach could be configuring views 'No results behavior' to show that link.


Views: how to enable Title Link per role?

Drupal 6 had a view node permission, but it was removed from Drupal 7 for some reason.
This module adds it to Drupal 7:
https://www.drupal.org/project/node_view_permissions

If only the administrator and staff have the view node permission, only they should see the link in your view.

This of course will also only allow administrators and staff to view the node page too.

You could also create a template for that view field.
In the view settings, under advanced, there should be a 'theme' link. Click it to see what your field theme file should be named.


The libraries YAML file is not correct. In YAML, indentation matters. Additionally, spaces should be used instead of tabs.

global-styling:
    version: 1.0
    css:
        theme:
            css/style.css: {}

global-scripts:
    version: 1.0
    js:
        js/script.js: {}


I recommend you try the Disable Breadcrumbs module.

  Disable breadcrumbs on a per node, per content type, or by path (any path) basis; Omitting the need to write additional code in the theme layer (template.php file etc..) to determine the visibilty of breadcrumbs on specific pages. This can be administered on node edit forms and from the content administration page (node operations) to select/unselect multiple nodes for enabled types.


Media module and views. Cannot make video image linked to node

Maybe you could try the File Entity Link module?  Here is a quote about it (from the module's project page):

Out of the box, the Media and File Entity modules attach media to entities using Fields but they provide no way to then display media in those fields as links to the parent entity. A common use-case for this would be a teaser view of a node showing an image linked to the node.
This very simple module adds an option to the "File Types" view mode settings to accomplish this (at admin/config/media/file-types/manage/image/file-display for images).


How to send form submitted data to paypal in Drupal?

I'm the maintainer of Drupal Commerce and of the Commerce PayPal module. I'm afraid your question is too broad to be answerable here, but for folks looking to solve the same issue, you should check out the code in my Commerce PayPal module. It provides a full integration of WPS, WPP, EC, and PPA / Payflow Link.

For general Drupal support, there are much better channels to pursue. I'd look into videos or books specifically focusing on the Forms API or just dive into module code like mine to learn through investigating working examples.


Drupal 8, how fix the error 'class not found' for custom class ?

Drop the "src" from your namespace and use statements. Wipe the cache after making that change.


Taxonomy Term Page is showing the same body for all nodes

Found the problem. Some poorly written jQuery was dynamically swapping out the body tags. Blerg.


You can run below queries on database to get your site online:

UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';


How to get the parent name if chid taxonomy term id is known?

Drupal 5.x: Taxonomy_get_parents()
Drupal 6.x: Taxonomy_get_parents()
Drupal 7.x: Taxonomy_get_parents()
Drupal 8.0.x: TermStorage::loadParents()
Drupal 8.1.x: TermStorage::loadParents()
Drupal 8.2.x: TermStorage::loadParents()


403 page when clicking on activation link in email

You have to give the right to anonymous role to view published content

your_domain/?q=admin/people/permissions

then, tick view published content


Why is my image with URL that links to external site in a custom block not showing?

Try using the full site url for the src tags.

Prepend return value of $base_url and the rest of your path leading up to the image to your src attribute


The problem is that you set your wrapper div in $form['price_form']['textfields'], but in the AJAX callback you are replacing it with the $form['textfields'] that does not have it defined. To be safe, keep these guidelines:

Never use the same identifier at 2 different depths of an form array, as it leads to mistakes. Be sure to set '#tree' => TRUE if you need to use identifier twice, to avoid conflicts.
In AJAX callback always return the same element you set '#prefix' => '
 on.
Be sure to only define each element once. If you are using

$form['price_form']['textfields'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => '',
);

to define element, don't reset it with $form['price_form']['textfields'] = array( later in code. Using array() creates new empty array effectively deleting everything set earlier. Write directly to it's members like this:

$form['price_form']['textfields']['#markup'] = t('Already exist');

Of course they are not set in stone, but don't break them unless you know why and what you're doing. In your case, you have 'textfields' twice, you are setting wrapper on one and returning another. That's why it only works once. Second time there is no element FAPI's AJAX is supposed to replace.


Drupal 7 - Multi Step Registration with save on end

As a clue, build a module and insert your form inside it, then set your form ['rebuilt'] attribute to TRUE in this way your form is saved in ['storage'] attribute in every step and you can get them via $Form_state variable.


Fatal error: Class 'SelectQuery' not found in /*/includes/database/database.inc on line 813

Check database setting in settings.php file. If database configuration is right then just clear the cache and rebuild registery.


Creating a shortcut to a listing of a specific content type or a set of specific nodes

You can do it with the Views module and some additional extensions.

The easiest way to do it is to install the Administration Views module (and all of its dependencies). It provides administrative lists just like you get from Drupal core, except they're built using Views.

Once you have that installed, go to /admin/structure/views. Clone the "Administration: Nodes" view provided by Administration Views, change the node type filter to be fixed instead of exposed, change the system path setting (eg. /admin/content/my-node-type) and save it.

That should be all - let me know if I messed a step or if something is unclear.


Caching strategy for a page that varies by IP

One approach could be to use a middleware to set a query parameter:

  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
    $ip = $request->getClientIp();
    if (Util::requestFromCampus($ip)) {
      $request->query->add(['oncampus' => '1']);
    }
    else {
      // remove the query parameter in case an off-campus user sets it incorrectly
      $request->query->remove('oncampus');
    }
    return $this->httpKernel->handle($request, $type, $catch);
  }

Set a priority higher than 200, so that it runs before the page cache. The page cache uses the url including the query string as cache key and so both versions can be delivered from cache, which is good for performance.

As example how to set this up see Drupal\ban\BanMiddleware.

If you use this approach you don't need the custom cache context anymore, you can use a context for the query argument in content that varies for off- and on-campus users.


Different home pages based on different conditions?

You could do this in settings.php and define $conf['site_frontpage'] from a server variable like $_SERVER['HTTP_HOST']. The same logic would allow you to set your $base_url(D7) or $settings['trusted_host_patterns'](D8) to the correct domain as well.


How can I change the author of a node before it is saved with hook_entity_presave()?

I added $entity->setOwnerId($current_user)  and that worked


Search box result => node add (searched string = node title)

This is probably because of not indexing the content after adding it. You can re-index the site by visiting http://<your-site-url>/admin/config/search/settings and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.


Workbench moderation and check permissions tab

You're not missing the permissions, just looking in the wrong spot. Log in as an admin user and head over to yoursite.com/admin/people/permissions. This is the main permissions management page which shows all permissions defined by all modules.

You'll see 'sections' of permissions defined by various modules. There will be 'Node' and 'Workbench Moderation' sections mentioned in the file you read, as well as the relevant permissions.


Can I display all token values available for my Drupal installation?

To see all the value a token would get, you should call the function that replaces a token with its value, passing a different value for its $object parameter.
Using pseudo-code, this is the code you should run:

foreach (get_all_nodes() as $node) {
  print token_replace("[termalias-raw]", 'node', $node);
}

"[termalias-raw]" is a token implemented by the Pathauto module that is associated with node objects.
This is the code contained in pathauto_token_list(), which is the function that lists all the token implemented by a module:

if ($type == 'node' || $type == 'all') {
  $tokens['node']['termpath'] = t('As [term], but including its supercategories separated by /.');
  $tokens['node']['termpath-raw'] = t('As [term-raw], but including its supercategories separated by /.');
  $tokens['node']['termalias'] = t('The URL alias of the taxonomy term.');
  $tokens['node']['termalias-raw'] = t('The URL alias of the taxonomy term.');
}

If you meant the list of all the tokens available, then that list is already given by the Pathauto module in the form that allows you to set the path alias for each entity supported by the module. To see it all you need to check each of the path alias types (e.g. user, node, taxonomy terms).


Once you have the file uri of the uploaded file, this stops being a Drupal problem and starts being a PHP problem.

You should take a look at SO for a full description.

What you are looking for is this snippet.

$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
  $zip->extractTo('/myzips/extract_path/');
  $zip->close();
}


I actually found the solution I was looking for here

I was close with what I was doing, I just needed to do the following...

Add contextual filter by Content:Title
Under "When the filter value is NOT available" Provide Default by Content ID from URL
Under "When the filter value IS available" Specify validation Criteria as PHP Code
Enter the following PHP code...

if (is_numeric($argument)) {
  $node = node_load($argument);
  $handler->argument = $node->title;
  return TRUE;
} else {
  return FALSE;
}

Click Save.


Add stock field to product display containing multiple SKUs

First, you will need to add an entity reference field to your line items. This will reference the product display node.

Then using Views Rules create a line item view with a "Rules Display"

For "contextual filter" add Order ID.
For "fields"

Add the quantity
Add Node ID (nid) of the referenced Product Display Page.

Now in your rule simply add a view loop and pass the Order ID as a parameter.

Inside the View loop:

Fetch entity from ID, pass the NID from the view result.
Do Calculate a value. Get the fetched entity quantity -  view result quantity
Set a data Value for fetched quantity field, calculated value.


How do I make the title field in views as the title of the block?

Add a contextual filter of type 'Content: Nid'.
Set 'Provide default value' to 'Content ID from URL'

Under 'When the filter value IS available or a default is provided' set 'Override Title' to %1.

That should do the trick...


Multi country page - avoid repeating content

With domain access module you can share content
and set content to show on only one specific domain name

i.e
Argentina.Spanish.com
Colombia.Spanish.com
Peru.Spanish.com
Chile.Spanish.com


Display a node counter, by specific content type?

Use the Count Nodes module.

  The Count Nodes Module counts total number of nodes created(published
  and unpublished both) in each content type. It provide a total number
  of blocks equals to the total number of content types created such
  that administrator can use one block for each content type.


Drupal commerce shopping cart pane empty for non-admin users

You may need to enable the permission for anon at Admin > People > Permissions

"View any product of any type"

You could try first

"View any [type] product"

but the former permission may still be required there.


How to get the Object based on File ID (FID)

You can use an EntityFieldQuery, e.g.

$field_name = 'field_something';
$fid = 123;

$query = new \EntityFieldQuery();
$query->entityCondition('node')
  ->propertyCondition('type', 'the_type')
  ->fieldCondition($field_name, 'fid', $fid);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // $nodes contains all nodes that reference the given file via field_something.
}


Is it possible to style the new node page?

You can style your node edit or add form by adding page--node--edit.tpl.php

or check here and here for more Suggestions.


How to exclude a module from being uninstalled during import?

This will only work with drush 10. So drush should be updated to version 10.
With drush version lower than 10, it will work only from the UI.


Which view do I have to use to make the order of the images random in Node Gallery Slideshow?

Under admin/build/views/list, look for node_gallery_gallery_image_views. Your probably looking for the 'view all image thumbnails' display here to have it randomize a full gallery. The current display order is based on your node gallery image weight so you'll want to remove these under 'Sort Criteria' (click the up down arrow icon to remove these settings).

After that, you want to add a sort order criteria, 'Global: Random' to have the results of the view sorted randomly.

Note: this will apply to all of your galleries since it is accepting an argument of the parent gallery node object. If you want this just to apply to one specific node_gallery, you'll need to clone the display first and adjust this argument.


If you want to have page specific menu system, you can create different menu blocks and put them appropriately.

Considering your example

Main menu is nothing but a menu block, so instead of using main menu block you can have two different menu blocks let say Menu block A and Menu block B

So in block configuration for Menu block A you will put the block visibility to show on "undergraduate" only and similarly put for Menu block b put it as "graduate"

Remember to put the menu blocks in same region as your main menu. You are just toggling menu block visibility on basis of URL.


user:role:add for email addresses in Drush 9/10?

Maybe there are better ways, but the following should work:
drush user-add-role "power user" $(drush user-information --mail=penguin@example.com --field=name)

You get the user name from the e-mail address using the user-information command.


Before paste the code you need to click on "Source" option.

See the screen shot


Drupal Internationalization / Translation

I don't know if I completely understand your question correctly, but I think there's some confusion. The Drupal translations from localize.drupal.org and the locale core module, will only help you translate the interface. If there's something missing or you want some custom translations you can always use: http://drupal.org/project/l10n_client - and to keep it up-to date: http://drupal.org/project/l10n_update

The i18n module allows users to translate the content into different languages, but it does not auto-translate. There are some modules that uses Google's APIs to auto translate but one violates Google's TOS and the other one will stop working when google pulls there translation API

http://drupal.org/project/gtrans
http://drupal.org/project/i18n_auto


List migrations separately but use single migration class

It sounds like you're trying to force a tool to do something it's not supposed to do. The migration tools drush migrate-status command only provides a high-level overview of the migration batch work associated with a migration (current state, migration source entities found, number of entities, migrated, etc.)

There is drush migrate-messages if you're wanting to inspect individual migrations that may have failed. But if you're wanting a super-granular, per-entity, view of each migration item then you're probably looking at building your own tool or debugging a migration as it's being processed.


in multi-site do you set base url for each sites settings?

To be more secure you should set the base url for each site, yes.

Setting this helps protect against a phishing attack where a malicious user manipulates Drupal's use of the host request header to make the site provide incorrect links.


Image style settings for scaling an image

Have you tried the Scale and crop option ? Go to admin/config/media/image-styles/add add a new style and then select Scale and crop with, for example, 100px width and height. This will produce some square thumbnail with 100px sides.