You could try something like the following:

Custom content type 'location' with the fields you need for your locations
Consider addressfield if these are address locations, or geofield if not
if you need mapping, consider leaflet
To use/display these locations elsewhere, you could add an entity reference field to other nodes or entities, and populate the field with links to the required location(s).
if you need to embed locations (e.g. in the body of a node ) perhaps node embed or advanced entity token (I've not used either one)
If you need to add additional view modes, you can use display suite or entity_view_mode

So, the general idea is that you define locations as needed using a custom content type. Then you attach these locations to other nodes/entities using fields or by embedding using a module that uses tokens or another special syntax.

With either approach, each location is stored just once, and the location is rendered on a page using a view mode that makes sense in that particular context.

To address your question about blocks specifically: you could indeed create blocks for company locations. To associate these blocks to pages/nodes, you could either embed the block in a node with something like insert block (https://drupal.org/project/insert_block), or attach the block to a node using block reference (https://drupal.org/project/blockreference).


How do you handle long runtime updates needed in hook_install()?

My suggestion is to not make it automatic on install. Provide a page from where an admin can launch the batch job.

However, if it absolutely must be automated, I have a suggestion, albeit a some what crude such:

hook_init() {
  $run_batch = variable_get('NOT_INSTALLED_YET', FALSE);
  if ($run_batch) {
    // Redirect to batch launch, or possible just set an approprite message.
  }
}

hook_install() {
  variable_set('NOT_INSTALLED_YET', TRUE);
}


So what's happening is you're querying a database that you're not connected to.

db_set_active('default');

...that makes the active database the Drupal default (the one it was installed on, usually).

$query = mysql_query("SELECT * FROM news");

...that doesn't actually do anything.  That is a MySQL Library function (i.e. not part of the Drupal API), so Drupal doesn't actually interact with it.

Now, depending on what you're trying to do here, it's not clear if you're trying to query a table that's part of the Drupal installation or if it's a secondary, external table in a database you're trying to connect to... however, based on the logic you're using I'm going to assume the table is in the Drupal database.

If news is a table in the default Drupal database, then what you want to use is db_query, and the API information for it is located here https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7.  You can read about interacting with the Drupal database through the Drupal API there.

Here's an example I pulled from the Migrate module:

$query = db_select('migrate_example_beer_topic', 'met')
         ->fields('met', array('style', 'details', 'style_parent', 'region','hoppiness'))
         // This sort assures that parents are saved before children.
         ->orderBy('style_parent', 'ASC');

Notice you don't actually have to specify the database you're connecting to, it just assumed 'default'.

In fact, for that matter, you should install the Migrate module and go through the examples that it has.  They come with the module, and will be accessible under sites/all/modules/migrate/migrate_example.


How to get into a Drupal 7 site using only Drush without touching code or anything else?

What I did was change the default theme to the basic seven theme:

drush @mydomain.dev vset theme_default seven

Then reset your admin password:

drush @mydomain.dev upwd admin --password="mypass"

Then go and find a page that loads the seven theme and by default the seven theme has the login block somewhere in the footer area. Login with admin and your new pass! =D

If you have a theme switching module, you'll have to turn that off too. Such as themekey or rules or securepages (this is what was causing my issue.)


Adding a form to Views Bulk Operation for configurable operations

Instead of running a PHP script. You would have to create a custom module and a custom Action. The action may be configurable (requiring a Form) and you can check the form for errors before proceeding.

An example template of what would go into your .module file can be seen at ( am not the author):
http://dropbucket.org/node/841

In case that website is taken offline, here is the code sample, which I believe to be self explanitory:

/**
 * Implements hook_action_info().
 */
function custom_action_info() {
  return array(
    'custom_action_callback_name' => array(
      'type' => 'entity', // Can be file, term, user, etc.
      'label' => t('Your label'),
      'configurable' => TRUE, //  Needs config form
      'behavior' => array('view_property'), // Uses view access rights
      'triggers' => array('any'), // Works always
    ),
  );
}

/**
 * Return a form definition so the action can be configured.
 */
function custom_action_callback_name_form($context) {
  // Set default values for form.
  if (!isset($context['recipient'])) {
    $context['recipient'] = '';
  }

  $form['recipient'] = array(
    '#type' => 'textfield',
    '#title' => t('Recipient'),
    '#default_value' => $context['recipient'],
    '#maxlength' => '254',
    '#description' => t('The email address to which the message should be sent OR enter [node:author:mail], [comment:author:mail], etc. if you would like to send an e-mail to the author of the original post.'),
  );

  return $form;
}

/**
 * Validate custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_validate($form, $form_state) {
  $form_values = $form_state['values'];
  // Validate the configuration form.
  if (!valid_email_address($form_values['recipient'])) {
    form_set_error('recipient', t('Enter a valid email address.'));
  }
}

/**
 * Process custom_action_callback_name form submissions.
 */
function custom_vbo_action_send_node_submit($form, $form_state) {
  $form_values = $form_state['values'];
  // Process the HTML form to store configuration. The keyed array that
  // we return will be serialized to the database.
  $params = array(
    'recipient' => $form_values['recipient'],
  );
  return $params;
}

/**
 * Add action callback where you perform the action.
 */
function custom_action_callback_name($entity, $context) {
  // Do the magic here.
}

EDIT

If you just want VBO validation rules and no form for your action, look at VBO Validation which supplies easy to use Hooks.


Acquia Cloud provides you with a default .gitignore in your repository (as described here):

docroot/files
docroot/sites/*/files
docroot/sites/*/private
acquia-files

It usually is enough for the vast majority. You're however free to add anything you don't wish to keep under version control. There's no perfect setup and it really depends on what you'd like to achieve. I strongly suggest keeping settings.php under version control because it holds critical configuration for your site.


Is it possible to define a field as disabled on creation in field_create_instance?

No, fields don't have a 'disabled' setting by default.

You could however use hook_field_access to restrict access to editing them

/**
 * Implements hook_field_access
 */
function MODULE_field_access($op, $field, $entity_type, $entity, $account) {
  // Define read only fields
  $readonly = array('field_my_field_1', 'field_my_field_2');
  if ($op == 'edit' && in_array($field['field_name'], $readonly)) {
    // Disable edit.
    return FALSE;
  }
  return TRUE;
}


Confirmation Email from Webform Submission

This functionality is available out of the box with Webform.

On the webform node page, click on the "Webform" tab
From the webform tab, click on the "E-mails" tab
Click on the "Component value" radio button and select the component of the webform that captures the email address.
Click on the "Add" button
On the next page, you can set the Subject, From Address, From Name, and E-mail contents.


Generate hyperlink on each row for html table that contains database data

If you have custom code that generates the table then it should be easy to output the link to files as well.

I assume you are looking for info on how to get the link to the file having your file id from the database.

You will need this:
Given a File ID (fid) how can I get the HTML that represents that fid?

EDIT:
After you provided some sample code I was able to figure out what you need:

You need a slash in front of drupal.

<a href=\"/drupal/sites/default/files/" . $data->FileName . "\">


When taking a copy of the node template do you need to maintain the article tag that is in there

Actually you're free to edit templates !

The theme's css might depend on some tags, especially the article tag, so you could lose layout/design
If you're a forward thinking brave drupalista you definitely want to keep title logic and the possibility of rendering all fields (and comments) and respect the view modes ;)


How to change programmatically the link of a field in a View

I have finally solved using hook_views_pre_render and setting the display of one of the fields to "do not display", and adding as pure HTML around the field, replacing the content with the other field. In other words, by writing at low level the link of the field.

Surely there must be another way of doing this.


I need to load DB configuration dynamically in Drupal 7

Drupal allows you to override settings using the $conf[] array in settings.php. They will be then available via variable_get('key', 'default') in any module.

See 'defining site variables'
and variable_get()

The pattern we use is that any defaults go into install.php. starts with:

function hottopicsnotify_install() {
  variable_set(HOTTOPICSNOTIFY_CONTENT_TYPES_VAR, 'hottopics_node_form');

Override the variables with an admin form where needed. e.g.

function hottopics_settings($form, &$form_state) {

Read using variable_get. e.g.:

'#default_value' => variable_get(HOTTOPICSNOTIFY_EDITORIAL_CRON_KEY, ''),


Drupal 7. Custom pages for displaying data

Using hook_menu() should get you the the ability to create those three pages.  Then you can use the page_callback to display the data you are looking to show. For the subscribers/id, you can use %id and then have pass the argument to the page_callback.  Using the db_query(), db_update(), db_select() functions in drupal, you'll be able to add the custom processing of the database.

If you are creating your own module you can use theme functions to decide how the page and that data will display.


Different registration procedures (with or without approval) for different roles?

So, first of all, I'd like to refer to my other answer here, it's good to take a look

You are going to be needing to separate webforms, each with its own required fields, then after building our webform, in Emails \ Handlers section located at admin/structure/webform/manage/[WebformName]/handlers. We are going to enable our custom webform handler module.

  One thing that you need to make sure is correct, is the structure of
  the module folder, so that webform would read it as a handler, we
  assume the module name here is: webform_handler_user_creation so the
  structure would be something like this:
  webform_handler_user_creation>src>Plugin>WebformHandler>UserCreationHandler.php
  with a webform_handler_user_creation.info.yml file in the root of
  the module directory.

With all that said, here's an example of the module on my github page

So what we need to do first is to make sure we do create our users after saving the webform submission, then load the submission values and use them based on their machine names to fill in our user creation thingy, here's an example code:

<?php
namespace Drupal\webform_handler_user_creation\Plugin\WebformHandler;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;
/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "usercreate",
 *   label = @Translation("User Create"),
 *   category = @Translation("Action"),
 *   description = @Translation("Creates a user after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class UserCreationHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
        $user = \Drupal\user\Entity\User::create();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $user_name = $webform_submission->getElementData('user_name');
        // Mandatory user creation settings
        $user->enforceIsNew();
        $user->setPassword('testPassword');
        $user->setEmail('test@example.com');
        $user->setUsername($user_name); // This username must be unique and accept only a-Z,0-9, - _ @ .
        $user->set("langcode", $language);
        // Optional settings
        $user->set("init", 'email');
        $user->set("preferred_langcode", $language);
        $user->set("preferred_admin_langcode", $language);
        $user->activate();
        // Add a custom role
        $user->addRole('CustomRoleName');
        //Save user
        $user->save();

  }
}

So based on your use case, you can add the user with a custom role with $user->addRole('CustomRoleName'); and maybe activate it with $user->activate(); it or a lot other things. You will be needing two different handlers/module with different concept for each role, one for simple member profiles and one for student profiles


Setting field values according to user input in a custom form?

You should put node creating into form submit function. In your case it should be nodeform_my_form_submit. You can read more about it here under "Submitting Forms". Btw, you can use
drupal_get_form as page callback function and with that skip using separate function.


Getting data from a view to populate a select drop-down

Going off of argiepiano's excellent suggestions, this is what I came up with: a module that provides a block with the select box populated by the view.

/**
 * Implements hook_block_info
 */
function my_module_block_info() {

  $blocks['my_module'] = array(
    'info' => t('Puts the values of My Taxonomy Term view into a select box')
  );

  return $blocks;
}

/**
 * Implements hook_block_view
 */
function my_module_block_view( $delta ) {

  $view_name = 'my_taxonomy_term_view';
  $display_name = '';

  $content = '<select>';

  $results = views_get_view_result($view_name, $display_name);

  foreach ( $results as $result ) {
    $content .= '<option value=\'' . $result->tid . '\'>'
      . $result->taxonomy_term_data_name . '</option>';
  }

  $content .= '</select>';

  $block['content'] = $content;

  return $block;
}


How to configure the Total Subscription module?

The Total Subscription module has indeed some challenges related to finding out how to get it configured as it should be. Apart from its Community documentation (which you seem to have found already), the best I have found to far is a video tutorial (without sound though ...) that takes you through various admin screens. E.g. to show you some of the blocks related to this module.

Apart from that, to understand what this module is about, I find its readme.txt a bit helpful, as well as the module's project page. Here is a quote from it:

  Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.


No, that's not possible; Drupal doesn't have an interface for editing CSS out of the box.

You'll either need to get into the code, or install/develop a module like CSS Editor.


The problem turned out to be that the "aurora" gem cannot be installed alongside compass & compass-aurora for all this to work properly.


No, hook_menu_alter() is not thought to dynamically add new routes. As any similar alter hook, it is thought to alter the routes defined from other modules.
It would not work for dynamically adding new routes for the simply fact that, similarly to hook_menu() is only invoked in specific cases, for example, when a module is installed, uninstalled, enabled, or disabled.

If you need to have dynamic pages, you need to do what Drupal does for nodes: You define a route with wildcards, which is similar to the node/%node route defined for nodes.
hook_menu() has some example for this kind of routes, under Wildcards in Paths.

For example, a route definition as the following could be used to serve a page like my-module/1, my-module-2, etc. mymodule_abc() would recive the wildcard value as argument, and it could use that argument to access data from a database table, which is essentially what Drupal does when a user visits node/1: It loads the node whose ID is equal to 1 from the node table, and it shows it to the user who requested that page.

  $items['my-module/%'] = array(
    'page callback' => 'mymodule_abc',
    'page arguments' => array(1),
  );

As side note, as said in Auto-Loader Wildcards, instead of my-module/%, you could use my-module/%mymodule_abc, and mymodule_abc_load() will be called every time a page like my-module/1 is accessed, getting the wildcard value (1) as argument; it could then return the object saved in the database from the form submission handler.
See node_load() as example. That function returns the object saved in the database from the form submission handler of the node edit form.

Auto-Loader wildcards are helpful when there are more routes that your module defines. For example, the Node module uses them because the routes it defines using wildcards are node/%node, node/%node/edit, and node/%node/delete. Instead of putting the code to load the node in 3 different page callbacks, it puts the code in a single function (node_load()) automatically called from Drupal.


Drupal Commons notifications queue is not working

The most obvious thing would be that cron is not running. You can see the last time it ran by looking at the site status report, that will also give you a link to run it manually.


Node add form set entity reference default selection based on content from another type node

I suppose with

  set the form selection

you mean the default value of the taxonomy term reference field?

If yes, in the code above try this:

$form['field_topic']['widget']['#default_value'] = $term->tid();

Btw. you also want to change your implementation from MYMODULE_form_alter to MYMODULE_form_node_forum_form_alter, because the former hook will be called for all forms, whereas the latter is just called when the forum node form renders.


Is it Inethical/Bad Practise to create a custom table and save content instead of using drupal fields?

Not at all. It's up to the developer and the needs of the site. Setting up a field to tie in  with the Field UI has a lot of benefits - it makes the field reusable on different entities, and allows it to be altered and manipulated as necessary. But it also adds a lot of overhead, and if you have to code your own fields, it adds time. If you know your data is to only be used for a single-case situation, then often it can be better to set up your own table and APIs in order to make the code more lightweight, and quicker to develop.

It's a case-by-case situation really.


Changing the layout of user profile edit page

I had to do this in the past and I went the module route.

Using Display Suite, Renderable Elements and Field Group I was able to fully change the layout of edit forms.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. Screencast

  Renderable Elements enables you to register any forms and manage the
  display through an UI. It will also make (additional) elements
  available of existing entities on the manage forms/display screens or
  you can for example register the contact form and rearrange the fields
  through Field UI. Screencast

  Field Group will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Edit: Also using Display Suite, you can add different views or blocks directly as fields to your node. So pulling fields from other entities shouldn't be a problem if you are good with views.


'300,000' isn't a number, it's a string. If you run

print (int) '300,000';

You'll get "300" as the response. '300.00' is a number, which is why it's treated as one.

So your issue isn't with Drupal Commerce, rather PHP and your users' input.

You'll need to implement some validation to correct your users' input before Commerce uses it. You can either do this by adding an extra validation function to the form using hook_form_alter(), or with some simple Javascript attached to the input box(es).


How to prevent certain users from adding (for example, a Node) to bookmarks with Flag Module

I assume you use Drupal 8:

Flag action handled by \Drupal\flag\Controller\ActionLinkController::flag so i think you should override this to check on your user and prevent to flag bookmarks nodes:

Override ActionLinkController controller using RouteSubscriber like the following:
Add the following to YOUR_MODULE_NAME.services.yml

services:
  YOUR_MODULE_NAME.route_subscriber:
    class: Drupal\YOUR_MODULE_NAME\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Create YOUR_MODULE_NAME/src/Routing/RouteSubscriber.php

<?php
namespace Drupal\YOUR_MODULE_NAME\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Change the route associated with /flag/flag/{flag}/{entity_id}.
    if ($route = $collection->get('flag.action_link_flag')) {
      $route->setDefault('_controller', '\Drupal\YOUR_MODULE_NAME\Controller\MyCustomActionLinkController::flag');
    }
  }

}

Create your new Controller YOUR_MODULE_NAME/src/Controller/MyCustomActionLinkController.php like the following:

namespace Drupal\YOUR_MODULE_NAME\Controller;

use Drupal\Component\Utility\Html;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\EntityInterface;
use Drupal\flag\Ajax\ActionLinkFlashCommand;
use Drupal\flag\Controller\ActionLinkController;
use Drupal\flag\FlagInterface;

class MyCustomActionLinkController extends ActionLinkController {

  /**
   * Performs a flagging when called via a route.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param int $entity_id
   *   The flaggable entity ID.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|null
   *   The response object, only if successful.
   *
   * @see \Drupal\flag\Plugin\Reload
   */
  public function flag(FlagInterface $flag, $entity_id) {
    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $this->flagService->getFlaggableById($flag, $entity_id);
    $uid = \Drupal::currentUser()->id();
    // Do your check here i just test with the user admin.
    if ($uid == 1) {
      // Change the message you want to show
      $flag->setFlagMessage("Sorry you don't have right to bookmark this");
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
    else {
      try {
        $this->flagService->flag($flag, $entity);
      } catch (\LogicException $e) {
        // Fail silently so we return to the entity, which will show an updated
        // link for the existing state of the flag.
      }
      return $this->generateResponse($flag, $entity, $flag->getMessage('flag'));
    }
  }

  /**
   * Generates a response after the flag has been updated.
   *
   * @param \Drupal\flag\FlagInterface $flag
   *   The flag entity.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity object.
   * @param string $message
   *   (optional) The message to flash.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The response object.
   */
  private function generateResponse(FlagInterface $flag, EntityInterface $entity, $message) {
    // Create a new AJAX response.
    $response = new AjaxResponse();

    // Get the link type plugin.
    $link_type = $flag->getLinkTypePlugin();

    // Generate the link render array.
    $link = $link_type->getAsFlagLink($flag, $entity);

    // Generate a CSS selector to use in a JQuery Replace command.
    $selector = '.js-flag-' . Html::cleanCssIdentifier($flag->id()) . '-' . $entity->id();

    // Create a new JQuery Replace command to update the link display.
    $replace = new ReplaceCommand($selector, $this->renderer->renderPlain($link));
    $response->addCommand($replace);

    // Push a message pulsing command onto the stack.
    $pulse = new ActionLinkFlashCommand($selector, $message);
    $response->addCommand($pulse);

    return $response;
  }
}

Notes:

You may need to do the same the route flag.action_link_flag_nojs.
I reimplement the method generateResponse because it has a private visibility.


During a Drush pm-uninstall, is there a way to see what sql queries were run?

You could try to adapt the devel query log as Letharion suggested, but that would involve some coding.  I have done similar things (for a different purpose) by using the Mysql General Query Log.  This requires restarting mysqld with an additional parameter, but beyond that minor inconvenience, works pretty well and shows you absolutely everything that's going on with the database.


How can I hide the entity ID on an autocomplete widget?

You should have a look on Chosen module.

  Chosen uses the Chosen jQuery plugin to make your  elements
  more user-friendly.

Follow this steps:

Install, enable and configure the Chosen module.
Change the widget type of your field to "Select list" at Manage Form Display of your content type
Check "apply chosen on this field" at Manage Fields > Edit of your field


Add the "Node ID (nid)" field
Add the "Comment count" field -> Configure field -> Rewrite results -> Output this field as link -> in the "Link path" enter: node/[nid]

You can hide the nid field as you probably don't need it.

Make sure the comment count is coming after the nid. You can just reorder them.


Why are two database tables (node and node_field_data) used for node data?

To add additional information to @jaypan's answer following are my observations

node_field_data contains 6 fields

nid     int(10) unsigned
vid     int(10) unsigned
type    varchar(32) The ID of the target entity.
status  tinyint(4)
title   varchar(255)
uid     int(10) unsigned    The ID of the target entity.
revision_translation_affected   tinyint(4)NULL

the nid is primary key in this table and referred by node and other fields as target id.
The type attribute tells what kind of content it is referring to, like posts, article or custom. In case of custom, it will store the name of the content type.


You can try adding '#return_value':

foreach($my_array as $key => $value) {
      $form['custom_field'] = array(
        '#type' => 'checkbox',
        '#return_value' => $key,
        '#title' => $value,
        '#default_value' => variable_get('custom_field'),
      );
    }


How to add custom price for custom line items added using commerce customizable products?

I havent found anything for line-items per say, but found this module that might work

https://drupal.org/project/commerce_pricing_attributes


What is the proper way to style pages in a new installation of a drupal theme?

Both or either are just fine, it really depends on what you want to achieve.

Panels will give you a UI in which you can move sections of the page around, but you will still need template files for the layouts if you don't want to use the standard ones.

Rearranging a template file is fine, but much less extendable via the UI.

In short, it's a matter of choice.  I recommend trying both and seeing which fits your needs best.

Also, check out Omega 4.x, it's a beast of a theme with some extra layouts built in and a pre-built gemfile so that you can use SASS if you want.


Views, find content types with field NOT IN other content type

Well, maybe it is idiotic, but finally I understood the issue with the relationships and the "referenced vs referencing"

So, what I did was:

relationships : "Content referenCING Content from A_REFERENCE_IN_B"
Fields A (the fields you want)
Filter type = Type A
Filter NID (using the relationship) , is null.

Amazing, and super fast.

The important part is REFERENCING not referenced.

Thanks.


How to print user role id with dynamic variable of language?

You're using $lg inside single quotes ('), because of which PHP is considering it as static text. If you want to use variable inside quotes, use double quotes ("). Check this ans for more details.

Try below code, to print role based on language:

<?php
global $user, $language;
$user_fields = user_load($user->uid);
// $lg = $user_fields->language;
$role = (!empty($user_fields->field_role[$language->language]) ? $user_fields->field_role[$language->language][0]['value'] : $user_fields->field_role['en'][0]['value'])
echo $role;
?>


Accessing Drupal REST endpoint using Oauth 2 token

Just follow the steps given in https://dev.acquia.com/blog/decoupled-drupal-authentication-oauth-20, once you get the access token in postman you will also see tokens for the user details you have given at admin/config/people/simple_oauth/oauth2_token.  Just copy the access token from postman and add it to Access Token field of Authorization tab(New version of Postman) by selecting Type as oauth2 (Dont't use the access token from the path given above).

Also make sure in permission page under RESTful Web Services section you will see your custom api listed and permission for authenticated user was given.

I followed the same and it worked for me.


Sure,

Install the features module and then you go to structure -> features

Click on "create new feature"

Give it a name and then on Edit component you can select what you want to export.
Select Content-type: node and you will see a list of all your content types, check the content types you want to export,( when you click the checkbox, you will see the ajax image wait till it disappear) and then click on download feature.
Version 7.x-2.x has got a better UI and it's possible to download it straight into your sites/all/modules/features folder if you give web server permission to write into that folder.

The feature you downloaded works like a module so upload the folder you downloaded into sites/all/modules/features, go to you module page and enable it.

You will find your content type with all the fields.

I suggest you to play with features module to understand all his potential.


print_r($variable) does not return anything useful, it just outputs text (which it does successfully, so it returns boolean TRUE [which is rendered as 1 when printed]). Your drupal_set_message basically does something like echo ($string . $boolean . $string)

Use print_r($variable, true) to return the output of the print_r to the calling function, instead of rendering it.

See https://www.php.net/manual/function.print-r.php


Add an extra class to views exposed filter “select” if default option is selected

Change the selector and class name to your needs, but this should work.

(function ($) {

  $("select")
    .change(function() {
      if ($(this).val() === $(this).find('option[selected]').val()) {
        $(this).addClass('default-value-selected');
      }
      else {
        $(this).removeClass('default-value-selected');
      }
    })
    .trigger("change");

})(jQuery);


Halt registration when certain conditions are (not) met

Do hook_form_alter for user registration form, and add extra validation function to the form using #validate like below.

$form['#validate'][] = 'extra_user_validation';

in function extra_user_validation set error after validation. So, that you can avoid the submit process and invoking hooks.

function extra_user_validation($form, &$form_state) {
   // Get the input values of registration form from $form_state['values']
   // Do validation & set error
}

That should work !


change field from int to big int in drupal

Use the bigint module.

  The default core fields do not include a bigint field. This module
  allows you to have a true BigInt (19) value. That means the number can
  contain 19 digits.

So, with this module you can define fields with the appropiate range.

Your problem now is to migrate data from your current field to a new bigint created field.

The usual steps will be:

Create and configure the new bigint field.
Edit affected nodes copying data form old int field to the new bigint field (using Batch API, for example). Or using a direct SQL commands, if your are brave enough.
Update related configuration to use the new field (for example, Views).
Delete de old field.

Depending on your usual workflow you can do this by different means:

Manually, closing the web during update.
Using Features for the configuration (fields, Views, etc).
Update script (for example, a hook_update_N if you are using a installation profile).


How to move block functions into .inc file?

The files directive is used to include files containing classes, check documentation.
You could include the file in the .module file.

require_once __DIR__ . '/includes/blocks.inc';

Edit: Included the other solutions added by @Beebee and @Jimajamma in the answer:

require_once  drupal_get_path('module', 'mymodulename') . '/includes/blocks.inc';
module_load_include('inc', 'MY_MODULE', 'FILE_NAME');
// This method is including a file residing in the module folder not in a subdirectory.


How to display translated options for list(text) fields with field_view_field()?

You can pass $langcode parameter in field_view_field function


How to convert a webform to a content type?

Unfortunately, there is no easy way to take a massive webform form and convert its form fields into a Drupal Entity + Fields. And yes when you want to re-architecture your website and do this for 50+ fields -- it sucks (been there).

Because some things like the Workbench module only work with things that are Nodes. And when you initially choose a webform to represent this data you've coded yourself into a corner.

This is kinda 1 place where Drupal is somewhat lacking -- interopability between similar tools (webform, entityform, entities, ECK, etc).

There are some tools to "move stuff around" such as:

https://drupal.org/project/bundle_copy
https://drupal.org/project/replicate

But they only work within 1 kind of architechure (Entities).


How do I create a summary that is grouped by years first and then months in Views using contextual filters?

In Views you can group results (e.g., by year), which can be found in the format settings. Within each group, the results are sorted according to your sorting criteria.

Although not exactly the same question, I think the answer of Views: how to ASC sort the grouping field #1 and sort DESC its content? is still applicable to your question.


You can use Views Aggregation to count the number of results for your specific cases.

Count number of nodes authored by a user

Since your results (to be counted) are nodes it makes sense to create Content type Views:

Create Content Views with Page Display and Filter out the node types you want to count later.
Add node Title field or Node ID under Fields to test you have the correct list of content. Add Author ID or Name to test the Contextual filter later.
Set Path to user/%user/stats, set Menu Tab so it displays under Drupal tabs on user pages
Add a Contextual filter Author UID (provide default value; User ID from URL) and test by entering user ID number into the Preview, make sure you see all the nodes created by the author with that UID
Under Fields make sure you only have ONE node field (if you have both NID and Title, remove Title). You can keep the Author fields, for testing if nothing else. We'll use one unique node field to count them aggregated. If we add another node field it will force Views results to show one node per Views row, which will make counting impossible
Remove Sorting criteria - they mess up Aggregation!
Turn on Aggregation
Edit the NID Field Aggregation setting to Count or Count DISTINCT (if you don't have duplicates in your Views results Count will do)

You now have Views counting the results! If you enter user UID into Preview you will see the number of their nodes in the NID field (adjust the NID field label accordingly).

If you enter all into Preview you will see a list of all Authors (from that nodes list, if you kept that Field) and the number of the nodes they created.

If you visit a user page you should see the stats tab added to Drupal tabs. Adjust the Permissions for the Views Page to limit who can see it.

Count number of comments authored by a user

Repeat the above procedure to count comments, only start with Commment Views Type, set a different Path user/%user/stats-comment and Menu tab

Count flags

To count how many of the listed nodes are flagged you'll need a Relationship to that information, then you'll be able to list a Field with the Flag status and use Aggregation to count them, similar to the above.

There are answers/articles on how to set up Flag Relationship in Views to display various information.


If you're just trying to display an RSS feed (rather that import the entries into your site's actual database and then show in a view), then I would use Feedburner, which will help you get the html code to publish any RSS feed.

Get a Feedburner account
Create a new feed to manage, using the feed's URL on the front page screen
Under the 'Publicize' tab, go to 'BuzzBoost' and activate that service at the bottom of the page
Once it's activated, you can get the embed code.  Just paste that code into a brand new block, and place the block whereever you want!

p.s. Further down that same page (the Publicize -> BuzzBoost page, I just cut off my screenshot too early), you can customize the feeds settings, such as should you display a date, and if so in what format, and how many characters of the post teaser to display, etc.  Play around with them to get the feed listing you want!


Contextual Links add destination=node to URL - can i restrict that from happening? - stopping delete functionality

The accepted answer is not entirely correct.  When hook_menu_contextual_links_alter() gets to act on the array of contextual links, no destinations have been set yet.

Instead, just a few lines after menu_contextual_links() (and so its alter hook) is called in contextual_pre_render_links(), there is this line adding the destination to the contextual link:

$item['localized_options']['query'] += drupal_get_destination();

If you set a query destination in hook_menu_contextual_links_alter(), the one you set will win.  But if you just want to get rid of the destination so for instance a redirect set in the form can do its thing (including, say, adding a fragment)... removing the destination before it is added here doesn't work.

This being Drupal, however, two lines later another alter hook is called:

drupal_alter('contextual_links_view', $element, $items);

(This is all in contextual module.)

So implement that hook instead.  For a module named example removing the destination from all node edit alter hooks on a given array of content type machine names available with the function example_selected_node_types(), the implementation would look like this:

/**
 * Implements hook_contextual_links_view_alter().
 */
function example_contextual_links_view_alter(&$element, $items) {
  if (isset($element['#element']['#entity_type']) &&
      $element['#element']['#entity_type'] == 'node' &&
      in_array($element['#element']['#bundle'],
               example_selected_node_types()))
  {
    $element['#links']['node-edit']['query'] = array();
  }
}


Turned on logging and saw Rejected-By-UrlScan next to the 404 errors.

Since our site is hosted in IIS, I needed to go into URLScan config, and allow colons, which are used by the Panels ajax func

C:\Windows\system32\inetsrv\urlscan\UrlScan.ini

; :   ; Don't allow alternate stream access


It is better to increase weight of your custom module for removing description of timezone field. Your code should be like below:

if($form_id == 'user_profile_form'){
  unset($form['account']['mail']['#description']);
  unset($form['account']['pass']['#description']);
  unset($form['locale']['language']['#description']);
  unset($form['picture']['picture_delete']['#description']);
  unset($form['picture']['picture_upload']['#description']);
  unset($form['timezone']['timezone']['#description']);
}


Display terms, username and user picture in a view block

There was a recent answer very much along these lines here that recommended the module Author Pane.  This module is extensible with hooks; might be the easier way for you to go as well.

  Author Pane is a block of information about a given user, like those typically found on a forum post, but can be used in other places as well. From core, it collects the user picture, name, join date, online status, contact link, and profile information. In addition, any module or theme can feed it more information via the preprocess system. All of this information is then gathered and displayed using a template file.


Field names returned in search snippet. How to hide?

There is usually a view mode for Search results, you can control the field label visibility settings there. See Admin >> Structure >> Content Types >> [Content Type] >> Manage Display >> Custom Display Settings. Activate the view modes for search and customize away.


Edit you node-type.tpl.php for this.

<?php
    foreach($node->taxonomy as $term){
            $term_classes[] = $term->name;
    }
?>

And print those classes in your node content wrapper.

<div class="content <?php print implode(' ', $term_classes); ?>">
    <?php print $content ?>
</div>


How to restrict a view to display only 2 content types?

Sounds like you need to set a filter type as well instead of just your contextual filters. So under filters choose "Content Type" and choose ONLY the content types you wish the user to see. Then the contextual filter set it to "No results found" (see screen shots)


How do I get low level data from the Flag module?

To get the total flagging count:
$count_service = \Drupal::service('flag.count');
$flag_counts = $count_service->getEntityFlagCounts($node);
$count = $flag_counts['my_flag'];

To get the current user's flagging status:
$flag_service = \Drupal::service('flag');
$my_flag = $flag_service->getFlagById('my_flag');
$user = \Drupal::currentUser();
$is_flagged= $my_flag->isFlagged($node,$user);

to toggle the flagging status:
if(!$is_flagged){
    $flag_service->flag($my_flag , $node);
}

or
if($is_flagged){
    $flag_service->unflag($my_flag , $node);
}

Best to wrap all of this into an if clause
if( $user->isAuthenticated() ){ ... }

It's probably easiest to just build my own URL / route to take care of the toggling to fit my needs.


Get fields to appear in fields list, arguments list and filters list in view

Instead of adding form element using hook_form_alter use CCK field. View will not understand your custom field but a CCK fields are integrated in views.

EDIT

Please check for Tag User module.


How to get value from field added in user settings

You can access global $user custom field values in the hook that suits you like this :

function your_hook() {
  global $user;
  $current_user = user_load($user->uid);
  $vars['account_type'] = $current_user->field_account_type[LANGUAGE_NONE][0]['value'];
}


Commerce, how to show 'view' of 100 products without speed/loading issues

As the commenters above indicate, there's nothing in particular that should be causing this slowdown. You'll want to look into what might be happening during the render phase of your View and see if some Views query caching and / or render caching might help. The challenge, of course, would be preventing double bookings of fully utilized time slots - but maybe you could easily invalidate the cache in those cases.

If anything is causing the slowdown, it could be price calculation across 100 products happening multiple times per pageload. Commerce by default runs price calculation to determine if an Add to Cart button should be enabled or disabled and also to display the calculated price to render on the product page. That shouldn't be coming into play if you're just rendering product entities directly - typically you'd only see that on the product display node, and you could easily prevent it by editing the Views field to simple display the price as loaded.

To check out what's happening w/ price calculation, you can simply enable the Rules log and see if it's firing off a bunch of rules and then figure out how to disable it. I think Views caching with some smart invalidation as products are purchased is the right thing.


Make GMAP api aware that the gmap has been resized

With regular GMaps API, you would need to reinitialize the map or trigger the resize event to start recalculation/replotting the map.

However, this seems to be a common problem for several users of GMap module and there were no direct answers 1 2 3 4.

This is one of the workarounds:

Go to admin/config/services/gmap and check collapsehack. This feature is supposed to be used when the map is in Drupal's collapsible fieldsets, but what it does is that it triggers map resizing on hash change. You can see this in the source code of gmap/gmap.js.
In your trigger add any hashchange - such as #open-map and #close-map.

Here's an example node content. JS/CSS are injected there just to give you an idea:

[gmap markers=blue::41.902277040963696,-87.6708984375 |zoom=5 |center=42.94033923363183,-88.857421875 |width=300px |height=200px |control=Small |type=Map]

Toggle gmap size

I tested this and it worked perfectly.


Seven Sub-theme shows Branding and Nav instead of Local Tasks / Admin Menu [8]

I think you need to copy the regions as well.  Here's the YML from our custom Admin theme.

name: MY Admin Theme
type: theme
description: 'My administration theme'
core: 8.x
base theme: seven
libraries:
  - my_admin/global-styling

regions:
  header: 'Header'
  pre_content: 'Pre-content'
  breadcrumb: Breadcrumb
  highlighted: Highlighted
  help: Help
  content: Content
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  sidebar_first: 'First sidebar'

ckeditor_stylesheets:
  - ../main_theme/css/style.css


Include cck text field and node id in your view's field list and then you can make your text field as link to node id.

Also for the filtration you can use contextual filters if required one is not available you can use relations.


Display Auto Generated Youtube Thumbnails with 'Video Embed Field' Module in Views

I only use the video embed field in views and have set the formatter to colorbox. I get the auto-generated thumbnails by default and on click of it, the video opens in a colorbox. You don't need to do anything else then this.


How exactly is it going out of hand? Unless you have some kind of maximum number of tables you're allowed to have, 100 tables aren't really a problem. It's like this because this is the only way support multiple values per field.

The field storage system is pluggable, you can for example also use MongoDB to store your fields. The advantage of that is that it can store a complete content type in a single "document" and retrieve it with a single lookup/fetch. The downside is, you have to manage/maintain a second database server (and be able to so, which you aren't on shared webhosting for example).

See also The truth about field storage in Drupal 7. As linked from there, there is also a Per bundle storage project, but development stopped. Looks like nobody cares enough about this to maintain that module.


Views out but can be changed at every stage of the process upto the field level.

You can check the theme information in the other section towards the bottom of the right vertical tabs. There you would see the list of theme templates you can use. The last one is where the fields get themed. and moving upwards each of the wrapping themes such as the row theme the entire page theme etc. The name suggestion are also there in the same place.

You can make the template as specific as you want.


Custom submit handler on form loaded via entity.form_builder

As per a comment from another user, the form is already processed after being returned by the form builder. That said, you can still alter values, but not add form elements or alter actions.

The solution for me was to do a form alter on the form before hand, and give it a submission handler, along with a hidden field. Then when I get the form in the code above, I now set the hidden field to contain a relevant value (Group ID). In my submission handler, I only proceed if that hidden value != NULL. This prevents me from doing anything on the core entity form which I do not want to affect.

Thanks for the hint 4k4!


how view count number vote fivestar on comment?

You can check this page at Drupal.org: Fivestar 7.x: Creating a User Comment/Rating and Average Rating for a Content type.

If you use the Fivestar voting module, your content will have own rating and reviews, and each contents each comment will have its own rating and review.


How to provide theme override for stylesheet conditionally included by a module

You can do this by implementing hook_css_alter as follows:

/**
 * Implements hook_css_alter().
 */
function mytheme_css_alter(&$css) {
  if (isset($css['tiles-styles.css'])) {
    $css['tiles-styles.css']['data'] = drupal_get_path('theme', 'mytheme')
                                       . '/css/tiles-styles.css';
  }
}


Importing node_revisions records from version 5 to version 6

Instead of trying some convoluted way of exporting and then re-importing the data and maintaining all meta-data - have you tried simply upgrading the site to Drupal 6?

This has been heavily documented on drupal.org

When you do a major drupal upgrade, so long as there is a drupal 6 module for your functionality, there will be update hooks that alter the database to convert it to the new schema.

This includes CCK, revisions etc


You can add the Term:ID and set the link to the term in 'rewrite results' as:

taxonomy/term/[tid]

If you want to keep the aliased URLs, you can use Global Redirect module.

  Once enabled, an alias provides a nice clean URL for a path on a site.
  However Drupal does not remove the old path (eg node/1234). The
  problem is that you now have two URLs representing the same content.
  This is dangerous territory for duplicate pages which can get you
  sandboxed by the search engines!


You have to create a little module and implement hook_form_FORM_ID_alter() to alter the form.


How to check if a user has privs to access a node in organic groups

The same function you should always use in any context: node_access('view', $node);

Modules are expected to use node access hooks to implement access control, so this function will consider all of the modules that may grant or remove access to the given $node object.


Identifying Community Modules vs. Custom Modules

I am unaware of any full list of modules that are on drupal.org for public consumption (there are a lot).  If I were you, I would do one of two approaches.

Based on https://stackoverflow.com/questions/6136022

cd sites/all/modules
for module in *; do
  echo -n $module
  echo -n ': '
  wget --spider --no-check-certificate -S "https://drupal.org/project/$module" 2>&1 | grep "HTTP/" | awk '{print $2}'
done

Lines that print out with a 200 exists; ones that don't should give a 404.

The other option is

cd sites/all/modules
for module in *; do
  grep 'project = ' $i/$i.info
done

Only modules on drupal.org will have a project line, which gets added by the packager script.

Also, if you visit the Available Updates page (admin/reports/updates) and check for updates, only public modules will be listed.


How Do i fix this in D8? there have been more than 5 failed login attempts for this account even flood table is not created in DB?

Drupal 8 still exited table flood. You can see here. Table flood created when use login failed. You can use the way in drupal 7. Simple

drush php-eval 'db_query("DELETE FROM `flood`");'

Full document.


Add a class to all the blocks in a region

As manikandan kannan is saying, you probably have the name of the region wrong. It probably is: 'content_bottom'

So your if-statement would become:

if($variables['block']->region == 'content_bottom') { ...


Short answer: Taxes doesn't exist.

Longer answer:
Taxes have not yet been implemented for Drupal commerce 2.x. You can follow along in the issue queue, git or IRC if you want to track the progress.

One of the relevant issue would be Tax data model.


The D7 equivalent would be:

$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');

foreach (db_query($sql, $args) as $result) {
  $names[] = $result->name;
}

Or if you wanted a structured query using db_select():

$variables = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE');

foreach ($variables->execute() as $result) {
  $names[] = $result->name;
}

n.b. the above are the most basic use of either of those functions. With some of the helper methods they get a bit more powerful.

For example, you're just looking for a single column of data from your query. The DB API can handle this with the fetchCol() method. So for the first example you can do:

$sql = 'SELECT name FROM {variable} WHERE name LIKE :name';
$args = array(':name' => db_like('csm_node_temp_') . '%');
$names = db_query($sql, $args)->fetchCol();

and for the second:

$names = db_select('variable', 'v')
  ->fields('v', array('name'))
  ->condition('name', db_like('csm_node_temp_') . '%', 'LIKE')
  ->execute()
  ->fetchCol();

In both cases $names will contain an array of the names found by the query. Much easier than looping over the results manually :)


geofield and leaflet maps: how to show proximity-originator on map?

If you are using geofields you can set up a proximity filter, and in your view filters, add the geofield proximity. In the settings 'source of origin input' try 'other geofield'?  Ty mapping the hotels and restaurants using two separate geofields, one for hotels, one for restaurants. Then map the restaurant distance from the hotels as origin>


How to add a value to the object group in group module?

Groups are fieldable entities, so you could add a field with a fieldname of, say, creation_date.

And if you'd then use the Rules module, you could create a custom rule like so:

Rules Event: After saving a new group.
Rules Action: Set a data value, i.e. to set the value of your creation_date field.

Note: If the field (like such creation_date field) does not show up within the Rules Action to be added, you may have to first add a Rules Condition like "Entity has field".


Just add a (boolean) field to the user.

  For new Drupal 7 site you can use:

  Admin > Configuration > People > Account settings > Manage fields
  Another method is using Profile2 module, a successor of Content
  Profile Drupal 6 module If you have started with a minimal install
  profile you will need to enable the Field UI module to access Manage
  fields via the Account settings.

Then, in a custom module, invoke hook_user_load and there, check if it's set. If not redirect to a page where the user needs to accept the terms and this field get updated.

Or, have a look at EU cookie compliance, it does more or less what you want.


How to browse the server to upload files from there in Drupal 7

****UPDATE****

Best option is to use https://drupal.org/project/imce_filefield
This is specially made to upload files to sites/default/files and add them.

Just configure imce and the field.

Uninstall file field sources, because it's not compatible to have them at the same time

Old anwser

You could use the FileField Sources module. To browse the server it looks like you need to use this with IMCE. From the FileField Sources project page:

The FileField Sources module expands on this ability by allowing you to
select new or existing files through additional means, including:

    Re-use files by an auto-complete textfield
    Attach server-side files uploaded via FTP
    Transfer files from a remote server (cURL required)
    Select existing files through the IMCE file browser

This question / answer was on another question:
Image Field Browser Option


Can I map to Body Summary in Feeds Importer?

Couple of ways of doing this using a dummy field. Create a dummy text field on the content type you are importing to. Then you could:

a. Use rules to move the dummy field into the body summary.

or

b. (preferred) Use the feeds presave hook in your own module to set the summary AND set the dummy field blank.

/**
 * Invoked before a feed item is saved.
 *
 * @param $source
 *  FeedsSource object that describes the source that is being imported.
 * @param $entity
 *   The entity object.
 * @param $item
 *   The parser result for this entity.
 */
function [YOUR_MODULE_NAME]_feeds_presave(FeedsSource $source, $entity, $item) {
  if ($entity->feeds_item->entity_type == 'node' && isset($entity->field_temp_summary['und'][0]['value'])) {
    $entity->body['und'][0]['summary'] = $entity->field_temp_summary['und'][0]['value'];
    unset($entity->field_temp_summary);
  }
}


Search taxonomy terms with node_search_execute()

Actually, the only missing part is the form field that should allow the users to select the taxonomy terms used from the nodes they are looking for. The code used from Drupal 7 (and Drupal 8) is still looking for the corresponding values in $form_state['values'].

If you look at the code used by node_search_validate(), the form validation handler added by node_form_search_form_alter(), you will notice the following lines.

  if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
    $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  }

If you then look at the code used by node_search_execute(), you will notice the following lines.

  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }

Effectively, the functionality of searching those nodes that use specific taxonomy terms has not been removed; it has been hidden to the users who don't have anymore a way to tell the Node module to which taxonomy terms they are interested. This seems rather unintentional; probably the feature was supposed to be completely removed, but the submitted patch removed just the code for the user interface. I cannot find the related issue opened on Drupal.org, and I cannot say if my supposition is correct.

Until the code in node_search_execute() and node_search_validate() is not changed, all you need to do is adding the form fields in the search form, keeping in mind that the Node module is looking for $form_state['values']['term']. (In other words, the form field added for selecting the taxonomy terms should be in $form['term'].)

If, and when, that code is removed, adding that form field would not have anymore any effect.
Drupal doesn't allow a module to alter how a module integrates with the Search module. As a matter of fact, Drupal uses hook_search_info(), but no hook_search_info_alter(); if you would want to extend how searching a node is done (for example, by adding more options), you would need to alter the page callback assigned to search/node and search/node/%menu_trail. See search_menu().


From the change record:

$name = $_POST['name']; // form param

becomes

$name = \Drupal::request()->request->get('name'); // form param

Incidentally, for GET vars, you would use:

$query = \Drupal::request()->query->get('name');


This sounds like the same question I asked here, and for which I got a "sorry, can't do" kind of answer:

How can I show a list of terms from a specific vocabulary that are not assigned to the current node

What you'd be asking SQL to do is check every term in the vocabulary to see whether it is assigned to the current node. The performance overhead of that is potentially huge (imagine a vocabulary with hundreds of terms, and a node with just one of those terms assigned).


pass argument through url and use it in exposed filters in views

Yes, you can do this with two views two views.

Create the first view for the the block showing the term ids. It should be possible to change the links the way the second view expects them. May be you need some PHP do achiev this.

With the second view you expect the term id as a filter and show the appropriate information.


How to use different sets of fields for unique pages like the home page?

In Drupal you can achive this using Paragraphs

  Paragraphs module comes with a new "paragraphs" field type that works
  like Entity Reference's. Simply add a new paragraphs field on any
  Content Type you want and choose which Paragraph Types should be
  available to end-users. They can then add as many Paragraph items as
  you allowed them to and reorder them at will.

You can create paragraph types, and these paragraph types you can add sets of fields.

Alternatively, if you just need this type of functionality for the home page only, then just create a block type /admin/structure/block/block-content/types and add fields to it and then create a block of your block type and assign this block to the home page only.


how to disable a class in migrate module

I'm currently using Drupal 7.22.

For my migration class, in my migrate_mypages.install file I have:

function migrate_mypages_enable() {
  Migration::registerMigration('MyPagesMigration');
}

function migrate_mypages_disable() {
  Migration::deregisterMigration('MyPages');
}

I haven't looked into the actual Migrate module, but it seems that when registering a migration in code, you have to use the full class name, whereas when de-registering the migration in code, you use only the name of your migration (machine-name).

If you are stuck with old classes, you can either add the de-register lines back in, and enable/disable your module, or, manually clear the class lines out of the table "migrate_status" in your database (as per Neograph734's comment).

As well, if you use drush, there is also:

drush migrate-deregister --orphans


Menu block makes parent menu item active when maximum levels not cover the linked node

If I understand correctly you need the Menu Position module. Using this module you can keep Parent Menu item active at any level of it's sub items.

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.


How to create a drop down field to categorize content when creating new pages?

The drop-down can be created as a Taxonomy.

The section pages can all be one View with a Contextual Filter for each taxonomy term.


Drupal ships with that functionality you are describing out of the box, I mean the comments entity. Can be administered -approved, published, deleted etc- under admin/content/comment and are fieldable (admin/structure/types/manage/%node-type/comment/fields) and themable (admin/structure/types/manage/%node-type/comment/display).

Don't forget the comment's API


You need to set path at config >> URL aliases >> patterns under that article patter you need to set something like.

content/[node:title]/[node:field_machine_name]

You can access with pattern url otherwise you can access by default with "node/nid".


How to run a cron queue programmatically?

For one of my project, this worked for me :-

$queue_machine_name = 'sync_product_list';
$queue = \Drupal::queue($queue_machine_name);
$queue_worker = \Drupal::service('plugin.manager.queue_worker')->createInstance($queue_machine_name);
$item_id = '123';
$queue_worker->processItem($item_id);


Automatically inheriting title for image

This is probably what you are looking for although it uses Media rather than IMCE...
http://webwash.net/tutorials/customize-media-module-image-display-drupal-7

Ok based on your comment I am assuming you have a directory on your computer called: 'images', that contains a bunch of files like 'image-001.jpg', 'image-002.jpg' and properties attached to these files ... on a Windows OS...

You can follow the instructions here: To export your 'images' directory and contents as a CSV (comma-seperated-values) file. This CSV-file can then be 'Read' by Drupal, and it will save you from having to re-enter properties attached to your images manually.

It's important to carefully format your CSV file in Excel  or whatever Spreadsheet software you are using (google docs is good at importing and exporting CSVs) so that there is at least one column with unique elements in it, e.g. Column 'Title' - > Image 001, Image 002, Image 003, etc...
Other columns can have headers that match the image properties, such as 'date created', 'copyright' etc...

You can then use the 'feeds' module to import this CSV to Drupal.
E.g. you can create a content-type 'Image' with fields that match your CSV's headers...like 'Date Created', 'Copyright' etc...

This question will probably help you in making the last stage happen...
https://www.drupal.org/node/1851322


Best way to redirect a page after javascript tracking code has executed

You can do something like below:

Create a custom module, If not already created (read more).
In your custom module, define a custom callback using hook_menu, and add a page callback.
In page callback function simply 'echo "script file/code"'. This will prevent Drupal from rendering various template files in your callback. NOTE:* If you use return instead of echo, Drupal will start rendering template files.
In your .JS file/code, do required tracking and re-direct user to another page.

Sample Code:

MODULE_NAME.module

/**
 * Implements hook_menu().
 */
function [MODULE_NAME]_menu() {
  $items['custom_url'] = array(
    'title' => 'Test',
    'page callback' => '_[MODULE_NAME]_callback',
    // Check required access.
    'access callback' => TRUE,
  );

  return $items;
}

function _[MODULE_NAME]_callback() {
  $jquery = base_path() . 'misc/jquery.js';
  $script = drupal_get_path('module', 'MODULE_NAME') . '/[MODULE_NAME].js';
  echo '<script src="' . $jquery . '"></script>
    <script src="' . $script . '"></script>';
}

MODULE_NAME.js

(function() {
  $(document).ready(function() {
    // Do your tracking here.
    console.log("Test");
    window.location.href = "http://example.com";
  });
}(jQuery));

Edit :

No worries, if you've not created a module before, you can follow steps given in How to Make a Simple Module with a Form and Menu Link to try how it works. The documentation is regarding creating a module which will define a menu callback and form.

Here you can find a detailed guide regarding Creating custom modules.

The code snippet I've provided above includes all basic code as per your requirement, except the tracking code which you need to write inside MODULE_NAME.js file. See the comment saying // Do your tracking here.


How to enable Rich text editor for content types

Follow these steps:

Go and write in drush command prompt-

sudo drush en ckeditor -y
Use full HTML format while editing the node as shown in attached
screenshot.


CKeditor not showing. 403 on ckeditor.config.js and ckeditor.styles.js

I worked this out. I found an .htaccess 'deny from all' file in the sites/all/modules directory. It must have accidentally got copied in there from the sites/all/files/private directory. I removed the file and ckeditor shows fine.


Request for new password when user login for the first time

Options to set a password

First of all, the very only way for any user to change their password, is using either of these approaches:

using /user/xyz/edit (with xyz = uid of the user), where there is an option to change your password. But: this can only be done for a logged in user (which assumes that the user succeeded in entering their (old) password).
using a "one time login URL", as further described below.

Requesting a new password

When you are not logged in, you can navigate to /user/password within your site (either for D6 or D7). That is where you will find the "request new password".

For a logged in user, in D7, who navigates to /user/password, you won't get the same "request new password" form however. Instead, you'll get something like so (your.name@yourdomain.com is the eMail Id to where the request new password eMail will be mailed to):

  Password reset instructions will be mailed to your.name@yourdomain.com. You must log out to use the password reset link in the e-mail.

eMail a one time login URL

You may also want to look at what is configured as email templates when new users are created (located at admin/config/people/accounts). Such as the template for "a new user created by an administrator". By default (in D7) that template looks like so (bold markup added here):

  [user:name],

  A site administrator at [site:name] has created an account for you.
  You may now log in by clicking this link or copying and pasting it to
  your browser:

  [user:one-time-login-url]

  This link can only be used once to log in and will lead you to a page
  where you can set your password.

  After setting your password, you will be able to log in at
  [site:login-url] in the future using:

  username: [user:name] password: Your password

So this one time login URL could be used by a new user. And if for some reason that URL doesn't work (anymore), then such user can still user  /user/password.

Variation: any user (such as an admin ...) can use that URL and specify the eMail ID of the new user who has to set a new password (the eMail will arrive at the new user ... if the eMail ID is correct).

Redirect on login when using a one-time login URL

One might consider adding links like /user/password and/or /user/xyz/edit (with xyz = uid of the logged in user) anywhere in your site (e.g. somewhere in your theme).

However, I'd use an approach using the Rules module to redirect on login when using a one-time login and password reset. How to actually do so (there are multiple solutions) is detailed in issue # 480584. Personally I'd go for a solution based on what is described in comment #37 of it.

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.

Use the Force password change module

Another approach might be to use the Force password change module (available also for D8 now, merci Jaypan!). Here are some details from its project page:

  This module allows administrators to force users, by role, individual user, or newly created user, to change their password on their next page load or login, and/or expire their passwords after a period of time.

  Features:

  Ability to force all users in a role to change their password.
  Ability to force individual users to reset their password from their profile edit page (user/[UID]/edit).
  Ability to set an expiry on passwords so that if users haven't changed their password within that time period, they will be required to do so.
  Ability to force all new users to change their password on first-time login (site-wide setting for all new users).
  Ability for admins to force individual users to change their password on first time login when creating a new user. (Note: If the global setting forcing all new users to reset their password is enabled on the module settings page, this checkbox will not appear as it is redundant).
  Listing of stats on the user edit page (user/[UID]/edit) showing:

  Whether the user has a pending forced password change.
  When the user last had their password forced to be changed.
  When the user last changed their password.

  Status page for each role showing:

  Password change details by user.
  The last time at which the role was forced to change the password.
  A form to force the password change for all users in that role.

Use admin/config/people/force_password_change
and enable  Force password change on first-time login (can also be configured for selected roles).


Move code from template file to custom module

I think you should go through the module developer guide.

You can use hook_preprocess_HOOK() in your template.php. So if your code was placed in the node template, the hook will be themename_preprocess_node($vars) and then you can check for a particular node type and create a variable like $vars['custom_variable'] = 'the query stuff'; and this variable will be available in your template.


Is it possible to use public:// for inline images (in text) to protect against changes in config?

Your issue is (currently) covered in the Drupal issue queue here against Core-8.2.x. This was committed to 8.2.x 4 months ago and I would imagine is in core - reading the issue should let you know which parts have been resolved.

I haven't found any non-core workarounds for this issue at present, the basic concept (from D6/D7 is an input filter to translate public:// URIs into canonical URIs when the content is rendered).

Issue Link: https://www.drupal.org/node/2666382

EDIT

It appears that only part of this change has been finalised, there is another issue suggesting that final resolution for this problem will occur with 8.3.x

Issue Link: https://www.drupal.org/node/2755223

It's possible (based off your description) that things are working as intended i.e. public:// values should be replaced with their canonical counterpart during the rendering. If this isn't the case I'd suggest following up with the second issue link above.


Feature stuck on Overridden - "Overrides" column empty, "Default" not

There's two possible reasons for this that I can think of: one is that the .info file for your feature is out of step with the other files. This can happen when you are creating or updating a feature and you don't wait for the little animated timer gif to stop before clicking on another option. It occasionally happens for other reasons, such if you do a git merge automatically with changes from another developer.

To fix this, you generally need to go through your .info file one item at a time and check it corresponds to the other files, so there are no items in any of those files that are not in the .info.

The other reason is if two features overlap in some way. If you have the same configuration item in two features, one of them will usually fail to revert. You may need to refactor your features to prevent this.


As the instructions say:

  To install Drush 6.x (stable):

composer global require drush/drush:6.*

Assuming you installed drush that way (using composer):

  To update to a newer version (what you get depends on your
  specification in ~/.composer/composer.json):

composer global update


EFQ SQL error when using filedCondition on two different taxonomy terms

If you check your error you will notice that your query is trying to look for a column named field_data_field_city0.deleted... , it appends a 0 to it. This problem occurs because the type of value you choose for that column in field query is not correct.

Can you check an confirm if field_city is a taxonomy type of field. If you can access your DB check the table field_data_field_city and check what is the name of last column.


Add a date field to your tip of the week content type.  That date field will indicate when the tip becomes visible on the site.  Order your view by date (descending), and filter out all entries where the date field is greater than the current date.

If you want to write some code, you can add a hook that runs when you submit the form, and, if you leave the date field blank, have it select the maximum value of the date field out of the database, add a week to that, and fill the date in automatically.


The simplest way is to use the Entity Reference module. You can add fields to your content type which are a reference to other entities, like taxonomy terms, nodes, etc.

Note:  You can combine it with field collection, but you need to understand that a field collection is not the same thing. A field collection lets you group fields so you can re-used them. For instance if you have multiple addresses, you can create a field collection with street, zipcode, city, etc. But in itself, it's not an entity. Entity reference lets you point from one entity to another.


i found out that the code above create automatically a link in the main help page, as long as the .info file indicate

  name: AMU HAL

and not

  name: 'AMU HAL'


Custom Gallery images showing in one column

Its has multiple ways to do that but I recommend you to do it with views.

Create a new views as block view and follow the following steps:

Add image field in fields
Add filter criteria
You can change the FORMAT of the views as you like (according to your requirement you should select Grid type) to display images in multiple columns.
Add a contextual filter with nid (node ID) field and set it like this
Save the views and go to admin/structure/block and enable your block
Don't forget to hide the image field in the manage display of Gallery Content Type, path is admin/structure/types/manage/CONTENT-TYPE/display

Image as Example

For more details, click here


The Master page is at item-view and the links of there point to
  item-details/[tid], the detail view is at item-details/[tid] for each
  item.

In reality the links on the master page shouldn't link to the details view, but just to the current page with /[tid] appended.


Calculate distance using Geolocation module

I've found a solution.

Getting the user location

I'm using the Browser API to get the user location in the frontend and then pass those parameters as query strings to my view, like ?latitude=xxxx&longitude=xxxx.

if (navigator.geolocation) {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 0
    };

    function success(pos) {
        var crd = pos.coords;
        // Send ajax request with crd.latitude and crd.longitude in query strings
    };

    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    };

    navigator.geolocation.getCurrentPosition(success, error, options);
} else {
    console.warn('Geolocation not available.')
}

