You need to implement hook_mail() in your custom module and then call drupal_mail() in your page callback function to get the result you want. You should save your table html in the $params array that gets delivered to hook_mail() and then set it as the $message['body'] value there (with additional html/data if needed). The linked tutorial and API pages should give you enough information and examples to work out the rest of the details.


Objects are passed by reference in PHP; therefore $node->nid is being set after your first go around the for loop. If $node->nid is set, no new node is created, so, I'd unset($node->nid) after each node_save() and give it another try.


In HTTP, links starting with http:// and including a domain name (e.g. http://example.com/foo/bar) is known as absolute paths.  On a Drupal site, they should only be used for off-site links.  Links not starting with http:// (e.g. /foo/bar) is known as relative paths. Relative paths should be used for internal links on your site. When a relative path starts with a slash (/) it is relative to the Drupal site root.  When it does not, it is relative to the location where it is embedded.

By making sure all internal links are specified using relative paths, they will not have to be changed when you move your site from one server to another.

For example, to link to /node/42, (provided you've clean URLs enabled) you can use the following markup:

 Link to node 42

(For menu items, as described bellow, you should omit the initial /, as menu items are always relative to the Drupal root.)

  Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

Support for this use case is already in place in Drupal.

Navigate to: Administration » Structure »  Menus and click on the link "List links" for the Main menu.  Then click on Add link.  In the field "Path" type in the relative path to the location (e.g. node path) in your site you want this menu item to point. Also provide meaningful "Menu link title" and "Description" strings.  End by clicking Save. Now the link will appear in your main menu, which in most (including the default "Bartik") themes are displayed at the top of all pages on the site.


"Drush sqlc < myfile.sql" doesn't return the site to previously working state. Are there files to be deleted?

The website encountered an unexpected error. Please try again later.

There was an error on PHP that Drupal couldn't handle.

If you have your install set to log errors, check the report.

Another option, on your settings.php add:

$config['system.logging']['error_level'] = 'verbose';

To show the errors.


Put this in a custom module and it will effectively remove User 1 from the People list, but only there.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  unset($form['accounts']['#options'][1]);
}

But as Free Radical pointed out, if you say why there might be better solutions.

Cheers,


How can I get the english node title printed on the translated nodes edit page.

Soluton

if($form_id == 'content_page_node_form') {
    $nid = (isset($form['nid']['#value'])) ? $form['nid']['#value'] : false;
    if($nid) {
        $node = node_load($nid);

        if($node) {
            $lang = 'en';
            $translations = translation_node_get_translations($node->tnid);
            $translated_node = (isset($translations[$lang])) ? node_load($translations[$lang]->nid) : $node;
            $translated_title = '
English Translation: ' . $translated_node->title . '
';
        }
    }

    $form['#prefix'] = (isset($translated_title) && $translated_node->title != $node->title) ? $translated_title : '';
}


Just create a view and list out taxonomy terms. Then display the view in front page.

Need to place view in page--front.html.twig.

Use Twig tweak module.

<dd>{{ drupal_view('view_name', 'page_1') }}</dd>

For Block

{{ drupal_view('view_name', 'block_1') }}


You can use the og_group provided by the OG module.

  // The id of the group to which you need to assign the nodes
  $gid = 123;

  // The node which should be added to a group.
  $node = node_load(1);

  $values = array(
    'entity_type' => 'node',
    'entity' => $node,
    'state' => OG_STATE_ACTIVE,
  );

  //Add the current node to the group using the funciton provided by OG
  $result = og_group('node', $gid, $values);


After a lot of trial and error, I realised that as long as the image goes through processing by Drupal, it's resolution somehow deteriorates during the process. As the issue with the site logo was a client complaint, I chose to bypass Drupal processing altogether by replacing site logo with site title, then applying text-indent: -9999px and background: url("../logo-image.png") to render the logo instead.


My implementation of template_preprocess_block() isn't working

The $variables['block_id'] variable is based on the number of blocks in a region (see template_preprocess_block(). If you want this for a specific block, despite what region it is in, you should be checking $variables['block']->delta == 10 instead.


WYSIWYG CKEditor is altering source text on reload. Why?

Simply because it makes no sense to print them. I'm sure they added this as a preventative measure to prevent people from writing bad HTML. There is no way to turn this off, for your own good, lol.

If you look at html.html.twig template file, where your CKeditor code will render is already inside the <body> tag, so it makes no sense to re-declare the <html> nor <head> nor <body> tags when they already have been declared.

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}  <--- YOUR CKEDITOR CODE WILL PRINT HERE...
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

  <script  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

For starters, Drupal 8 comes with jQuery, there is no need to add it, simply you just need to mark it as a dependency to your js file and then and only then, Drupal will load it. See How to include jQuery Once on your Drupal 8 pages

Loading scripts via CKeditor is considered bad practice. So the question becomes, how can I properly add the .css and .js bootstrap file?

Option A

Create a library file for your theme if it doesn't have one already

mytheme.libraries.yml

bootstrap4_cdn:
  css:
    theme:
      https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css: { type: external, minified: true }
  js:
    https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js: { type: external, minified: true }
  dependencies:
    - core/jquery
    - core/jquery.once

Note: In .yml files spacing matters, so make sure the indentation is exactly the same.

Then on your theme.info file add

libraries:
  - mytheme/bootstrap4_cdn

For better understanding, I encourage you to read Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

Option B

Use the bootstrap library module, which will add the library for you. (Basically does option A for you)

Option C (better yet)

If you want to create a Drupal 8 boostrap 4 theme, then you could create a Drupal Subtheme and use Bootstrap Barrio as your base theme.

Why a sub theme? Because themes are no different than Drupal Core or Contrib modules, if you hack them directly and then download an update for it, you will lose all your changes.


Acquia Dev Desktop, PHP 5.6 and SSL certificate issue on local MacOSX

After looking around I found kenorb's reply on a similar issue:
https://drupal.stackexchange.com/a/149456/62500

and after poking around the DevDesktop installed files on my Mac I managed to solve it.

The problem is the certificate file does not exist at the default location.

print_r(openssl_get_cert_locations());

Returns

Array (
    [default_cert_file] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/cert.pem
    [default_cert_file_env] => SSL_CERT_FILE
    [default_cert_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/certs
    [default_cert_dir_env] => SSL_CERT_DIR
    [default_private_dir] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/private
    [default_default_cert_area] => /Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl
    [ini_cafile] => [ini_capath] => )

So it is looking for cert.pem in the non existent directory "/Users/acquia/csbworkdir/dmitrybezer/libopenssl/install/ssl/"

To solve this, edit /Applications/[Dev desktop folder]/php5_6/bin/php.ini

and add these lines:

[openssl]
openssl.cafile="/Applications/[Dev desktop folder]/common/cert/cacert.pem"
openssl.capath="/Applications/[Dev desktop folder]/common/cert/"

where is [Dev desktop folder] is the name of your Dev Desktop folder.


You need to set your Exposed filter Selection type settings to Autocomplete instead of "Dropdown" you will get term names instead of TIDs.

Read more in part of this answer: How to use URL query parameter on a View Exposed Filter?

There is another way to do it: introduce the term information into the view through a Relationship so you can use the term Name. Read the steps in this answer: Get taxonomy name instead of id

That answer also mentions how you can "prettify" the URL: use the Query Parameters To URL module, it's being ported to D8.


Render Panels Overridden user profile template

I suggest you don't create a menu hook at all.

Just implement your desired layout in a custom panels page instead, and you can control the menu from there.


Help with a db_select() not returning results when it *should*

I'm not assigning $results->execute() to anything - that's why I can't iterate over the results.  Answer was provided by a local mailing list that I sent this link to.

So, solution is $results = $results->execute().  Of course, the query should be renamed to something like, $query;


Add/edit node auto share to social networks

I used the Janrain module for getting similar functionality. It allows you to integrate social networking logins, set up buttons for social sharing and a lot of other stuff. Its actually pretty easy to set up the module

Some other modules include - Socialmedia, social login If you are just looking for sharing - Sharethis


How to track which external link users who registered on my site came from

I believe StatCounter allows for this
http://statcounter.com/
http://drupal.org/project/statcounter

I believe what your asking for is against GA's TOS http://drupal.org/node/318974


Have you tried:

<?php
 dsm (array_keys(get_defined_vars()));
?>


Setting link field in menu content item as not required

To get this working in the form alter hook you need to set #required to FALSE in the widget:

$form['link']['widget']['0']['uri']['#required'] = FALSE;

The red asterix mark for a required field is no longer there, but the form does not validate. To get the form validated you would need to do this in the field definition. Implement a hook hook_entity_base_field_info_alter and set required to FALSE:

function mymodule_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'menu_link_content') {
    $fields['link']->setRequired(FALSE);
  }
}

But this doesn't help either, because there is code in the menu link content class that depends on $this->link, so even if you manage to pass the validation you get an error later, that the link is missing.


How to add a description to an image field?

To do that you'd need to add another column to the field type, which there's no native support for currently.

You're not alone in wanting this functionality (I'd definitely like it) and there is a patch that adds a hook_field_schema_alter() function to the field module, which you can use to add extra columns. I haven't tried it but the comments and tests on the above link seem to suggest it does work.

Bear in mind if you go down that route you'll also have to implement a few other alter hooks (hook_field_widget_form_alter() for example) so it's not a quick-fix.

If you're not up for patching core you might just want to use the Field Collection module to accomplish something similar. You can add a collection item containing an image widget and textarea widget to basically achieve the same effect (although there is some very slight impact on performance).


Change JSO(N) parameters that have been set by another module

You should try this

// Get all the current javascript information
$current_js = drupal_add_js(NULL, NULL, 'header');

// Filter the information down to just the settings.
$current_js_settings = $current_js['setting'];


Send Billing Information from Address Field to PayPal site using WPS

The user profile may not have the data saved to it yet, if it is a new user or if you allow anonymous checkout somehow, so it is better to retrieve this data directly from the order. To do that, we have to do some fancy footwork using the entity API - this also avoids any snafus related to database changes or translation arrays. I created a simple function that uses this API to extract an array of address fields:

/**
 * Helper to retrieve the profile from an order
 *
 * @param order
 *   The order object
 * @param type
 *   Either shipping or billing
 * @return
 *   The requested data
 */
function _my_module_address_from_order($order, $type="billing") {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $type = "commerce_customer_".$type;
  return $wrapper->$type->commerce_customer_address->value();
}

Then I call it thusly in the actual hook:

/**
 * Send default billing address to paypal
 */
function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $address = _my_module_address_from_order($order);
  $data['address1'] = $address['thoroughfare'];
  $data['address2'] = $address['premise'];
  $data['first_name'] = $address['first_name'];
  $data['last_name'] = $address['last_name'];
  $data['city'] = $address['locality'];
  $data['state'] = $address['administrative_area'];
  $data['zip'] = $address['postal_code'];
  $data['email'] = $order->mail;
}

Note that paypal will not display a billing address unless it gets all of the values address1, city, state and zip as well as first_name and last_name!

Much of this solution was arrived at from consulting http://www.drupalcommerce.org/discussions/756/load-address-order


How do I add a My Account Item to a New Menu?

/**
* Implementation of hook_menu().
*/
function mymenu_menu() {
$items['user/%user_uid_only_optional'] = array(
'title' => 'My account',
'title callback' => 'user_page_title',
'title arguments' => array(1),
'page callback' => 'user_view_page',
'page arguments' => array(1),
'access callback' => 'user_view_access',
'access arguments' => array(1),
'menu_name' => 'your-menu',
);
return $items;
}