Using the location to calculate distances with Drupal hook

Then, using the THEME_views_post_render(\Drupal\views\ViewExecutable $view, &$output) hook I check that $view->id() is the view in which I want to make the calculations and I get the data from the URL using the Drupal function \Drupal::request()->query->get('latitude'); (and longitude).

From that point, I decode the JSON variable $output['#markup'] and change the JSON objects the way I need to fulfill my requirements.

if ($view->id() == 'farmacias_perto') {
        $user_latitude = \Drupal::request()->query->get('latitude');
        $user_longitude = \Drupal::request()->query->get('longitude');
        $json_result = json_decode($output['#markup']->jsonSerialize());

        foreach ($json_result as $pharmacy) {
            $latlong = explode(',', $pharmacy->field_geolocation);
            $pharmacy_latitude = $latlong[0];
            $pharmacy_longitude = $latlong[1];
            $distance = distance($pharmacy_latitude, $pharmacy_longitude, $user_latitude, $user_longitude);
            $pharmacy->distance = round($distance);
        }

        $output['#markup'] = json_encode($json_result);
}

I used the distance function explained here.


Purpose of "rows" when adding Long Text field

Rows control the height of your text area for editors. It does not change how the data is stored in the database.


How to properly skip apostrophe in db_select?

There are a couple of points here:

Your Drupal query is wrong insofar as it wouldn't produce your example SQL. You don't need to add an expression, rather a where clause
Quotes are fun in MySQL (see SQL modes). Your default mode would appear to be ANSI_QUOTES, which means:

  Treat “"” as an identifier quote character (like the “`” quote character) and not as a string quote character.

Which explains why MySQL is trying to interpret the single quote as a column name. PMA probably sets a different mode per-query, so the same SQL works in that environment.

Taking those into account, this is more like what you're hoping for:

$query = db_select('corpus_text', 'n')
  ->fields('n', array('text_id', 'speaker', 'text'))
  ->where("REPLACE(n.text, '''', '') LIKE :search", array(':search' => '%' . db_like($key_search) . '%'))
  ->orderBy('speaker', 'ASC');

Which produces:

SELECT  n.text_id AS text_id, n.speaker AS speaker, n.text AS text
FROM
{corpus_text} n
WHERE  (REPLACE(n.text, '''', '') LIKE :search)
ORDER BY speaker ASC

Notice that the single quote is escaped with two single quotes, MySQL's way of handling this situation.


How do I update commerce product display nodes based on SKU (of the referenced product)?

Although an old thread, for the benefit of others looking, this could be done easily using views_bulk_operations (VBO). No coding required.

Install VBO.
Create a View of product display nodes.
Add a relationship to commerce product.
Add a batch update operations field to the View.
Enable the "Modify entity fields" option in the VBO field settings.
Add an exposed filter for the product SKU
Save
Use the batch update operation to check and set the relevant taxonomy term reference field.


This:

$form['subscribers_wrapper_container'][]["#tree"] = TRUE;
$form['subscribers_wrapper_container'][]['UCM_SUB'] = array(...

Can't be what you meant to do. You're creating two new elements there, one with only #tree in it.

Surely you want the tree on the outer element, e.g.

$form['subscribers_wrapper_container']['UCM_SUB']['#tree'] = TRUE;

for($i = 0; $i < $form_state['values']['number_subscribers']; $i++){
  $form['subscribers_wrapper_container']['UCM_SUB'][] = array(
    '#type' => 'textfield',
    '#size' => 30,
    '#title' => t('Subscriber IP Address'),
    '#required' => TRUE,
  );
}


i am getting "Error generating image." Files permission is 777 and gd library is installed

Check your image toolkit (URI /admin/config/media/image-toolkit). You must see like this


Permissions for adding bundles to custom entities

Writing in here, since its a faux paux to link to blog articles.

In your permissions.yml file of your module, you can define a permissions callback like so:

permission_callbacks:
  - Drupal\mymodule\MyModulePermissions::permissions

Then in your MyModulePermissions class:

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModulePermissions implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructor for MyModulePermissions.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity_type.manager'));
  }

  /**
   * Get permissions for MyModule.
   *
   * @return array
   *   Permissions array.
   */
  public function permissions() {
    $permissions = [];

    foreach ($this->entityTypeManager->getStorage('myentity')->loadMultiple() as $type) {
      $permissions += [
        'create ... ' . $type->bundle() => [
          'title' => $this->t('Allow creation of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'update ... ' . $type->bundle() => [
          'title' => $this->t('Allow update of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'delete ... ' . $type->bundle() => [
          'title' => $this->t('Allow deletion of %type', array('%type' => $type->label())),
        ]
      ];
    }

    return $permissions;
  }
}

Something like that. Code is untested. This will loop through and create CRUD permissions for each bundle.


Adding comments in Full content view mode happens, not through a link, but in the comment form that is displayed below the node (assuming it is set to be displayed in the content type's comment settings), but you need to switch on the Display comments checkbox in the Page: Row style options dialog.

You're right, Display links will print the add comment link in Teaser mode. If you have Full content mode and have both Display links and Display comments on, then you get both the link AND the form, which is akward. I don't know why it is that way.


One time URL doesn't re-direct the user to change the password

That's what's rpt does .. no ??

  (password fields in registration form will be hidden).

So with this module you won't be able to set a password manually i guess.


How to display a profile form using profile2 module

I did something like this recently. Since profile uses fields, this make things pretty simple. For the form you could do something like this:

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

  // Use field attach form and handle the fields yourself:
  field_attach_form('profile2', $profile, $form, $form_state);
  // Or use profile2 API which is simpler
  profile2_attach_form($form, $form_state);

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

Since all the profile form only is the fields that are attached to the profile, you can simply attach the fields yourself to the form, using Drupal core APIs:

field_attach_form adds the fields to the form.
field_attach_validate handles validation.
field_attach_submit to handles adding the values to the entity (profile).
Lastly you would need to save the profile entity using profile2_save.

After browsing the profile2 module code, I found that it provides a wrapper function to attach the fields to the form and save the form. This is simpler, but in doing so, you loose a little control. To use this you need to use the profile2_attach_form. Doing this will also handle the validation and saving of data.

To use the above code you should be able to c/p it, rename the form and replace profile_machine_name with the actual machine name of the profile you want to display the form for.


How can I add a second submission handler to a form to run after the default handler node_form_submit

All the methods you have mentioned should be calling your custom submit handler at the end. However check your $form array when the page is loaded to confirm your custom submit handler is at the right place.

If not try

MYMODULE_entity_insert($entity, $type) {

//Paste your secondary node creation code here

}

See https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_insert/7 for more details on this hook


How to pass same contextual arguments to two view blocks programmatically?

While rendering a view you can only use on display.
So it is only possible to loop through your display array and generate the view within that loop like:

          else {
              foreach (['block_1','block_7'] as $display) {
                $view->setDisplay($display);
                $view->setArguments([$term->tid]);
                // You need to render here.
                // The loop will overwrite the first display.
              }
            }


Drush needs a higher bootstrap level to run

This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.


Changing a form value or input field value during the submit handler

Just stumbled upon this and it's pretty dead so here's the answer in case OP still cares... turns out @Mołot is right.

The correct way to programatically change a form's submitted value is actually during validation and not during submission.

If you go back and re-read the documentation for form_set_value(), you'll notice that it explicitly says:

  Changes submitted form values during form validation.


How to organize better the taxonomy-selection drop-down box in Views?

You can use Hierarchical Select module to manage taxonomy terms in select list.

See this discussion to implement hierarchical select with Views module : http://drupal.org/node/1170192


In reply to your fix you posted in language_initialize. It's very strange that the first arg would be empty.

So now that you've added in your changes, http://www.hillsongconference.co.uk/se/home works.
However, this should be exactly the same as http://www.hillsongconference.co.uk/?q=se/home
and you will see that this brings in the 404 error (whereas q=/se/home doesn't).

So I'm worndering if the htaccess file has been edited?  As this is how Drupal converts the arguments in the url path to $_GET['q'].  The Drupal .htaccess file also strips out leading slashes, to insure the first argument isn't empty.

You've hacked core now, which is a terrible no-no.  Even if you are never going to update this site, it still needs to be fixed out of principle!

If you are running a nginx setup the correct rewrite (to not include the slash) is  rewrite ^/(.*)$ /index.php?q=$1  last; not rewrite ^(.*)$ /index.php?q=$1   last;


How can I print a text field's database value with devel so that it displays on all nodes?

Based on node.tpl.php, it says

  $node: Full node object. Contains data that may not be safe.

Things I noticed that's not quite right:

dpm() doesnt need to be used with print
dpm($node['content']['system_main']['nodes'][7533]['field_download_link']['#field_name']); wouldn't work since $node is an object.

Things to try:

Use only dpm($node); and see what's the output. If the field you're looking for exists then you can continue with manipulating its data
you could place the structuring of your link in hook_preproess_node() and just render it into your template file.


Adding an existing file to the File records

It may be easiest to create a special directory to receive these incoming files.
For example, if the directory is /var/www/sites/all/files/inbound then your code could do the following to scan the directory for new files and move them to the cms storage system:

  global $user;
  $new_files = (array) glob('/var/www/sites/all/files/inbound/*');
  foreach ($new_files as $filename) {
    $uri = file_unmanaged_move($filename);
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid = $user->uid;
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }

If you want to run this periodically then you can add the above to an implementation of hook_cron.


Joining 2 uids in custom table with users table

It will not be overridden. It will be another relationship. See the example at the API docs: https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7

See also the example here: https://stackoverflow.com/a/11103419/2467536


4 is definitely worse than 1. While \Drupal should be avoided to make unit testing and other things easier, it's still possible, but with calling functions, it's definitely not.

I fear there's no clear answer to this. There is no common standard for this in Drupal 8. A few modules have repository services, for example block.repository. You still have to manually inject that into your controllers, forms and other places, but you can make interfaces that are much easier to mock/test compared to an entity query.


Check if a panel page is enabled programmatically?

You can use

panels_load_display

Then check the disabled flag for page status.


Is it safe to use a custom value for users.status column

Why would you need to?

You can attach a boolean or numeric field to the user entity.

Navigate to Admin -> Configuration -> Accounts -> Add Field.


Trying to migrate user data into multi value term reference field

Use a callback with a separator to transform the source value to the destination value. For example:

  $this->addFieldMapping('statuut_nl', 'stat_id')
   ->separator(';')
   ->callbacks(array($this, 'computeValue'));

  protected function computeValue($value) {
    $allowed_values = array(
      2 => 'Postdoctoraal onderzoeker',
      ...
    );

    return ($allowed_values[$value]);
  }


Also might want to take a look at Taxonomy CSV import/export or Taxonomy import/export via XML