I have a feeling with the access callback. Either your function is wrong (which you haven't posted) or something is up with your permission setting for this module.

Try temporarily updating your access callback to true to verify that it is causing the issue:

'access callback' => TRUE,

and clear your cache.

I think you may be better off creating a permission using hook_permission and using access arguments instead of access callback.

/**
 * Implement hook_permission()
 */
function myid_print_permission(){
  return array(
    'administer myid_print' => array(
      'title' => 'Administer myid_print'
    ),
  );
}

/**
 * Implements hook_menu().
 */
function myid_print_menu() {
  $items = array();
  $items['user/%user/myid_print_settings'] = array(
      'title' => 'ID Print Settings',
      'description' => 'Configuration options for the myid_print module',
      'page callback' => 'myid_print_admin_settings',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'type' => MENU_LOCAL_TASK,
      'weight' => -9,
  );

  $items['user/%user/myid_print'] = array(
      'title' => 'Print an ID',
      'page callback' => 'myid_print_user_page',
      'page arguments' => array(1),
      'access arguments' => array('administer myid_print'),
      'file' => 'myid_print.pages.inc',
      'type' => MENU_LOCAL_TASK,
      'weight' => -10,
  );
  return $items;
}


Infinit loop when I submit a form and redirect to this form with an additionnal parameter

If you want to redirect to the form page you need to do something like this in your submit handler:

$form_state->setRedirect('NAME_OF_THE_ROUTE_OF_YOUR_FORM', $route_paramters, $options);

Maybe you can insert your results by query parameters?! Or save them in a session so that they can be used again. But the $form_state->setRebuild seems to be smarter to me.


Getting a list of nodes of a specific type (eg, forum) via REST API

Services 3.x

You would use the parameters like this:
http://localhost/endpoint/node?parameters[type]=node_type

You can find out more how to use this by looking in the code (going off memory here):
File: services/resources/node_resource.inc
function: _node_resource_index


How can I show video and images in slideshow with lightbox style?

I achieved this some months ago... you can see an example in here http://www.entretierras.com/en on the left sidebar there is a block (slideshow) called "Our routes in pictures"

What we did:

First of all - New content type:
- Create a new content type. In my case I called it "slideshow sidebar"
- Add image field
- Add video field (see http://drupal.org/project/video_embed_field)
- The idea is the content can have an image or a video, but not both. (I control this by using Conditional fields module) Optional
- Create some nodes

Create an image style

Second - Create a view:
- Create a view. Block presentation. Showing content fields.
- Install Colorbox and Views slidehow modules. Colorbox is used for opening the slide in a lightbox way. Views slideshow is needed to create the slideshow.
- Add the fields you have created above.
- Apply a filter for the "slideshow banner" content type
- Select the format as slideshow and configure it as your requirements
- On every field (in the view) select the formatting as color box and aply the image styles you have created previously.

Hope this could help.


How to use feeds tamper to set default value from importer node?

Currently, there doesn't appear to be any core method of achieving this, either through Feed's Tamper or core Feeds Module.

There's a patch here, but I'm still looking for a core solution.


Add JavaScript files to the administrative pages

Using a module, you can follow two methods:

Implementing hook_init()
Implementing hook_form_alter()

The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

system_init() contains the following code, to add specific files to administrative pages.

  $path = drupal_get_path('module', 'system');
  // Add the CSS for this module. These aren't in system.info, because they
  // need to be in the CSS_SYSTEM group rather than the CSS_DEFAULT group.
  drupal_add_css($path . '/system.base.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

  // Add the system.admin.css file to the administrative pages.
  if (path_is_admin(current_path())) {
    drupal_add_css($path . '/system.admin.css', array('group' => CSS_SYSTEM));
  }

  drupal_add_css($path . '/system.menus.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.messages.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.theme.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

path_is_admin() is the function that in its documentation is described as:

  Determine whether a path is in the administrative section of the site.

Consider that some node-related paths, such as node/<nid>/edit, could be included in the administrative section, depending on the setting found on admin/appearance.

The list of the node paths that could be included in the administrative pages is returned from node_admin_paths().

  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;

If, for any reason, you need to avoid any page with a path like node/*, you need to add specific code to avoid those, if you are using path_is_admin(). Consider that any module could change the pages that are considered part of the administrative pages.

In both the cases, the alternative would be using a library, if the module implements hooks_library() with code similar to the following one.

function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');

  $libraries['mymodule.library'] = array(
    'title' => 'MyModule Library',
    'version' => '1.0',
    'js' => array(
      $path . '/mymodule.js' => array(),
    ),
    'css' => array(
      $path . '/mymodule.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );

  return $libraries;
}

In this case, the previous implementation of hook_form_alter() would become the following.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $form['#attached']['library'][] = array('mymodule', 'mymodule.library');
  }
}

Instead of calling drupal_add_js(), and drupal_add_css(), the code should call drupal_add_library('mymodule', 'mymodule.library').

The pro of using hook_library() is:

Dependencies between libraries are automatically handled. That is what happens in the case of system_library(), which defines two libraries using the following definitions.

  // Drupal's form library.
  $libraries['drupal.form'] = array(
    'title' => 'Drupal form library',
    'version' => VERSION,
    'js' => array(
      'misc/form.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 1,
      ),
    ),
  );

  // Drupal's collapsible fieldset.
  $libraries['drupal.collapse'] = array(
    'title' => 'Drupal collapsible fieldset',
    'version' => VERSION,
    'js' => array(
      'misc/collapse.js' => array('group' => JS_DEFAULT),
    ),
    'dependencies' => array(
      // collapse.js relies on drupalGetSummary in form.js
      array('system', 'drupal.form'),
    ),
  );

Calling drupal_add_library('system', 'drupal.collapse'), misc/collapse.js and misc/form.js would both be included.
The CSS files associated with the library would be automatically loaded together the JavaScript files.
Whenever the library would use more JavaScript, or CSS files, the code to include the library would not change; it would still be using $form['#attached']['library'][] = array('mymodule', 'mymodule.library');, or drupal_add_library('mymodule', 'mymodule.library').

There is no need to use current_path() when you can use arg(). If the path for the current page is admin/structure/block, then

arg(0) will return "admin"
arg(1) will return "structure"
arg(2) will return "block"

Update

hook_init() is not used anymore from Drupal 8. The alternative for Drupal 8 is using hook_form_alter(), hook_page_attachments(), or hook_page_attachements_alter(). hook_page_build() and  hook_page_alter() are not anymore used in Drupal 8.
What I said about using a JavaScript library is still true, even if it is suggested to use #attached to attach a library (or a Javascript file, or a CSS file) to a page. Drupal 8 doesn't allow anymore to attach just JavaScript or CSS files to a page; you need to always attach a library, which a set of JavaScript and CSS files, eventually made of just JavaScript or CSS files.


How do I create individual fields on a node?

Have a look at my answer to "How to add new data to a predefined list?", which describes what you can do with the Select (or other) module.

In your case, you could use that module also to define 2 fields, which I'd label something like so (or anything else you'd prefer):

Attribute (with values like Material, Color, Year, ...).
Value (with values like Plastic, Red, 2015, ...).

Obviously, if "I" would then want to add like "Taste = Sweet", I'd just have to add "Taste" to the 1st field, and "Sweet" to the 2nd field.

Sweet enough?


The module Entity Embed will be able to do that. There is now a dev version available, but you better wait for the first alpha/beta-release.

Even longer it will take, until this is in core:

Allow image style/responsive image mapping to be selected in Text Editor's image dialog

This is postponed to drupal 8.1

Until then you can use jquery to move the image from an image field to an empty container in the body. To avoid flicker effects, add a style display:none in the twig template of that specific image field and show it after moving it into the body in jquery.


Best practice for template theming - #markup vs safe_value

You actually want to use the render() function like so:

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

See http://api.drupal.org/api/drupal/includes%21common.inc/function/render/7 for reference. Also, be sure to use hide($content[FIELD_NAME]) right before you render $content or you will render the field a second time (unless you've hidden it in the view mode on the Manage Display tab of the content type).


SMB shared video files from Windows to Linux

Found the problem! It has to do with SELinux. After looking at the folder with

ls -Z

And seeing that files that were accessible had a context that the folder didn't (httpd_sys_rw_content_t), I disabled SELinux with

sudo setenforce 0

and I was able to access the files. Of course, I have more work to do, and I don't intend on keeping it turned off, but this at least shows me where the problem is. Wu!


How do I make changes to the user registration function?

You can use

hook_user_insert

to add additional code to the new user account creation process.

More information on the User API


CKEditor toolbar missing when conditional field becomes visible

Not finding a built-in way to avoid the problem of missing CKEditor toolbars on conditionally displayed fields, instead of using the Conditional Fields module, I use the Asset Injector module's JS Injector to inject this JavaScript into the node add/edit page (note that the authors field is an entity reference):

var el = document.getElementById("edit-field-authors-0-target-id");

if (el) {
  showHideBio();
  el.addEventListener("change", showHideBio);
}

function showHideBio()
{
  var el = document.getElementById("edit-field-bio-wrapper");

  if (this.value) {
    el.style.display = "block";
  }
  else {
    el.style.display = "none";
  }
}

Seems to work just fine, but open to suggestions for improvement. Thanks to @Taggart Jensen for the idea.


I found the solution: Calling translation_node_get_translations(), I have to provide the tnid (the node ID of the original node) as parameter, not nid, as nodes are translated by the node ID of the original node.

function _azzurra_get_translations_nids($node){
  $nodes = translation_node_get_translations($node->tnid);

  $nids = array();
  foreach($nodes as $value){
    $nids[] = $value->nid;
  }

  return $nids;
}

I wrote this function who return a list of all nids related to the argument node [included the nid of the argument node.. ]


How to permit users to add more items to a multivalue field conditionally?

Just place this in a custom module replacing what is given in CAPITAL letters:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENT_TYPE_node_form') {
    if (CONDITIONS) {
      unset($form['field_files_collection'][LANGUAGE_NONE]['add_more']);
    }

  }
}


As The Docs for condition says:

Parameters
$field: The name of the field to check. If you would like to add a more complex condition involving operators or functions, use where().

So let's see QueryConditionInterface::where:

Parameters
$snippet: A portion of a WHERE clause as a prepared statement. It must use named placeholders, not ? placeholders.
$args: An associative array of arguments.

Should do the trick for you.


Merge 2 collumn (Display suite) to one collumn depending on resolution

I would use a combination of 2 view modes plus Context Mobile Detect to trigger the different view mode


How do I use variables from config.ini.php?

As far as I know, you shouldn't be using a "config.ini.php" file for configs in your custom module.

You should have a /examplemodule/config/install/examplemodule.settings.yml file like this:

var_1: "value1"
var_2: "value2"

Then when you reinstall your module, it adds the values.  There's no need to run code in hook_install.

To access the values, use:

\Drupal::config('examplemodule.settings')->get('var_1');

and to edit:

\Drupal::configFactory()
  ->getEditable('examplemodule.settings')
  ->set('var_1', $value)
  ->save();

You're using state correctly, I tested this out:

\Drupal::state()->set('var_1', $value);

$var_1 = \Drupal::state()->get('var_1');


Can I theme fields depending on view or block that contains them?

Here is introduction for views2. To read manuals exactly for your views version, use Advanced Help module.

You can template everything, overriding template files in complex manner.


Why does drupal commerce create an empty order for every anonymous user?

There's nothing in core Drupal Commerce that would create an empty order for every anonymous session. Core Commerce will only create an order when an anonymous user adds a product to the shopping cart. This means some other module must be creating those orders for every session. I'd look to your contributed modules, especially if any are facilitating adding products to the cart via links instead of forms.


Why is hook_form_alter() not setting default values in _after_build function on /node/add/myct?

After doing some research, it turns out that taking a JavaScript/jQuery approach is the wrong way to do this. Rather, the code should use hook_form_alter() to retrieve POSTed data ($form['#method'] = 'post';) and set the default values of the node form (including CCK fields) via a function specified with $form['#after_build'].

So, if you want to dig in here and start monkeying with the "real" properties, you need to come in after the point that the CCK form elements are processed. Luckily, the form API has a phase designed for exactly this purpose: #after_build.

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  // Check for a particular content type's node form.
  if ($form_id == 'example_node_form') {
    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'example_after_build';
  }
}

/**
 * Modifies CCK form elements on the example node form.
 */
function example_after_build($form, &$form_state) {
  // Your code here.
  return $form;
}


Tables are not creating with hook_schema

<?php
/**
 * @file
 * Contains install and update functions for Views.
 */

/**
 * Implements hook_install().
 */
function mid_components_install(){

}

/**
 * Implements hook_schema().
 *
 */
function mid_components_schema(){
    $schemas = array();
    $schemas['mid_components'] = array(
        'description' => 'The mid_components data.',
        'fields' => array(
            'cid' => array(
                'description' => 'Primary key',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'title' => array(
                'description' => 'Human readable name of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'machine_name' => array(
                'description' => 'Unique machine name of the component',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'description' => array(
                'description' => 'Description of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => FALSE,
            ),
            'options' => array(
                'description' => 'A serialized array of options for this display; it contains options that are generally only pertinent to that component.',
                'type' => 'blob',
                'size' => 'big',
                'not null' => FALSE,
            ),
            'status' => array(
                'description' => 'Status of the component',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
                'unsigned' => TRUE,
            ),
            'created' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is created',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is modified.',
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('cid'),
        'unique key' => array('machine_name' => array('machine_name')),
    );
    return $schemas;
}

/**
 * Implements hook_uninstall().
 */
function mid_components_uninstall(){

}

Follow this method. And Make sure after doing any chnagings to your .install file, uninstall your module and reinstall it again.


Why is step 2 of file to media migrate giving me missing bundle error?

in step2 i had to change it to this
destination:
  plugin: entity:node
  default_bundle: grants


You should try changing the no results message in the view, maybe have return an invalid address like a@a@a.c or something.


You do have to have an ID - and you can use your hash here simply by defining it with 'type' => 'string'.


How to use devel on a taxonomy term page to see available nid's?

Terms have a term ID number (tid) and nodes have a node id number (nid). Terms are applied to nodes so nodes can be associated to terms and vice versa.

Devel module can show the structure of a taxonomy term. To achieve this:

Download and enable the devel.module
Ensure you are logged in with a user who has the Access developer information permission
Browse to the taxonomy term you want to inspect
Click the Devel tab if it is visible

If it is not visible, that is likely either a permissions issue or a theme issue - to fix a theme issue you could try changing to a core theme like Bartik

Then you should see some output like this:
You can click tokens or Render or other sub-tabs as well
This shows the tid and other values associated with the term, but not the nid of nodes associated with the term


How obtain the Distance/Proximity between 2 fields?

As far as I know it is not built into the location module but can easily be done in php with Haversine Formula, have a look here.

To add it to your view you can use Views PHP or theme a field with views-view-field--your-field.tpl.php passing in the two coordinates.


How to load a contributed module load before a custom module?

You could update the module weight so that it is lower than that of the contrib module meaning it would get loaded first.


Creating a view from multiple content types where one is optional

Install the Entity Reference module, and create an entity reference field on your Content Type B. Configure the field to reference Target Type Content and Target bundle Type A. Lets call the field ref_to_a.

Set up a view of Content Type A as a table of fields. Add the Title and Body fields. Then under Advanced add a Relationship. Use Entity Reference: Referencing Entity and choose Content referencing Content from field_ref_to_a Do not set the relationship as required, as you do not want to exclude the Type A records which do not have a Type B referencing them.

Now add a Content:Body field to your view, and configure it to use the relationship you have just created.

This should give you a view which will look like:

New York    Something
Ohio        Something   Interesting tidbit
Virginia    Something

Adjust your formatting as required, and good luck.


Automatically attaching/relating one view to another view based on same value in one field

You can do this by using Contextual Filters in Views. Contextual Filters allow you to filter Views results by "Context" (context usually means the currently displayed page or currently logged in user). Assuming you want to display Contacts on a Company page:

Create a new View (admin/structure/views/add) to show content of type Contact. Make sure the Create a block checkbox is checked. If you forget and skip that checkbox, you'll have to add a Block display on the next screen.
Fill out the View so that it looks as you want it to, with the appropriate fields, etc. displayed.
Under Advanced, click to add a Contextual Filter. You're going to be filtering Contacts to display only Contacts which match a certain value for the company ID field. Scroll through the list of fields in the popup window that appears until you find the company ID field. Check the checkbox next to that field and click the Add button.
You need to define the value of the contextual filter. Under WHEN THE FILTER VALUE IS NOT AVAILABLE choose Provide default value. Choose PHP Code for the dropdown Type and enter the following code in the PHP textarea:

$node = menu_get_object('node');
if (isset($node) && $node->type == 'COMPANY_CONTENT_TYPE') {
  $company_id = field_get_items('node', $node, 'COMPANY_ID_FIELD_NAME');
  if (!empty($company_id)) {
    return $company_id[0]['value'];
  }
}

Replace COMPANY_CONTENT_TYPE and COMPANY_ID_FIELD_NAME with the appropriate machine names for your company content type and the field name used to store the company ID.

This PHP loads the currently displayed node and loads the value of company ID field from that node. The value returned is used by the contextual filter to display only contacts which have a company ID field which matches this value.

You can preview the Contacts that will be displayed by manually entering a company ID in the Preview with contextual filters: input while editing the View. The preview should show only Contacts for which the company ID matches that entered value. On a live page view, this value is provided by the PHP above.
Save the View, and go to the Blocks admin page (admin/structure/block). Your new View should appear in the list of available blocks. Drag-drop the block you created into the Content region and save. Optionally configure the block and set it to only display when viewing Company nodes.

At this point you should be able to navigate to any Company node and see the list of contacts as a block, provided by Views. The PHP code entered loads the company ID from the Company node, and filters out all displayed Contacts which don't have a matching value for the company ID field of that Contact.

If you run into any issues or if I missed any steps, please comment below :-p For more information about using contextual filters, I recommend the Taming the Beast: Learn Views with NodeOne video series (parts 19-24 cover contextual filters).


Entity Metadata Wrapper Save VS Node Save when invoked from hook_node_insert

Essentially, there really isn't much difference between node_save() and the save() method of the entity metadata wrapper. Neither should however be used to save the node passed in as the argument to hook_node_insert().

The argument is passed by reference (since it's an object and all objects are passed by reference in later PHP versions), and any changes you make to it will be included when the node is saved by Drupal just after it's done calling the hook implementation.

Trying to manually save the same node again could trigger endless recursion into your hook_node_insert() implementation.

Just alter the node object as you see fit (setting the title in this case, though that is not a translatable string, so replace t() with check_plain()) and do nothing more.

If you need to do more complex alterations, the entity metadata wrapper could come in handy, but you must remember that any alterations you want to have saved must be performed on the node instance passed as a reference to hook_node_insert(). This means you can't node_load($node->nid) here first, since that would actually just create a new node object with data that's already in the database. If you do manage to save that node copy without ending up in a recursion loop, it would either mean that the node save already in progress - the reason hook_node_insert() was originally called - overwrites any changes you made, or fails because the new node to be saved already exists.

Instead, pass the $node argument to entity_metadata_wrapper() directly and the wrapper will be able to alter the correct node object for you, but remember to not call save() on the wrapper!


CAS Authentication disable drupal invitation

I do not know the CAS module but I do know a very generic way to hide / replace any page with another: add an alias! De-aliasing happens before routing. So if CAS has a page say /cas you'd like to see when someone visits /user/login simply add an alias with a system path of cas and alias user/login.


Assign programmatically created order to anonymous user

I think you may be thinking about this incorrectly. If I were you, I'd write a custom module that created a new path designed to create a shopping cart for whoever lands on it with the requested products. You can include a token or something in the URL to ensure each one only gets processed once, and you can redirect to /cart or some other route after the order is created to try to reduce duplicate carts.

This means on the secondary site you're just storing in a cookie or the session the product IDs that you'll then use to construct the cart when you pass them to the Drupal site via query parameters or something like that. It isn't really possible to create a remote session for someone and then force assign the session ID to them when they land on your site afaik.


How do I compare a date field with the current time in a twig template?

If you feel like a preprocess function is overload and if you can afford to ignore timezones, try converting both date values to Unix timestamps to make them properly comparable. And prefer raw node values over formatted content values:
{% if ('now'|date('U') > node.field_closing_date.0.value|date('U')) %}
  Past
{% endif %}


Clean and easy way to add meta tags to my D7 website

For Drupal 7 the Meta tags module is the way to go:

  The Meta tags module allows you to automatically provide structured metadata about your website.

MetaTags Quick is also good, but Meta tags has more features.


How can I order views Attachments in views page

Actually Drupal have re-order display, but I think it is for admin page only.

I also got same problems as you, but finally I found a way.

1) Click to ADVANCE.

2) Click to the machine name and edit it by ABC order.

Hope it will help.


I'm trying to configure memcache module and failed to load dmemcache.inc

Modifications to settings.php are required. Read the docs on how to configure it. Here is an example configuration I use with two memcached servers:

$conf['memcache_key_prefix'] = __FILE__;
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;
$conf['memcache_servers'] = ['172.16.12.51:11211' => 'default', '172.16.12.52:11211' => 'default'];


How to add item to $vars[breadcrumb] in Drupal

I hope that you have set $breadcrumb in page.tpl.php.
Secondly, you do not need to do it by using theme_preprocess_page.

Just implement using THEME_breadcrumb like this:

function theme_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  $output = '';
  if ((arg(0) == 'node') && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
    if ($node->type == 'TYPE NAME') {
      $breadcrumb[] = $node->title;
    }
  }
  if (!empty($breadcrumb)) {
    $output.= '
' . implode(' › ', $breadcrumb) . '
';
  }
  return $output;
}


This is an educated guess:

The page "Programs & Services" on the programs-services link is built by Views module.

You can edit the Views by clicking on the small gear icon you see in the top right corner of the content area and choosing "Edit Views". Or find that particular View under Structure > Views and edit from there.

Under Filters on the left you'll probably have several filters listed, with one of them labeled (exposed). You can click on it and Remove - that is how you get rid of the "drop-down" filter currently present above the results.

To change which page titles appear in the results you again have to change something under Filters, but it's impossible to tell what because that depends on your site configuration.

Sometimes (besides the Published filter) there is the filter based on Content type, for example, to list only Articles that are on the site, or only Basic pages.

Sometimes there is a filter that filters by Taxonomy (tags) that the content is labeled with (for example list only content tagged with "Medical").

You need to find out what the current filter configuration is (post a screenshot), and how your new pages you want to list there differ from other content (are they of a different Content type, have they been posted after some date, by a different author, tagged with some tag).

Then you'll be able to change the filters accordingly to show the new content instead of the current list.


Composer: require dev branch then go back to stable once current dev is stable

You should better use a patch.

You will ask composer to download and install the required patch on top of the current stable release.

Once the patch will be inside the stable release, the patch won't be applied anymore (a patch is basically a diff file, so when there's no diff, there's not patch)

Install https://github.com/cweagans/composer-patches this is a dependencies that will allow to use a section in the composer.json to declare the patch. It will install it automatically.

composer require cweagans/composer-patches

Then add an extra section in your composer.json

"extra": {
    "enable-patching": true,
    "patches": {
        "drupal/module_to_be_patched": {
            "<patch1 information>": "<patch1 file path>",
            "<patch2 information>": "<patch2 file path>"
        }
     }
}

You will find the patch file path on the module tracker, on the repository of the module, for an issue

For exemple, successive patches for a drupal/webform issue : https://www.drupal.org/project/webform/issues/3137981

Then simply

composer install

You will see the patch is being installed right in your terminal.

Reference : https://groups.drupal.org/node/518975

Patching : https://www.drupal.org/patch/apply


Make views slideshow responsive - remove inline styles

The flexslider module mentioned above seems great with it's mobile swipe support, but only images are supported and I needed videos slideshow, with overlays support. So I've added the following lines in my theme's CSS file and it worked:

.views_slideshow_cycle_main { width: 100%; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }

With SCSS, it may be easily written as:

.views_slideshow_cycle_main {
  width: 100%;
 .views-slideshow-cycle-main-frame {width: 100% !important; height: auto;}
 .views-slideshow-cycle-main-frame-row {width: 100% !important; height: auto;}
 .field-content { max-width: 100%; width: 100%;}
 .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding:0;}
}

The overlays were added by views_slideshow_xtra_overlay.

Adapted from This discussion


Have a look on the original template on modules/block:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

As you might see in line 4 there is a

<?php if ($block->subject): ?>
<h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php if ($block->subject): ?>

Use this... but do not forget to use

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

before the title and

<?php if ($block->subject): ?>

after the title - these variables enable contextual links.

Additionally assure that you follow the template naming conventions. I think it should be views--view--my-view--block-1.tpl.php (but I am not sure - did you alreay find out if your template file is used? To do this just add any text into the file to see changes in the browser).

When you just added a new template file remember to rebuild theme registry. Either by deleting all Drupal caches or by visiting admin/appearance. If you use Devel module in conjunction with Admin menu you find a possibility to rebuild the theme registry under the projects favicon on the left of the Admin menu.


A good starting point is the bootstrap theme. They have a stable version for drupal 8. (It's the most object oriented theme I've seen so far)

  So I would suggest to make your custom theme, as sub-theme of it.

If you want to do it fully by yourself, you would use hook_form alter existing forms (if needed) and theme_hooks/html.twig to add some bootstrap specific classes and change HTML structure.
The mentioned theme is a good starting point to look at all the things that need to be changed.


Google Rich Snippets and Facebook Open Metagraph

In the answer above, there are modules indicated. However, in my experience, they won't work with fivestar, for they are only generic. So, what I usually do in such cases, is to:

Create a template for that node type, like node--type.tpl.php
Create a preprocess function in your theme's template.php file, implementing hook_preprocess_HOOK(). This will translate to an actual function name like mytheme_preprocess_node(&Svariables).
In that function, use the $variables['node'] to get the data from the fivestar widget field.
Format and prepare that data for output, and add your custom variables to the $variables array.
Use the variables you provided in your preprocess function to insert the correct markup in your node file to correspond to the opengraph / rich snippets format.

Some notes:

Use devel module and dpm() function to dump the $variables in preprocess function and the data in the template file.
Use the google markup tool and the facebook markup tool to test your markup.
The logic is, prepare variables in preprocess, and put them in markup in template file. Try not to have computations (business logic) in the template file itself, use preprocess for it.


Problem with JS linked to an Ajax loaded page

Have a look at the Ajax Framework. It will make your life way easier. You can probably accomplish everything you're trying to do with out a single line of js.


It might be a better idea to set a contextual filter on the path. You can still do some tweaking in hook_views_query_alter(), if needed (you can do a lot of things with contextual filters in the ui), but at least views knows by doing that which cache contexts it has to set.


How can I inject relevant/filtered ads every 5th result in a view?

What you could do is

Create view only for ads:
Create preprocess function in your custom theme/module that is loaded before the template.
In this preprocess function call your view programmatically with the filters from the current page.
In Drupal 8 you can set filter programmatically like that:

ViewExecutable::setHandler($display_id, $type, $id, $item);

Order the results in the way you want and store them in an array variable that you can access from the twig.

Hopefully that helps.


Standard bootstrap main menu with dropdown?

Your "standard" Bootstrap subtheme launches with your "standard" Bootstrap Nav Bar. For most intents and purposes this is the main-menu... links added to the main menu at admin/structure/menu/manage/main-menu appear there ...

Oddly the navbar isn't available to configure from the blocks page as you might expect nevertheless ... there are some navbar options available under admin/appearance/your-bootstrap-subtheme/settings.


How can I refresh a view block as soon as new content is added?

You can achieve that using the Views node.js module

  This module implements dynamical update of views by nodejs after executing rules action.
  This module implements rules action which we can add to any rule for updating some views (views which need update, one can select in action).

  During updating of views all arguments that are already passed to view will be taken into account.

  It is also correctly working with views which use ajax.
  Introducing video.


With References or Entity References (recommended) module, you can add node reference fields to your node type.
It's pretty straight forwad. I'd suggest looking at drupal.org docs about making node types asyou are new to Drupal. You will not need to code anything in most cases. for content display, you can use theme templates and/or Views.


How to Filter views result by current logged in user's role

Try adding view relationship to "Content: Author", and then add contextual filter for field "(author) User: Roles".


Workbench Access field cannot be used for access control

The fields were enabled all along, the main issue was targeting the problem.  Only my body field was displaying on the node draft. I had several other custom content fields in the node but they weren't displaying in the Draft.  The site is built using Context and Views so was I had to do was clone Draft versions of those View Blocks and View Blocks.  Setting that up can be a little confusing but I found good documentation here

Draft Revision Blocks


You can copy node.tpl.php and rename it to node--blog.tpl.php for any blog specific changes. Find more about Drupal Template changes


What can I do with content types that I can't with taxonomies?

Taxonomies allow hierarchical nesting of items in vocabularies, and each term can only be in one position and one vocabulary at a time.

Nodes, however, can be tagged with any number of terms from any number of vocabularies.

Tagging taxonomy terms with other terms from other taxonomies, or with other terms from within the same taxonomy could potentially have very different results than maintaining a separation between terms (descriptors) and nodes (content that can be described), especially when it comes to using something like Views to sort and separate content based on descriptors.

So it's not so much that content types can do things that terms can't, as it is that content types cannot do as many things that nodes ought not do.


You really shouldn't be putting things like that in a drupal block via the UI anyway because someone with permissions could come along and mess it up and then everything breaks.

You can add/remove/change markup on the page by editing the templates in your theme.

For example you could add your template script tag into the page.tpl.php file of your theme.

Assuming you are using the same template on all pages (or a bunch of pages) or you just want a template on a specific page then this is really straight forward.

If you have more complex requirements you might need a large amount of template overrides or you may want to use some code in template preprocess functions in template.php to make things simpler.

For more information on this see Theming Drupal 6 and 7. There is a lot of info in there.


If your addition is general and not specific to your site, you could create an issue and post a patch there.

And even if you have a site specific extension, maybe it can be solved in a way that just requires an additional hook to the contrib module itself which could be useful for other use cases as well. Then you could again create an issue for that.


There is in fact a module that can do this. It's the Select with style module.


Uploaded image in Block Plugin keeps on getting deleted overnight

As you guessed its must to set permanent while saving the file. You need to include,
    $file = File::load( $fid );
    if ($file) {
      $file->setPermanent();
      $file->save();
    }

  The files will be added to the {file_managed} table as temporary
  files. Temporary files are periodically cleaned. Use the 'file.usage'
  service to register the usage of the file which will automatically
  mark it as permanent.


Is there any away to randomize a display message in rules?

The display message can be customized by following this procedure. You might also want to write a custom module, which may enable you to control your message display by user role.

If you want to display the status message in a different way, (there is a module for that ;-) too) try Better Messages module.

  Better Messages is a very simple module that provides "Popup-like" Drupal messages.


Advice Needed on Associating Articles by user with Nodes

This is rather straightforward in Views 3.x - you just want to create a relationship based on the field that you are using to associate the content. This could be something as simple as an author but for your case it sounds like you are going to have multiple types of content that relates back to a venue, ex. articles, etc.

So you would want to use a module like entity_reference and create a field of type entity reference, perhaps named "Related to Venue", that connects to your venue content type. Then add this field to whatever content types you have and when a user adds a new node (ex. an article) they could relate that back to the appropriate venue.

Now in your view block for the venue page, you just need to create a relationship using this field and then add a contextual filter that will find the appropriate node id from the venue page. This is a bit tricky but this is a very common task and this handbook page on d.o walks you through the basics.


Populate a field in form alter with user name and one with user ID

The D8 uid property reference isn't something that can be cast into a string as you could in D7.

In D7, user objects use a generic PHP object class (stdClass) with a uid property containing a string. In D8, user objects use a Drupal\user\Entity\User class. This class does't have a direct uid string property.

In D8 the uid property magically retrieves the User entity field property instead of a simple uid string.

As such, there are other new methods/properties (as you've mentioned) to retrieve the underlying uid value.


Display region's blocks into user-profile.tpl.php

If you would like to show blocks only on the profile page and not on the user/register or user/login or or user/*/edit, you can use the code for blocks visibility.

<?php
global $user;
if (arg(0) == 'user' && $user->uid == arg(1) && is_numeric(arg(1)) && (arg(2) == NULL) )
{
  return TRUE;
}

else {
  return FALSE;
}
?>


Why does drupal_session_start fail after a user clears cache then logs back in?

For D6, following lines will work to get the session values

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

If you are using D7 user Drupal's built-in ajax framework.


How to check node authorship info in views

Add a filter to your view of User: Current.  This will filter the nodes to ones created by the current user.


Please create view (content revisions view) like below images:

In view relationships please add  content revisions : user  for user information

Thanks!


Ajax'ed file field doesn't find the form constructor function on rebuild

You will need to include file by using the $form_state['build_info']['files'] array.

For example:

$form_state['build_info']['files'][] = drupal_get_path('module', 'user') . '/user.pages.inc';


Simple answer - the line foreach ($node_taxonomy AS $term) is where the $term variable is coming from. That's a basic PHPism that treats $node_taxonomy as an array, and puts the current item from that array into the $term variable as it iterates over the array.

As snufkin noted, $node_taxonomy is the only variable you're getting access to automatically.


Ensure  your connection string in the phpunit.php.dist is correct. The correct format is:

mysql://username:password@localhost/databasename#table_prefix


How to securely authenticate content embeded in another site?

1- build the content structure well in your first site and create a view from admin/structure/views/add that return the data needed to the second site which acts like a client consuming your first site content.

2- Download and enable Services module and enable the submodule Rest Server and submodule OAuth Authentication now you can create secured resources to be consumed by any other sites.

4- create an end point from admin/structure/services/add and choose authentication type as your case "OAuth Authentication" will fit as you need to authenticate the client "the second site consumes your data".

3- Download and enable Services views module that will help you expose any view as a resource to be consumed and managed via services and

4- From the view you have created before click the button Add and choose services, now the view will appear as a regular resource in your site under admin/structure/services/list click edit resources to see it named with your view name enable it and choose the required authentication and authorization.

Now any authenticated client client site or App can consume that resource from http://YOUR_SITE_DOMAIN/END_POINT/VIEWS_SERVICES_URL.

The last and the most important part in your requirements is to configure the authentication method and test it will I recommend below helpful tools and articles.

Chrome rest client extension to test the webservice.

Very helpful article about services module

Another helpful article


No.

When you add a new View, in the first screen there is a GUI with menus that let you create a view to;

Show users sorted by newest first

And that is all there is to it!

You can obviously refine the View to enhance the presentation, change the sorting, add a pager, etc. - but just to list the users, the above is what is required.


How to set different cache mobile and desktop based on header HTTP for one URL?

You have to add a cache context to the page:

/**
 * Implements hook_preprocess_HOOK() for the page template.
 */
function mymodule_preprocess_page(&$variables) {
  if ( ... ) {  // check if this is the page
    $variables['#cache']['contexts'][] = 'headers:X-Something';
  }
}

This adds probably too many variations, so you might need a custom cache context to only vary by two conditions, mobile or desktop. Extend RequestStackCacheContextBase, so that the request stack is already injected and return either 'dc.mobile' or 'dc.desktop':

  public function getContext() {
    $request = $this->requestStack->getCurrentRequest();
    $header = $request->headers->get('HTTP_X_AKAMAI_DEVICE_CHARACTERISTICS');
    if (...) {   // check $header for mobile
      return 'dc.mobile';
    }
    else {
      return 'dc.desktop';
    }
  }

This is a tagged service (tag name: cache.context). See the documentation for more information https://www.drupal.org/docs/8/api/cache-api/cache-contexts, especially the warning about the Internal Page Cache in the last chapter concerning anonymous traffic. In most cases it should be a better option anyway to handle this edge side or even better client side in js, not server side.


You just need to call user_save() using code similar to the following one.

$edit['pass'] = 'New password';
user_save($account, $edit);

$account contains the user object for the user account to alter. I get you load it using user_load(), but it could also be the user object for the currently logged in user. In the latter case, Drupal will regenerate the session using the following code (part of user_save()).

  // If the password changed, delete all open sessions and recreate
  // the current one.
  if ($account->pass != $account->original->pass) {
    drupal_session_destroy_uid($account->uid);
    if ($account->uid == $GLOBALS['user']->uid) {
      drupal_session_regenerate();
    }
  }

The password in $edit['pass'] is the plain password. user_save() will replace it with its hash using the following code (at the beginning of the function).

if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}

As alternative, you could use drupal_submit_form().

$form_state = array();
$form_state['user'] = $account;
$form_state['values']['pass']['pass1'] = 'New password';
$form_state['values']['pass']['pass2'] = 'New password';
$form_state['values']['op'] = t('Save');
drupal_form_submit('user_profile_form', $form_state);

In this way, if you have any module that, for example, validates the password, its code would be executed, and you would get any error code from form_get_errors().


How to show order total components in a block?

Quoting @Clive from the comments above:

  Commerce has a "Commerce Order: Order total" component that can be used in Views- it does exactly what you're looking for.

Thank you!


The error you see is output from ConfigImportSubscriber::validateDependencies(), which uses the following code.

  // Validate the dependencies of all the configuration. We have to validate
  // the entire tree because existing configuration might depend on
  // configuration that is being deleted.
  foreach ($config_importer
    ->getStorageComparer()
    ->getSourceStorage()
    ->listAll() as $name) {

    // Ensure that the config owner is installed. This checks all
    // configuration including configuration entities.
    list($owner, ) = explode('.', $name, 2);
    if ($owner !== 'core') {
      $message = FALSE;
      if (!isset($core_extension['module'][$owner]) && isset($module_data[$owner])) {
        $message = $this
          ->t('Configuration %name depends on the %owner module that will not be installed after import.', [
          '%name' => $name,
          '%owner' => $module_data[$owner]->info['name'],
        ]);
      }

The code assumes that for a name like node.type.article the owner is the Node module. If the owner is not one of the installed modules, Drupal gives the error you see.

To answer your question, the module name is assumed to be stored in the configuration filename.


How to get drupal module path in javascript?

First of all you need to call drupal_add_js() with a 'settings' parameter. This will inform your Drupal.settings javascript namespace about the settings/variables you need in this file via drupal. Try the following :

Lets suppose you want to call a specific *.js file on a nodes' view page, call it as :

drupal_add_js(array('myModule' => array('basepath' => '<your-drupal-base-path>')), 'setting');

This basepath is global and you can get it in any *.js file called at this point. Next, you can use this basepath in your *.js file as :

var path = Drupal.settings.myModule.basepath;


Feeds importer imports only some of the nodes

Feeds keep track of previously imported items in the feeds_item table. This also includes items that were only updated by Feeds, but not originally created by Feeds.

Under normal circumstances, when you delete an entity imported/updated by Feeds, Feeds will delete the corresponding import meta data from the feeds_item table. There can be occasions where this does not happen. These are:

During the deletion of the entity, a PHP fatal error occurred which prevented Feeds from cleaning up the import metadata. Non-fatal errors should not cause this, as Drupal would then perform a rollback of the deletion.
Feeds is disabled when deleting the entity.

Feeds doesn't clean up orphaned items from the feeds_item table. To clean this up, you'll need to execute a query on that table. The id column represents the importer ID and feed_nid the feed node ID (the latter is only used when you have attached your importer to a content type and you need to create a node to import content).

Example query to delete all import metadata for the importer 'my_importer':

DELETE FROM feeds_item WHERE id = 'my_importer';

There is an issue to let Feeds automatically clean up orphaned feed items: https://www.drupal.org/project/feeds/issues/1394320

For more information about the feeds_item table, see https://www.drupal.org/node/1768352


Can I add text to a form file upload field?

You can add a #prefix to a file upload field using hook_form_alter, but I don't think it will give you what you're looking for

function test_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'test_node_form') {  //custom content type of 'test'
    //custom field in the content type called 'field_test_upload'
    $form['field_test_upload']['#prefix'] = '
test prefix
';
  }
}

With the above code I have a custom content type of "test" and a custom field called "field_test_upload"

When adding a #prefix to the field I get the following results:


There is a couple of hooks in drupal 7 to restrict access to files.

One thing you have to realized is that these access hooks are only going to work if your download method is private, and the files are in your private path.

As you mention in your question there is a hook_file_download that should work in your case (assuming the file is private). This is not going to work if the file, someone is linking to, is somewhere public such as sites/default/files/abc123.txt.

If you happened to be uploading these private files in a field, then hook_file_download_access would seem more appropriate. This will give you the field that the file belongs to and also the related entity that this field is being used on so you should be able to do more complicated logic such as calling the the appropriate access function to check if the user has access to the field instead of having a hard-coded list in the code.


Redirecting a registration link in logintoboggan

Use a hook_menu_alter to alter the user/register path and add your own page callback to it.


If you attach an image field to the content type, you can define Image Styles at admin/config/media/image-styles. It is the core continuation of the Imagecache module.

This may be able to be made to work for inline images using the Media module, but YMMV.


How to load a file during the load of drupal 8 bootstrap (hook_init)

I think that you actually already har answered your own question.
EventSubscribers is the way we do it in Drupal 8, so it might be right what you are trying to do.


Views of products just showing the first time a taxonomy term is used?

Did you build your view based on nodes or on taxonomy terms? (https://drupal.org/node/770782)

I think a taxonomy terms based view is the preferred way. Maybe you already did this.

  1) add a new view of view type "term" (not the default "node" option!)
  by ticking the correct option after clicking 'add view'

  2) add the Taxonomy Term to the list of Fields

  3) Add a relationship "Taxonomy: Node" and make it obligatory

  4) In the basic settings enable the 'distinct' option.

  5) Add some filters to narrow the results as needed.

When setting filters you can try to use a contextual filter Term-ID with a default value set from the node page, only from the term list sports. You will also need to set a normal filter with term list product category.


Drupal 7: fetchField(0) giving me half of the records!

Yes, the loop iterates through result, but additionally you do that kind of again in your line $value = $result->fetchField(0);.

This should be changed to $value = $record->name;.


The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.

Example:
Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css


How to show different entity in Views with different displays?

You have to add relationships Content: Taxonomy terms on node then you will get options to add taxonomy in filter criteria and fields


Multi-value checkbox within content type

Add a new field choose FIELD as 'List (text)' and Widget as 'Check boxes/radio buttons'
Then in allowed values list, give your values
eg:
funky|funky
cool|cool
dive|dive
swank|swank
disco|disco
Choose Number of values to "Unlimited"
Then in DEFAULT VALUE, you can see all the options as check boxes, check every boxes if you want display all as selected.

Now you will get the desired output


How to purge cached content every day via cache tag?

Here is the code that flush cache on first hit of a day:

  public function build() {
    ...
    ...
    ...
    $this->handleCacheTag($build['#cache']['tags']);
  }

  protected function handleCacheTag(&$tags) {
    // Get the current date number.
    $current_date_number = date('z');
    $last_date_number = \Drupal::state()->get('module_name.foo.date_counter', $current_date_number);
    // If last date in settings is different from current day, invalidate
    // tags.
    if ($last_date_number < $current_date_number) {
      $invalid_tags = range($last_date_number, $current_date_number);
      array_walk($invalid_tags, function(&$invalid_tag){
        $invalid_tag = 'foo:date.' . $invalid_tag;
      });
      Cache::invalidateTags($invalid_tags);
    }
    \Drupal::state()->set('module_name.foo.date_counter', $current_date_number);
    $tags[] = 'foo:date.' . $current_date_number;
  }


Node's Preview when using Views module to render Node

The solution was to rebuild the whole thing in Display Suite module. Views (when using Unformatted List of Fields) cannot render teaser and Full content in node's preview!


How do I send an email when users update their email address?

You could add a HOOK_user_presave method in your custom module.

Example:

function mymodule_user_presave(\Drupal\user\UserInterface $user) {
    if ( !($user->isNew()) ) {
        //check if the value in the db is different to the value in $user
        if ($user->original->getEmail() == $user->getEmail()) {
            // send email
        }
    }
}


How can I encrypt the username and email address in the database, to protect against emails being stolen from a compromised database (D7)

If you want encrypt it, it means you need to decrypt it. So it means that the algorithm that encrypt and decrypt are available somewhere in your application or drupal files.

I guess if the user that has access to your database he has also access to your files, or at least I guess he can have access easily.

And in that case, encrypted datas are useless.

The most important its to hash the password with algorithms like SHA1 and use a salt or private key, thing that Drupal 7 is doing.

This is just my point of view, but if you want do it what you can use this module http://drupal.org/project/aes and with some user hooks, such as hook_user_presave() and hook_user_load().

The trick in this case it's that your module should be the last one before saving save the data and be the first one that decrypt data.


Drupal 8 Views or Pixture Reloaded paging/formatting problem

Problem solved.

Looks like I had a corrupted instance of my Newsletter content type. When I deleted it the problem went away.


drupal_add_js - working with inline but not file

With Drupal instead of using $(document).ready, you can/should use Drupal.behaviors. Here is a boilerplate JavaScript wrapper you can use:

(function($, Drupal) {

  // Custom functions and variables can go here

  Drupal.behaviors.moduleName = {
    attach:function() {
      // Put your document's onload code here
    }
  };
}(jQuery, Drupal));

By the way, now that it's all done, to go back to the original topic, I wouldn't/don't use drupal_add_js() at all. Instead, you can do this:

<?php
if($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}
?>

This attaches the file directly to the form, allowing it to be overridden further down the line through the context of the form it belongs to.


Find and display most recent referencing entities

I've made an assumption about the way you want the table to be formatted, but something like the following should get you most of the way there:

// Set up the table.
$header = array('Factory Name', 'Field Value');
$rows = array();

// Get some nids for the factories you're interested in. Your real query will probably be more specific (checking status etc).
$args = array(':type' => 'factory');
$factory_nids = db_query('SELECT nid FROM {node} WHERE type = :type', $args)->fetchCol();

// Load the factory nodes.
$factory_nodes = node_load_multiple($factory_nids);

foreach ($factory_nodes as $factory_node) {
  // Add the factory name to the first column of this row.
  $row = array($factory_node->title);

  // Get the latest measurement related to this factory with an EntityFieldQuery.
  // fieldCondition() and fieldOrderBy()/propertyOrderBy() are the important bits here.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'measurement')
    ->propertyCondition('status', 1)
    // This is the entity reference condition; entity ref fields use 'target_id' as the field column name.
    ->fieldCondition('field_factory_reference', 'target_id', $factory_node->nid)
    // If the date you're interested in is in a field, use something like this...
    ->fieldOrderBy('field_measurement_date', 'value', 'DESC')
    // ...or if you're interested in the node created date, this
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1);

  $results = $query->execute();

  // Make sure there are some results.
  if (!empty($results['node'])) {
    // EntityFieldQuerys always return an array of nids even if there's only one result,
    // so it's easier to run through node_load_multiple and shift the element later
    $measurement_nodes = node_load_multiple(array_keys($results['node']));

    // Get the node
    $latest_measurement_node = array_shift($measurement_nodes);

    if ($field_items = field_get_items('node', $latest_measurement_node, 'field_some_field')) {
      // If we have an appropriate value, add it to the row.
      $row[] = $field_items[0]['value'];
    }
    else {
      $row[] = 'No data found';
    }
  }
  else {
    $row[] = 'No data found';
  }

  $rows[] = $row;
}

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


Yes, it is possible, with the attributes property.
my-library:
  version: 1.x
  js:
    js/App.js: { attributes: { type: module } }

See Adding attributes to script elements and JS properties.


Creating static pages on production from a local module

Method I ended up using:

Procedurally create nodes on local environment, parsing XML feed with SimpleXML
Hardlink to production server when crosslinking nodes
Use Node Export to export/import nodes from local to production server
Use pathauto on production to create node aliases


How can i find out when the next cron will run?

Basically, you cannot.

If you are using Drupal 7 built-in CRON triggering method, in Drupal 6 Poormanscron module, CRON run depends on the availability of visitor. If no one visits your page, CRON will not run. Drupal can't predict if or when visitor will appear, so the best you can know is when CRON will not yet run anyway, even if visitor is available.

If you are using external tools, Drupal has no way to predict if and how they will trigger it. It will accept all proper request, so you know even less than in the first case. Even if you know when it is supposed to run, you don't know time difference between servers, as it is subject to change slightly. You don't know the lag between a moment when CRON should happen and when it will, as practically no web servers are hosted on real time operating systems, so there are no guarantees about maximum time between action request and it's execution. In simpler words, server can postpone CRON task if it's to loaded, sometimes even skip it.

If you need predictable and reliable cron, go to http://example.com/admin/config/system/cron, find URL described as "To run cron from outside the site, go to". Then, mail your server administrator and ask him to add this to server's crontab:

*/5 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=yourcronkeyrandomstring

This will make your site's CRON run every 5 minutes, and you shouldn't need to know when exactly - it's ofthen enough for most tasks. If it's not, make it */2 to run it every 2 minutes, or just leave * at every position to get it triggered each and every minute. You can read more about system's CRON configuration on Wikipedia. Of course it will not allow Drupal to know, it will just free you from the need to know.


How to create anchor link to another page

If 'puppy-training' is a section on the '/training/classes' page then there is not a way to remove the '#' symbol. The '#' symbol is a fragment identifier. It is supposed to refer to a location within a resource (i.e., the '/training/classes').

If you would like to have a URL without the '#' symbol, I would recommend creating a separate node for that piece of content.


How can I create a Simple page that display the latest node of a content type?

Just do the following with node object in your page callback function. No need of returning separate #markup.

return drupal_render(node_view($node));


How can I implement a form into a DC view footer?

You might want to consider using the Commerce Shipping module to handle the integration to Drupal Commerce, it doesn't support adding the shipping quote form in the cart footer, but it would help in handling the actually shipping quote with commerce.

The problem you are facing is in the hook_views_data, you should do something like this:

function MY_MODULE_views_data() {
  $data = array();
  // Define an footer handler for displaying shipping quotes.
  $data['MY_MODULE']['shipping_footer'] = array(
    'title' => t('Shipping API Quotes'),
    'help' => t('Display a user input form to allow the retrieval of shipping quotes.'),
    'area' => array(
      'handler' => 'MY_MODULE_shipping_form',
    ),
  );

  return $data;
}

You need to define an area handler as shown above, that should let you select the form in the views UI.


Why responsive panels are not one beside another by default?

This can be done CSS only:

Apply a width and float to all panels in the footer:

#footer .region {
  float:left;
  width:20%;
}

Or make them a little smaller so you can apply margins to 'm.


How to efficiently check if taxonomy has children

As arpitr says taxonomy_get_children() loads the child terms, so you are better of with a fork of this function.

I wanted to know whether a term a) is connected to any nodes and b) has any child terms.

/**
 * Helper function to check whether a term has no child terms and is not
 * connected to any node.
 *
 * @see taxonomy_get_children()
 */
function YOURMODULE_is_term_empty($tid, $vid) {
  $children = &drupal_static(__FUNCTION__, array());

  // Is term connected to node?
  if (!isset($children[$tid])) {
    // Get id's of connected nodes. Make query lighter by using no pager,
    // setting limit to 1 and sending an empty array with fields to order on.
    $node_ids = taxonomy_select_nodes($tid, FALSE, 1, array());

    if (!empty($node_ids)) {
      $children[$tid] = false;
    }
  }

  // Does term have child terms?
  if (!isset($children[$tid])) {
    $query = db_select('taxonomy_term_data', 't');
    $query->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
    $query->addField('t', 'tid');
    $query->condition('h.parent', $tid);
    $query->condition('t.vid', $vid);
    $query->addTag('term_access');
    $query_result = $query->execute()->fetchCol();

    $children[$tid] = empty($query_result);
  }

  return $children[$tid];
}

NB: I did not make this work recursively.


How do I add a field to a view that shows the user that published the node?

You may want to have a look at the revisioning_content_summary view which comes with the Revisioning module. You'll find it at admin/build/views/edit/revisioning_content_summary.

It lists both the User: Name for the author and the Node: Last edited by for the moderator -- the information used in the Revisions tab, too.

Additionaly, have a look at creating views of type Node revision, which enable you to list all revisions of nodes, along with the revisioning information.


Yes, when you create a block programatically you can add any content inclusive another blocks.

In your block function you can do something like:

$blockA = module_invoke('block', 'block_view', 1);
$blockB = module_invoke('block', 'block_view', 2);
return $blockA['content'].$blockB['content'];


Force drupal 7 to place "www" in front of urls

Adding this to your .htaccess file will do it...

RewriteCond %{HTTP_HOST} !^www\.YOURDOMAIN\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.*) http://www.YOUDOMAIN.com/$1 [R=301,L]


How do I count the number of products in cart programmatically?

In Drupal 8, carts are special orders, related to a user (like regular orders). In a custom module, you can fetch the logged in user orders, filter them by a convenient boolean field called 'cart', sort them by creation date to get the last cart for this user. Then you can get the items count for this cart order :

in mymodule.module :

use Drupal\commerce_order\Entity\Order;

function mymodule_preprocess_[page|block|something_else](&$variables) {

  // get orders...
  $query = \Drupal::entityQuery('commerce_order')
    // ...for logged in user, could be anonymous (uid = 0)
    ->condition('uid',\Drupal::currentUser()->id())
    // ...which are carts
    ->condition('cart', 1)
    // ...last created first
    ->sort('created', 'DESC')
    // ...get only one
    ->range(0,1);

  // execute this : you get an array of a unique order ids (last cart)
  $cartsOrders = $query->execute();

  // I found one : this user has a cart
  if(count($cartsOrders) > 0) {

    // load the order which is the last cart for logged in user
    /* @var Order $lastCart */
    $lastCart = current(Order::loadMultiple($cartsOrders));
    // send this order items count to the template
    // ({{ cartItemsCount }} in your twig)
    $variables['cartItemsCount'] = count($lastCart->getItems());
  }
}

This may contains non optimal or ugly code, this is just a starting point (but quickly tested though, seems to work). Also this need to be tested in rare case scenarios or weird situations (involving anonymous users for example). My strategy (grab the last created cart order) may be wrong too...I would be happy to have a specialist feedback on this.

EDIT

I spent more time on this and had to debug a few things, here is some improvments (more Drupal Commerce 2 way) :

/* @var CurrentStoreInterface $cs */
$cs = \Drupal::service('commerce_store.current_store');
/* @var CartProviderInterface $cpi */
$cpi = \Drupal::service('commerce_cart.cart_provider');
$cart = $cpi->getCart('default', $cs->getStore());

$nbItemsInCart = $cart ? count($cart->getItems()) : 0;


How can enable multiple contact form in drupal 8?

Each has their own URL. Check contact.routing.yml but pretty sure they are of the form contact/{contact_form} where contact form is the machine name. You can create menu links and aliases to these like any other path.


How to get services post data(json format) callback function?

Through comments, we determined the OP would like to alter the results
  of the user registration service resource...

To alter the results of user registration data, implement hook_services_request_postprocess_alter() in your custom module, for example:

/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_user_resource_register') {
    $result->foo = 'bar';
  }
}

This will allow the value of foo to be available to your application that is calling the user registration service resource.


How do I unfollow an issue on drupal.org?

To unsubscribe to the issues for a project, for example the "Drupal.org web masters" project, you need to:

visit the issue page for the project (http://drupal.org/project/issues/webmasters)
click on the "Subscribe" link

In the next page, select "None," and click on "Subscribe."

Unable to unsubscribe to drupal.org issues is an old issue that has been opened in 2006, and it has been marked as fixed. I can confirm that unsubscribing from an issue queue works, as I have done it many times in the last years.


Views: display entity reference fields as view fields

Yes you can do it. The Entity view Attachment  module is built for such task. Using this module, fields of another content types becomes a filed of another one. this link is a good tutorial of this module.


Image not responsive in one content type. Can anyone help me resolve this?

Because you a style rule somewhere...

.node-openpublish-photo-gallery .field-name-field-op-main-image {
   width: 620px;
}

They appear to be different content types...

node-openpublish-photo-gallery (not working)

node-openpublish-article (working)


The function you are looking for is field_info_instances().

  Retrieves information about field instances.


The theme settings not being inherited by the subtheme is a Drupal core bug. If you simply copy the theme settings from the parent's .info file to the subtheme's .info file, it will alleviate the issue.

However, keeping a local patch of the theme is a reasonable solution in this case. The rule of "dont edit a contrib theme" is really in place just to ease potential updates, etc. for users who may be unaware of the risk of losing their changes upon updating themes/modules.


Has anyone worked on a built-in CLI terminal [w/ drush]?

The upcoming Drush 7 now has drush core-cli which used the Boris shell


You can add the <h2> tag under Style Settings of your field.

Example:


How to set up a child theme using pattern lab?

Welcome to Drupal answers.

Patternlab does not have opinion about Drupal theme hierarchy. So given you are maintaining the parent child hierarchy as per Drupal theming structure your child theme must be able to inherit all the component templates from parent to child.

While there could be multiple ways you can go ahead with development in future, one way would be to keep creating new components at parent theme & pattern lab. Patternlab can continue using base theme styling to show the components whereas  in Drupal styling(css) would be dynamic via variables which would be decided for what theme you are building.


These links are navigation links, so called "breadcrumbs". They inform the site visitors where they are on the site.

You are using the Bartik core theme -- take a look at /sites/themes/bartik/templates -- there is a file page.tpl.php. On about line 176 the following code

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

renders these breadcrumbs.

You could comment or remove these lines to avoid rendering navigation links. If you make changes to theme files remember to flush cache to see the changes.

But a better solution would be to create a Bartik subtheme (because each time you update the Drupal core, all your changes made to this file will be overridden, I would also not recommend to touch core files).

You could consider to choose another theme which has additional settings options like for displaying breadcrumbs.


How to enable theme on profile installation

In your profile_name.info, add a new line with theme = mytheme.


Does drush support everything I can do with web admin interface?

No, you can't. That's not possible.

Every command needs to be explicitly provided to Drush. Many contrib modules now come with integrated drush commands, for example Devel generate, Features, Views, XML Sitemap and so on.

To see the list of commands that are available to you, call drush help. You can get detailed help on each command with drush help <command>.


How to use Rules to change the value of entity reference’s field?

Step 1: Create a Rules Component

Create a Rules Component (of type "action set") like so:

Parameters are "node" and "stock decrease".
Rules Action = "set value/calculated value from other filed within same content type" (*).

Here is a prototype of such Rules Component:

{ "rules_decrease_stock" : {
    "LABEL" : "Decrease Stock",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "stock_decrease" : { "label" : "Stock decrease", "type" : "integer" }
    },
    "ACTION SET" : [
      { "drupal_message" : { "message" : "Something just got sold, so please decrease the stock for node with id [node-to-update:nid] with an amount of \r\n[stock-decrease:value] units. To actually do so, replace this (informational) Rules Action with setting the appropriate value for the appropriate field ..." } }
    ]
  }
}

The actual action only displays a Drupal message (to show the values of the variables passed to it). Replace that action with the actual update of your inventory node (*).

Step 2: Create a Rule

Create a rule with Rules Event something like "after updating a node of content type "Sales". Maybe also some Rules Condition like "stock_available" is updated (checked if the unsaved value differs from the saved value). And add these Rules Actions:

Update the stock_available in your Sales content type (*).
Perform the Rules Component (from step 1), whereas you pass these 2 parameters:

the node, which you can pass via the value (token) of the entity reference.
the stock decrease amount (which is identical).

(*): you indicated in your question you know how to do that ...


I've found that the best way is to just thrown an error during presave. Here's a simple example:

function mymodule_node_presave($node){
  if(empty($node->title)){
    throw new Exception('Error saving node: Title cannot be empty');
  }
}

The node_save() function has a try...catch block wrapping the presave step that will catch the exception.

The advantage of this over drupal_goto() is that, if you're importing multiple nodes, it will skip the current node and proceeed to the next one. This is great if you're using something like the Feeds module. In contrast drupal_goto() will exit immediately and may interfere with other steps in the request or cron, which will break importing multiple nodes.


Addition to an integer field with a form

You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).


Show advanced search form outside fieldset

take a look at the Advanced Search Module:

This module alters the default search box in many ways. If you need to
have options available like in advanced search, but directly in the
search box, this module is for you.
Basic options The module adds
options to select:
which content type(s) to search, which specific module search to use
(node, help, user or any module that implements search), which input
type to use (with Elements), advanced criteria For all these choices,
there are options to switch between a select box, checkboxes or radio
buttons, and also customize the selector label and the default - Any -
text.
Advanced options There are also options to:
change the default search box label, add a default text in the search
box, add advanced search criteria, change the default submit button
text, use an image instead of the submit button, change the order of
all the elements, include some elements in a popup block, add a filter
to the results page, show/hide basic and/or advanced search in the
results page, show/hide meta data in the results page, multiple search
paths


Importing products into Drupal Commerce and handling Tax

Found the solution it seems.
It is apparently not enough to add a field under the data array, you also need to add the include_tax field on the same level as amount and currency:

//commerce_price[und][0][amount]
$price = array(LANGUAGE_NONE => array(0 => array(
  'amount' => $price * 100,
  'currency_code' => $product_obj->vatType,
  'data' => array('include_tax' => 'MVA_hoy'),
  'include_tax' => 'MVA_hoy',
)));
$form_state['values']['commerce_price'] = $price;

Now, when importing products, the tax field is updated.


Have you tried ->sort('a_term_field.entity.name', 'ASC'), that should work.

Some limitations exists with multilingual fields, as it is not defined on which language it should be sorted.