Block overriding with template file doesn't work

To Alter User login block

Find the template.php file for the theme you're working on. Should be in the root of the theme folder for your theme
Assuming the "yourthemename_hook" function does NOT exist, at the bottom of your template.php file insert the following code:

function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }
function yourthemenamehere_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

Now create a directory inside your theme's directory called "templates" (assuming it doesn't exist already)
Then create a php file inside that folder called: "user-login-block.tpl.php"
Inside this file, put the following code:

    <?php print $name; // Display username field ?>
    <?php print $pass; // Display Password field ?>
    <?php print $submit; // Display submit button ?>
    <?php print $rendered; // Display hidden elements (required for successful login) ?>

    Create an Account | Forgot Password

CRITICAL STEP as an admin on your website, navigate to "admin/config/development/performance" and click "clear all caches" -- if you don't, then these changes won't display on your website
Modify the html markup inside "user-login-block.tpl.php" to your heart's content, and don't forget that you can also add those css classes to your main style.css file (AFAIK)


How to add a custom vertical tab to node edit form?

If you're looking insert renderable elements into the form array in the same manner as the grouped vertical tabs, you can hook_form_alter() your way to this via adding a details form element:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // @TODO: Add your own logic for filtering relevant node forms
  if (in_array($form_id, array('node_page_form', 'node_page_edit_form'))) {
    $form['example'] = array(
      '#type' => 'details',
      '#title' => t(''),
      '#description' => t(''),
      '#group' => 'advanced',
      '#open' => TRUE,
      'markup' => array(
        '#markup' => '
Random Markup
',
      ),
      '#weight' => 1000,
    );
  }
}

If you're looking to add markup that's not relevant to your node forms, you might be better off subtheming Seven and adding your own node-edit-form.html.twig template to your subtheme with your own markup additions:

    {{ form|without('advanced', 'actions') }}

    {{ form.advanced }}

Random Markup

    {{ form.actions }}


Is it wise to edit the default Google Analytics path exclusions?

It should mean that pages such as EDIT nodes, will appear and be tracked by google analytics, which could cause false numbers.  You could change the exceptions by removing the

node/*/*

but including other specifically excluded content, such as

node/*/edit.

You would want to keep an eye on google analytics to see if other pages are creaping in and then exclude them as you find them.


Can I track embedded pdf's in statistics module

The gist of most Drupal performance-tuning essays is don't use the statistics module, because it causes a lot more Drupal DB traffic.

I can't help with configuring the statistics module itself and I suspect the reason the links aren't being monitored is that those files are being delivered from the sites/.../files folder by Apache|Nginx directly, and Drupal isn't seeing them. As such, you might be able to monitor the webserver logs to get the info you need.

Alternatively I would start off by looking at google analytics or some similar client-side tool for this. If that isn't suitable (and it's not guaranteed it is), then next step could be to create a handler for your files, e.g. a ctools module, which parses the path to get the file to deliver, logs whatever info is appropriate and then sends the file onward. There are some issues re: caching and headers, but not very hard.

If you could do that, but are stymied because the file links are entered by the user within nodes, perhaps you could add a text content filter (such as those that break paragraphs at newlines) that read in the original URL and converted those matching the right pattern to the monitored form. That isn't hard either.


Here is some example code. Maybe your selector is incorrect?

$form['main']['elem1'] = array(
  '#type' => 'select',
  '#title' => t('1'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);
$form['main']['elem2'] = array(
  '#type' => 'select',
  '#title' => t('2'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);

$form['main']['elem3'] = array(
  '#type' => 'textfield',
  '#value' => t('3'),
  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="elem1"]' => array('value' => 'A')),
      // XOR.
      array(':input[name="elem2"]' => array('value' => 'A')),
    ),
  ),
);
$form['main']['elem4'] = array(
  '#type' => 'textfield',
  '#value' => t('4'),
);
$form['main']['elem5'] = array(
  '#type' => 'textfield',
  '#value' => t('5'),
  '#states' => array(
    'visible' => array(
      ':input[name="elem1"]' => array('value' => 'A'),
      ':input[name="elem2"]' => array('value' => 'A'),
    ),
  ),
);

And then the alter function.

function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'af_aam_aam_form') {
    $form['main']['elem4']['#states'] = array(
      'visible' => array(
        array(':input[name="elem1"]' => array('value' => 'A')),
        // OR.
        array(':input[name="elem2"]' => array('value' => 'A')),
      ),
    );
  }
}


Messed-up div IDs for ajax-modified form field

function mymodule_form_NODETYPE_FORM_alter(&$form, &$form_state, $form_id) {
    $form['field2']['#attributes']['id'] = 'my_dom_id_for_elem2';
    // or if it doesn't work properly you can wrap the element
    // $form['field2']['#prefix'] = '
';
    // $form['field2']['#suffix'] = '
';

    $form['filed1']["widget"]['#ajax'] = array(
        'callback' => 'on_filed1_change',
        'wrapper' => 'my_dom_id_for_elem2',
        'event' => 'change',
        'method' => 'replace',
    ); }

function on_filed1_change(array $form, FormStateInterface $form_state) {
    // This line is not necessary, at this time $form['field2']
    // has already been modified and you can just return the form element itself, it will be used as response.data by javascript.
    //$form['field2'] = $modified_field2;
    return $form['field2'];

}


Why are non-required fields still showing up in my node_edit template using Page Manager

And I finally found out why:

If the user who's accessing this node_edit form variant has the right to update this field even if it's not required and you didn't add it to the form, it will show up as part of the base form in Node add/edit form (Home » Administration » Structure » Pages)

Hope that helps someone else too.


Custom ckeditor.styles.js file with WYSIWYG module

These are 2 ways (there are certainly more) to add custom ckeditor stylesets using the drupal wyswiwyg module.

Using the contributed module Ckeditor Styles
Using hook_wysiwyg_editor_settings_alter as follows:

(code "inspired" by ckeditor_styles module)

In a custom module add the hook_wysiwyg_editor_settings_alter implementation:

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 *
 * @param type $settings
 * @param type $context
 */
function MYCUSTOMMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  // We only add the settings to ckeditor wysiwyg profiles.
  if ($context['profile']->editor == 'ckeditor') {
    $format = $context['profile']->format;
    $path = drupal_get_path('module', 'MYCUSTOMMODULE') . '/js';
    $settings['stylesSet'] = "mycustomstyleset:/$path/ckeditor_styles.js";
  }
}

and add a file named ckeditor_styles.js in a sub directory js of the custom module:

CKEDITOR.stylesSet.add('mycustomstyleset',
  [
    { name : 'Red', element : 'span', styles : {'color' : 'red' } },
    { name : 'CSS Style', element : 'span', attributes: { 'class' : 'my_style' } },
    { name : 'Marker: Yellow', element : 'span', styles : { 'background-color' : 'Yellow' } },
    { name : 'Heading 4' , element : 'h4' },
    { name : 'Blue Button', element : 'div', attributes : { 'class' : 'blue-button' } },
  ]);


How to send variable to the javascript in Drupal?

The standard way to do this in Drupal is with drupal_add_js(), using the "setting" type, e.g.:

drupal_add_js(array('variableName' => 'value'), 'setting');

That will make the variable available on the JS side at Drupal.settings.variableName.


Support integer or float values as an attribute on a Drupal Commerce "Add to Cart" form

I ran into the same problem (and asked a similar question which I ended up answering myself  here)

Basically with the knowledge you gave I was able to implement a new module which installs a widget for the "list integer" and "list float" types that uses a textfield for input and on POST it sanitizes and adds the value of the textbox to the "allowed_values" setting on the field allowing it to pass the standard list field validation and use the standard list field storage.

This allows you to enter and display a "number" and use the value as a product attribute.  Best part is I did not have to alter another modules code, which addresses the majority of your concerns as:

  The core "options" module not playing nicely with float/int fields.

The options module defines the widget, since you are doing this, you don't need to worry about it.

  Other modules assuming the field is a list of data?

Since you defined your own widget and are not using the standard "options", other modules will not know it exists so you don't have to worry.

  The weirdness around implementing another modules hook.

Again, by adding the sanitized field into the allowed_values setting on POST you pass validation and this allows you to use the "LIST" modules standard implementation of hook_options_list and you don't have to modify someone else's code

As far as your first point on too much data, this is possible that you will have a problem here if you have a multitude of products OR if you are added and removing products all the time (which would continuously add to your "allowed_values" list). For the first point, you could probably also implement a field type in your module and do your own implementation of hook_options_list to follow your logic and just return all the values in your database (i don't have that much so didn't bother).  For the second point, you could implement hook_cron and clean up on the allowed values setting based on the values for the field in the database.

hope this helps and if you have any questions let me know!


How To Enter Data Into A Custom Drupal Entity?

I think everyone suffers the same bewilderment on first meeting ECK. Its workflow is bonkers.

You begin by creating an entity type and optionally renaming the default bundle (which otherwise will have the same name as your entity). I recommend giving the bundle a unique name to avoid confusion in this rabbit warren interface.

Then from the list of entities, click into that entity and then into the bundle. From here you can manage fields - and add your data from the 'entity list' tab. There, the link to add new instances of your entity type will be at the top of the interface - "+ add [name of your bundle]" and the list there will effectively serve as a rudimentary content list for that entity until you can whip something up in views.

If you want to cut through the labyrinth and use a simple link to add your data, it'll be structured like this:

admin/structure/entity-type/[your entity name]/[your bundle name]/add


User photo gallery that another user can view

for some interesting options, take a look at the Album Photos module. I'm not sure if it will do what you're asking OOB, but if you use it, it would change your question so I'll suggest it.

  "Album Photos" is an image album module providing multi-user album
  features. The module development objective is to provide a
  comprehensive image album solution for Drupal.

  Version 7.x-3.x Highlights

  Integrates with core image styles. Uses Libraries API 2.x for
  Jeditable. Built in support for Colorbox. Vote on images with Voting
  API. Comment on images. Built in support for Plupload. Upload multiple
  images with Plupload. Limit the number of albums created per role.
  Reads image exif parameters. Nice presentation of the images. Views
  integration. Support for private file system. Drag and drop interface
  to re arrange photos and albums to sort by custom weight order. Photos
  Access Included as a sub module. Enable this module to control who has
  access to the photos and galleries.

  Create password protected photo galleries. Create galleries with a
  list of collaborators who can edit the same gallery. Create private /
  locked galleries that can only be seen / edited by the gallery owner.
  photo gallery, image gallery, user managed photo albums


Append parameter to URL accross all pages

The best hook for this is hook_url_outbound_alter. This affects links generated by url(), which is used by most/all code generating urls and links in Drupal.

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // If the param of interest is present and the url being generated is internal.
  if (!empty($_GET['country']) && !$options['external']) {
    $options['query']['country'] = $_GET['country'];
  }
}


Problem with product page (sidebar goes down)

Ok, mine is inside an article container. Go to Appearance -> Commerce Kickstart -> Settings -> Zone and Region Configuration and check Content Section -> Content Zone -> Regions.

There should be Sidebar First, Content, Sidebar Second in order. Make sure all of those are in there.

I do know I ran into this issue but mine was CSS related (I changed the width of the content region). Check your settings above and make sure everything looks good. No unassigned regions etc. Try a full wrapper if you don't have one and try without if you do and see if that changes anything.


I'm not aware of any architecture that can guarantee publishing of N number of items exactly at some atomic time -- as the number of items N increases; you will always have more processing time given linear execution.

It sounds like they used hook_cron and an interval check for publishing unpublished items.

Option 1 (get rid of interval cron and provide 1 specific cron task @ time)

They could easily change the architecture to use a specific cron task to check at a specific time via Cron and publish all unpublished items via a Drush task -- removing timeout errors.

This requires new, relatively easy code.

Option 2 (parrallelize option 1)

call option 1 with like ultimate_cron module and background task, with N tasks to publish approximately N content items; parallelize the publishing process to limit how long it takes.

This is new harder code, and harder to debug.

Option 3 (crazyiness here)

create an unreachable directory which can be scraped. Scrape the result of viewing the Drupal pages final result to static files; remove restricting .htaccess file or rule at 11pm based on a simple cron task. Eg, make all your dynamic content -- into static pages prior to release and make they public instantly. Your page content may not allow this approach -- but everything would be made public in an instant.

This is crazy and pretty much a rewrite of any approach and removes Drupal and largely the DB almost (but for a reason).

Whose fault is the problem

Well, no 1 party is at fault ... the requirements were vague on how many items (at most) would be published at X time and also how long a lag in publishing is allowed.


How can I get form_ids for all forms my module implements?

Forms aren't implementations of anything as such, they're just plain PHP functions that happen to return a certain structure by convention. There's no registry of forms or anything like that, and the module that a form is defined in isn't tracked anywhere (it's not information that Drupal needs). Form functions don't even have to be named in any particular way.

There's also hook_forms() which allows you to map multiple form IDs to a single form callback function, so that's an extra layer of complexity that would need to be handled somehow.

I can't think of a single reliable way you could get that information through code. Well, I'm sure you could use reflection to write something very specific to your module, provided your own form functions follow a predictable naming convention; but as far a generic solution goes, I'm 99.9% sure it isn't possible. Unless there's a creative way around that I'm just not thinking of.

If it's just for this single module, why not just write a function which returns an array of all the known form IDs. Then when you add a new form, update that function manually. It will be much easier than implementing the reflection code to do this.


Can multiple users edit a node to create several different revisions without being able to publish them?

The Workbench module with Workbench Moderation seems to do what you require. Users create drafts, which can then be markled for review. Once an admin reviews the content he can choose to publish it, update it or send it back to the user for further work. Each user has their own drafts, so different users can have drafts of the same document.

You can have as many stages and transitions as you want, so you could have a reviewer role who reviews content and sends it off to a publisher role to be published.

Workbench is Drupal 7 only, but Workflow seems to do similar things for Drupal 6, although I've got no experience with it personally.


Permission for specific role to edit ANY comment

The permission drupal gives by default says 'edit own comments'. I do not see a permission which allows 'edit any comment'. Try using User Tweaks module. Module page says

  edit any comments (and edit any  comments), which allows
  user with the Post comments permission to edit comments. The
  permission is not required for users with the Administer comments
  permission.

Updated Answer-

I just saw the comment module code.
You simply have to give Administer Comment Permission for that Role, but it will give delete permission as well.

If you are comfortable in custom coding you can alter the access callback for comment edit menu item.

If you see hook_menu implemented by comment module, here is the delete menu item code

 // Every other comment path uses %, but this one loads the comment directly,
  // so we don't end up loading it twice (in the page and access callback).
  $items ['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'comment_edit_page',
    'page arguments' => array(1),
    'access callback' => 'comment_access',
    'access arguments' => array('edit', 1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );

which basically calls comment_access function as

function comment_access($op, $comment) {
  global $user;

  if ($op == 'edit') {
    return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  }
}

You can implement hook_menu_alter to change access callback for edit, something as below.

  // Implements hook_menu_alter
  function mymodule_name_menu_alter(&$items)  {
    $items ['comment/%comment/edit']['access callback'] = '_my_module_name_custom_callbck';
  }

// Access Callbck for comment edit.

  function _my_module_name_custom_callbck($op, $comment) {
     if ($op == 'edit') {
     global $user;
      return (in_array('your_user_role', $user->roles) || $user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
    }
  }

Note: I have not evaluated why drupal is not giving it by default, it will still be important to identify.


You can use the Conditional fields module.


How to fetch views field label in hook_views_pre_render?

Try $view->field[{field machine name}]->options['label']

The $view object has a property 'field', which is an array of all fields set in your view. You need to select the one labeled 'Name'.

Each field is listed using its machine name as key, hence {field machine name} as a placeholder. You need to replace that with the actual machine name.

The field in that list again is an object, with a property 'options'. This is an array of all options, including alterations, whether the field is excluded or not, etc. In those options is also an index called 'label', which contains the field's label.


This might be a fix for your problem, perhaps you should try this on your test environment: https://www.drupal.org/node/2060519


Where to use the php functions when adding fields to existing nodes?

Fields are attached to Entities, not Nodes. So the field is either attached to bundle that is your node (for all nodes, pre-existing or not), or it hasnt been attached to that bundle yet.

You can use field_info_field and look at the element bundles to see if your given field is attached to the given Entity. If it isn't you can use field_create_instance to add the field to your entity.

You can get a list of all entity types and inspect their bundle types with the bundles key returned from entity_get_info by calling $site_entity_list = entity_get_info(NULL).

Entities and fields are cached, so be sure you use something like drush cc all to be sure you're looking at up-to-date values for all these function calls.

EDIT:
You use these functions and PHP from essentially a small php script. Such business logic could be in a small module with hook_update_n() for instance. Or, you could use Drush and write a very simple PHP snippet using hte above 3 functions and some loops and call it using drush like:
drush php-script your-script-filename.php


If your module name is

gissue_issue

Then you could have a hook namespace collision with

hook_load

In which case the $nodes parameter is being passed to your load function as well.

Just a possibility to consider.


In that case, what you'll want to do is set this variable: commerce_checkout_redirect_message. This variable is used by the module to populate the message.

For example:

variable_set('commerce_checkout_redirect_message', 'You must log in to continue.');


How to create a search box bloc with search API

Although you can expose the views form as a block and you can add it twice to a page, the issue is that you may just want a keyword search form in the header but on the actual form you want something more. An additional peculiarity was that the infinite scrolling plugin makes the form ajax, and when exposed as a block it fails to submit.

My solution was to create a new form + block and place the block it where I needed it:

my_search.module:

<?php
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter() for the search_block_form form.
 */
function my_search_form_header_search_alter(&$form, FormStateInterface $form_state) {
  // NB so that these are not added to the get query params
  $form['form_build_id']['#access'] = FALSE;
  $form['form_token']['#access'] = FALSE;
  $form['form_id']['#access'] = FALSE;
}

HeaderSearch.php:

<?php

namespace Drupal\my_search\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class HeaderSearch.
 *
 * @package Drupal\my_search\Form
 */
class HeaderSearch extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'header_search';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#action'] = '/search';
    $form['#method'] = 'get';
    $form['k'] = [
      '#type' => 'search',
      '#title' => $this->t('Keyword'),
      '#maxlength' => 64,
      '#size' => 15,
      '#title_display' => 'invisible',
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      // Prevent op from showing up in the query string.
      '#name' => '',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Form is redirected no need for anything here.
  }
}

MySearchBlock.php:

<?php

namespace Drupal\my_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'MySearchBlock' block.
 */
class MySearchBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\my_search\Form\HeaderSearch');
  }

}


How to access to form field in views-exposed-form.html.twig (exposed filters)

Solved. The problem seems to be an incompatibility with Better Exposed Filters module.

Thanks!


While custom code seems to be good option to achieve the transaction of item ownership, User Points module may help in transaction of items.

In custom way I would have created item as content type with user reference field for item ownership, I would have turned on revision on item content type so to get detailed report of transfer of ownership and on every transaction of item would have updated the ownership field with new owner, maintaining the revisions. User Points module provides handy api's custom integration and it also provides rules integration which looks more robust system to expand user points in future also.


How do I alter the complete url, not just the path, of nodes?

InboundPathProcessorInterface can't do it, that's an incoming request, it has no way of redirecting to another site, because that's what you have to do.

Implement something similar to redirect.module: a request subscriber that sets a redirect response.

For outbound processing, that definitely works, but you have to set the right options. Have a look at how \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::processOutbound() sets the language domain.


Panels to do a specific layout for one content type edit mode

Page manager (which, technically isn't the same thing as Panels), manages the url node/% differently from node/%/edit.

When you to go Pages, you need to enable the node edit task, and make configuration to that page, not the node view one.


Views - Add a wrapper around fields or rows

I think it's pretty safe to say that most people tackle both of your questions using the Cascading features of CSS.

For example, a typical view's HTML looks somewhat like this:

So, to your 1st question, Views already creates a div that wraps each row, that's the
 one.  You can style it per view by doing something like this:

.view-NAME .views-row {
  /* styles for the rows div goes here */
}

And to your 2nd question, Views also already creates a
 that wraps all the rows, that's the
 one.  To style it for a particular view you can do something like this:

.view-NAME .view-content {
  /* styles for the div wrapping your rows goes here */
}

Now, somewhat obviously, this is all dependent upon your theme.  I am aware that some out there dislike all the markup Drupal by default creates and has overridden a lot of the standard templates to create leaner markup.

If that's the case in your instance, you should still be to instruct Views to add a class to each row if you want.  This is accessed via the overall Style Settings (where you can also look at each Views template that is used for the particular view).

You could also instruct Views to add a class to each field wrapper.  This is accessed from the config widget by each field.

ADDITION based upon commentary:

The Views template that creates the output of the view-content div is views-view.tpl.php and the code in question is:

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

so without changing this up, you're right, Views doesn't allow quick and easy preprocessing of the View to insert any other variables into that div's classes.

You could however use Views' preprocessing hooks to create an additional variable so you don't need to create lots of additional templates but rather just one more.

For example, copy views-view.tpl.php to your theme (easiest) or module (requires special Views theme incantations :) and modify it along these lines:

<?php if ($rows): ?>
  <div class="view-content <?php print $my_special_content_class; ?>">
    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

and then create a views preprocess hook along these lines:

function YOURTHEMEORMODULE_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['my_special_content_class']='FOO';
  } else {
    $vars['my_special_content_class']=''; // so we don't have to isset() or !empty() it in our template :)
  }

}

Save everything and clear your theme cache and now you should be on your way.

SECOND ADDITION:

Upon further thought, and a 'doh!' moment, you can do this without a template at all in preprocess like this:

function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='VIEWYOUWANT' && $display_id=='DISPLAYYOUWANT') {
    $vars['rows']='
' . $vars['rows'] . '
';
  }

}

if you don't mind another wrapped div in there.  And, I think you will need to/should do this in your theme instead of a module so you make sure this happens in the right order, eg, you want this to happen after Views is all said and done with things, and the theme hooks always run after the module hooks.


This is a known issue - Topic command does not work when using Phar. Searching the issue queue is always recommended. Since the current version is Drush 9, I don't expect this to be fixed.


How to automatically create subitems based on node entries?

Try the Content Menu module.

This module provides an easy way to add existing nodes (content) as a sub item  to menu.

  Content menu module improves Drupal's default menu management interface for tighter integration of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created.
  See the screenshot


After Drupal 7.32 should sql injection attempts create PDOExceptions?

It is my understanding that in theory, yes, a compromised site from the particular vulnerability could lead to such behaviour. As Drupal.org recommends, in such cases you should treat your site as compromised and all next actions should be the appropriate for this case.

The fact that you patched the site shortly after the announcement, as you mentioned, is very important. As far as I have seen, most attacks are coming from scripts and it has not come to my attention any automated attack that would cause such behaviour (to my experience of course). This again is not reassuring, just a thought on the possibility for the nasty thing to have happened.

Apart from the obvious actions (see links below), I would definititely take a good look of the code that doesn't behave nicely. Also a good tool is always diff comparing to clean code. I would as well take a good look in the db. Last, there might also be a possibility that some contributed module has got issues with 7.32 or maybe anything else that might have been updated.

Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?

https://www.drupal.org/drupalsa05FAQ


I will tell you that the easier way it to use node_load. You do your query to simply get the last nodes according your criteria and then with the nid you load each node with node_load.

Why ? Because CCK changes his database structure according the fields that are attached or not to one or more content type. If you will change the CCK field one day, you will have to change your code, so the easier way to avoid it, its simply use node_load.


How can I debug adding libraries via hooks?

To attach a library to a certain paragraph type you could use template_preprocess_paragraph__PARAGRAPH_TYPE() like following. Note how it's just added to the $variables array not the element.

function MYTHEME_preprocess_paragraph__slider(&$variables) {
  $variables['#attached']['library'][] = 'MYTHEME/carousel-styling';
}

Same with the field. Simply use template_preprocess_field__FIELD_NAME() and attach the library directly to the $variables array.

Your content-styling and carousel-styling libraries probably should look more like following. Note how it's added as theme category, not as base. See the docs on File Structure for some info about SMACSS.

content-styling:
  css:
    theme:
      css/content.css: {}

And finally: Flush cache, flush cache and flush the cache again!!!!!!!


How do I set the "Save draft" button by default on all webform nodes?

/**
 * Implements hook_webform_node_defaults_alter().
 */
function mymodule_webform_node_defaults_alter(&$defaults) {
  $defaults['allow_draft'] = '1';
}


Duplicate Results in View with OG Relationship

Okay, so I believe I traced the issue to a problem with Entity Reference Relationships in Views, and posted a bug.

However, I was able to solve the duplicate issue AND get the results I wanted (all titles from related groups) by taking a different approach in the View.

Instead of hook_query_alter() or hook_views_pre_render(), I just wound up adding the field that reference the groups, setting the Formatter to "Label", and checking the "Link label to referenced entity." This produced a comma-separated list of groups linked to the group page (exactly what I wanted).


How do I add a minipanel to a panel page?

I found the problem: It was because the Mini Panel contained a Block that was also contained on my Panel Page. Once I removed the block on the Panel Page I was able to add it.

I wish there was a way I could have the Block in both, but I guess not.


Yes, Views data export is your best choice.

Create a view displaying users and add a page display. Add the fields you want in your export and change any additional settings you want.

Then add a display of type Data export, and set it to attach to the Page display. This way it'll add a link to the file download to that page (You can probably also skip the Page display and only add a Data export display with a path defined).

Choose your export format (CSV) under format settings. If you have a lot of users, make sure to choose batch operation under 'Data export settings'.

It's also a good idea to require a specific permission or role to access the view.


Updating composer autoloader after moving modules

I am using this to refresh module paths. I tried all other combos with apc_clear_cache etc and didnt help, also nginx restart didnt help, this 2 did.

service php7.2-fpm restart
drush cr


How to implement a multi step approval with webforms/entityforms based on form components?

Implementing this workflow is possible by using a combination of these modules (and regular content types, no need for something like "webforms"):

Rules.
Node Convert.
Flag.
Content Access.

Refer to my answer in the question about
"How can I allow anonymous visitors to submit content?" for examples (and more details) about how to use these 4 modules together (this question here seems like a variation of that question).

Below are some details to implement your workflow with a similar approach:

  An employee submits the form

Employee create a node of content type (say) "Request" (Use Content Access to finetune all sorts of permissions about "which role is allowed to create such types, if you have multiple types of requests you just extend to multipple content types).

  Supervisor gets notification, after reviewing the form, he either approves it or denies the request on the same submission.

Use Rules to "send an eMail" (= action) to Supervisor "After content of type 'Request' gets saved" (= event). In the (custom) eMail for the Supervisor, include all relevant details about the Request (depending on the various data that are available to Rules). Such as an URL of the node to be reviewed.
To ensure the Requestor cannot change the Request data (while the review process is outstanding), add an extra action to the same (previous) rule which updates the access to the Request (to make it read only for requestor).
Use the Flag module to enable the Supervisor(s) to mark the submitted node with flags such as 'Approved (by Supervisor)' or 'Denied (by Supervisor)' (Rejected?). The permission to set these flags is limited to the Supervisor(s).

  If approved, an email notification gets sent out to Director who in turn approves or disapproves the same submission.

Use Rules (again) so that "After a node gets flagged with 'Approved (by Supervisor)'" (= event), it causes a similar "send an eMail" (= action) to Director occurs. In the (custom) eMail for the director, include all relevant details about the Request (depending on the various data that are available to Rules). Such as an URL of the node to be reviewed.
Use the Flag module (again) to enable the Director to mark the submitted node with flags such as 'Approved (by Director)' or 'Denied (by Director)'. The permission to set these flags is limited to the Director.
Use Rules to "send an eMail" (= action) to Requestor "After content of type 'Request' gets flagged as denied (by Director)" (= event).

  If denied by supervisor, an email gets sent to an employee.

Use Rules to "send an eMail" (= action) to Requestor "After content of type 'Request' gets flagged as denied (by Supervisor)" (= event).

So just some basic Rules/Flag stuff ...

It does not (yet) include anything related to Node Convert. This module only needs to be added to this mix if you want to further refine the above with specific "fields" that some of the workflow participants should not "see" at all (to avoid you'd have to use "field permissions", which could be an alternative to that.

Possible enhancements

Form Block

I've no experience with the Form Block module. On its project page it says "Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.".

It seems to me that if you're using panels then there is possibly some added value when using this module. However, I'm not convinced (yet) about the real added value of this module.

There are a few things though that seem to me like red flags (= I'd think twice before using that module):

Where is the documentation?

Apart from what it says on the project page, there is (a) no community documentation (at least not linked to from the project page) and (b) some readme.txt that comes with the module, but with no "real" content.
Where is the D7 release?

There is an official release available for D6. But a D7 version only exists as an alfa 1, which is over a year old. And then there is a D8 version in beta status already. Not sure what is coming up in D8, but for D7 there seems to be something wrong. Is there ever going to be an official D7 version? Nevertheless, looking at the usage statistics there are a lot of D7 sites. Close to 10K reported installs for that D7-alfa version. 10K sites using the modules can't be wrong, so it must be something like "that alfa1 version is virtually an official release that should be tagged like so".

The above bullets are just a few of the criteria I often use for deciding on contributed modules. Refer to the community documentation about Maintenance Scorecards for more details. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Bean

Maybe consider adding another module in the area of Blocks, by looking at the Bean module. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

Combined with the options available for granting the appropriate Bean permissions, it should give you a lot of flexibility about how exactly you want to use this (great) module in your specific case. As a bonus, the Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module (which somehow compensates the fact that you need to add another module).

Video tutorials

If you're not familiar with Rules, checkout the video tutorials Learn the Rules framework. And/or the similar set of 8 video tutorials about the Flag module.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of the Bean module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.


Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'?

Directing using

global $user
$user->uid

adds a new variable to your current scope, which adds potential for misuse and other accidents.

Using

$GLOBALS['user']->uid

can be seen as a safety precaution.  You can still mess things up, but it is somewhat harder, and you don't introduce a new variable.

However, directly poking around in the $user object is bad in a lot of cases, especially explicitly using $user->uid.

Whenever possible, you should leverage the API.  For example, use

if (user_is_logged_in()) { ... }

instead of

global $user;
if ($user->uid) { ... }

and use user_access() instead of using $user->roles.

One place where explicit $user->uid use may be needed is with database queries, though that can be lessened somewhat with EntityFieldQuery->addAccount and db_select->addtag('node_access').


How do I sync taxonomy terms with the second level of a menu?

I used this on a site a few months ago to essentially do the same thing:

function _foo_add_submenu ($menu_name, $vid, $plid)
{
  $vocabulary = taxonomy_vocabulary_load($vid);
  $tree = taxonomy_get_tree($vid);

  if (count($tree) > 0) foreach ($tree as $term) {
    $item = array(
      "link_path" => "taxonomy/term/{$term->tid}",
      "link_title" => $term->name,
      "menu_name" => "menu-menu",
      "plid" => $plid,
      "router_path" => "taxonomy/term/%",
    );

    $sql = "
      SELECT menu_links.mlid
      FROM {menu_links} menu_links
      WHERE menu_name = :menu_name AND plid = :plid AND link_path = :link_path
    ";

    $result = db_query($sql, array(
      ":menu_name" => $menu_name,
      ":plid" => $plid,
      ":link_path" => $item["link_path"],
    ));

    $record = $result->fetchObject();

    if (isset($record->mlid) && $record->mlid > 0) $item["mlid"] = (int) $record->mlid;

    menu_link_save($item);
  }

  menu_cache_clear_all();
}

$menu_name is the menu to mess with, $vid is the vocabulary to build from, and $plid is the item to add to.  When you run this, you will end up with a real menu in admin/structure/menu/manage/menu-whatever.  You will need to add some additional housekeeping functions to handle adding terms, removing terms, etc, but they all involve similar functions and menu_link_save / menu_link_delete and menu_cache_clear or menu_cache_clear_all being called from the right taxonomy hook.


How to pick the most expensive shipping rate

seems like your 6€ shipping rate does not have a maximum, so it gets listed again ?


How to query for a list of tables in a secondary database

$conn = Database::getConnection('default', 'civicrm_test');
$database = $conn->getConnectionOptions()['database'];
$conn->query("SET FOREIGN_KEY_CHECKS = 0");
$tables = $conn->query('SHOW TABLES')->fetchAll();
foreach ($tables as $table_result) {
  $table = $table_result->{"Tables_in_$database"};
  $conn->query("DROP TABLE $table");
}
$conn->query("SET FOREIGN_KEY_CHECKS = 1");
$conn->destroy();

I only needed to disable/enable foreign key checks, because I needed to. Others may not need to.


How can I use my table for Views 3 sort criteria?

You can let Views know about your data using hook_views_data.

The function documentation itself contains all the information you need to use the data for sorting and other Views functions, so I'm not repeating them here.


As Clive pointed out,

  You have javascript errors, the most common cause of that in the admin
  theme is using the jQuery Update module with its default settings. If
  you do have that module installed, just go to its config page, and
  select the default Drupal jQuery for the admin theme

The Jquery Update Module cause the problem. I configured the module and set my Jquery version to 1.10. This solved my problem


How to integrate JS / CSS only on specified Pages / custom content types

The concept given by Molot is good. Because url can be changed any time.

Still you can add the css and js file using hook_preprocess_page or yourtheme_preprocess_node in your template.php of active theme.

function yourtheme_preprocess_node(&$vars) {
// Add JS & CSS by node type
if( $vars['type'] == "your-node-type") {
drupal_add_js( /* parameters */ );
drupal_add_css( /* parameters */ );
}

where yourtheme need to be replaced by the name of the your active theme.
Please clear cache for changes to reflect.

Hope it will work for you.


See module's INSTALL.txt file:

  If the site is using HTTP Basic Authentication (the browser popup for
  username and password) you can embed those in the url. Be sure to URL
  encode any special characters:

  For example, setting a user name of "myusername" and password as,
  "letme&in" the configuration would be the following:

  $conf['stage_file_proxy_origin'] =
  'http://myusername:letme%26in@example.com';

Another way, if you have a static IP, is to bypass the Apache auth for certain IP addresses.


Try using

global $user;

if(!$user->uid) {
  drupal_set_message("You must log in to view this content.");
  drupal_goto('node/153', array('query'=>drupal_get_destination()) );
}


Can't get the key of webform's select field in the results

It is a bit of a pain. Looks like you have to do this each time, but here goes...

Go to your Webform in question...

Click the Results tab
Click the Download button
Open the Select List Options section
Under Select Keys, choose "Short, raw options (keys)"
Set any other options as you need and then click Download

You should have a file where the select option columns are populated with the keys rather than the values.


What you are trying to do is to use module in alpha version (bad practice) that keeps PHP code in database (very, very bad practice)  for task that can be accomplished by modules without these flaws, like Views Calc, Views Aggregator Plus or even built-in aggregation.

My current favourite is Views Aggregator Plus:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

And example on it's page is quite similar to what you want to accomplish here.

For a whole table sum, just add Global: mathematical expression column to sum values in row, and then Views Aggregator Plus to sum that column. Column may be hidden, for example with CSS.


How to show images below a select box according to the value?

As far as I know there are no ready made solutions for this, and you will need to write a custom module. The way to do this would be to implement hook_form_alter to modify the select element and add a #ajax property.

If you've never written a module with hook_form_alter then this article might be of help: very-introduction-drupals-hookformalter

And here are some relevant questions on Drupal answers:

adding-ajax-to-existing-node-form
how-to-use-ajax-in-form-alter-in-drupal-7


Sounds like the theme you are using is doing this. The answer may have nothing to do with the Webform module.
When you use a Theme provided by a company that sells themes, you are building your site ontop of a site that they already built for you. Yes, this saves some time, but sadly, you have to find out how that site works. Often times, they have made some "very interesting" decisions that can not be easily explained.

Do you have a link to this page? I am wondering if maybe that title is appearing in a BLOCK. If you mouse over that title, does a gear appear to the far right of that title?

As for the terminology, I do not know. This does not sound like the way Drupal handles titles. I suspect the crew that built this theme made interesting decisions.
The webform module simple creates nodes where the content is fields.
Each webform-node has a node-title in the same way that all nodes have titles.
To edit the title of a node, simply edit the node and change the title and save it. The new title should appear.
If this is not how your site works, then whoever built the theme is doing something very strange.

I hope that helps.


How to attach media item created during migration to media field in node

When I have done a similar type of migration at that time I did the following steps:

First I created media type Audio in Drupal 8 and it's fields.
Then I exported all audio file details and FID from D7 and created csv file.
Written migration script to import audio into media.

Example:

source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
  type: audio
  constants:
    bundle: audio
process:
  mid: fid
  bundle: constants/bundle
  langcode:
    plugin: default_value
    source: language
    default_value: und
  name: filename
  uid: uid
  created: upload_date
  changed: upload_date
  field_media_audio_file/target_id: fid
destination:
  plugin: 'entity:media'
  migration_dependencies: {  }
migration_dependencies: null

The same csv I used to import data into file entity and written migration script.

Example:

source:
  plugin: csv
  path: 'csv file path'
  header_row_count: 1
  keys:
    - fid
process:
  uid: uid
  fid: fid
  filename: filename
  created: upload_date
  changed: upload_date
  filemime: mime
  uri: uri
destination:
  plugin: 'entity:file'
  source_path_property: filepath
  destination_path_property: uri
migration_dependencies: {  }

After that, I attached the FID to my node field.

process:
  field_audio/target_id: fid

  I am keeping media id, FID of Drupal 8 same as FID of Drupal 7. So we
  can attach the same FID to the node directly.


Using the Field collection module in Drupal 8 seems to NOT be a good idea anymore. It currently only has an alfa1 release from April 2016). Instead you may want to try to use Paragraphs instead, as suggested also on the Field collection project page, i.e.:

  Paragraphs is likely to replace field collection for Drupal 8. Field collection is on its way to being deprecated. It is recommended to use paragraphs instead of field collection for Drupal 8 projects.


Autocomplete field consisting of multiple fields

Instead of using Node Reference (References), I suggest you to use Entity Reference module. It has an option to build the autocomplete options with a view so that you can add other fields.


Drupal 7 "undefined function" fatal error; from FTP error

If you have a backup this is the time to use it.

If not you should:

Put your Site in maintenance mode from command line: https://drupal.org/node/590468 or by using Drush: drush vset maintenance_mode 1
Replace the deleted module with exactly the same version in exactly the same place.
Run update.php either from drush: drush updb or command line: https://drupal.org/upgrade/running-update-php
All should be fine.

Please report back if this works or if another solution is found


How can I link an image of a jCarousel to a certain link?

I assume you're using views and jCarousel and Drupal 7.

On same content type that you have your image fields, add a new link field. Add this link field to your view but check the Exclude from display checkbox, set the Formatter to URL, as plain text and make sure the link field is before of your image field in order.

Edit your image field settings in the view and, under Rewrite Results, check Output this field as link. Scroll down to the replacement patterns and copy the pattern that references your link field. Put this pattern in the Link Path text box.


How to pass argument to php file using a drush command?

This is explained quite nicely in drush topic scripts.

Your script should start with:

#!/usr/bin/env drush
<?php

Then, you may call your script directly. For example, if you have saved your script in a file called myscript, then you would call it via:

$ myscript a b --flag=bar

Drush provides a method called drush_shift that allows you to access you one at a time:

$first = drush_shift();
$second = drush_shift();

In the above example, $first will be a and $second will be b.  You may access your options via drush_get_option() as usual.

$flag = drush_get_option('flag');
$other = drush_get_option('other', 'default');

In the above example, $flag is bar and other is `$default'.

Note that you can use $argv as suggested in the other answer, but if you do this, your arguments and options will be mixed together, and you will need to parse them yourself.  Using drush_shift() and drush_get_option(); is more convenient.


multiple values of several fields grouped together

You should look at field_collection module. It allows you to create a field, and add fields to that field (behind the scenes it's using entities).

A typical use case, is if you want user to enter multiple sets of data, like fx

name
image
url

To achieve this, you would create a field_collection field on the node or what you want this on and set the cardinality to the limit. Then on the field collection you would add the name, image and url fields. It's also possible to configure some fields to be required and other to be optional.


Hide the header of a view block when there is no content

Well I think you are asking how to hide a block view completely when it is inserted as a global: view area in the header of another view.

  For the parent view:

When inserting the block view into the header of another view, make sure you leave the box unchecked that says: Display even if view has no result

  For the block view that is being inserted check these 3 things:

1:
If you are displaying fields in the block view, you want first make sure you are hiding any empty fields under Show: Fields | Settings

2:
Then you want make sure you you have the Hide block if the view output is empty: set to yes under the advanced tab in the block view.

3:
You also want to add a contextual filter for the block view that defines the context you want. Then set the WHEN THE FILTER VALUE IS NOT AVAILABLE setting to hide view. (For the image below, my context needed was taxonomy term ID.)

Hope this helps!


Add a link field using CCK for the content type.
override the label output to include the rendered link in the View.


If you are willing to upload zip files, then maybe Pack & Upload could work for you.

Although I haven't used this before, I would assume that folder structure would remain.


So it is pretty obvious that module means that entry was added by either the file, imce or user modules, right?

Right, it's just the name of the module that added the record.

  What does node, file and user mean in this context?

They're arbitrary strings used by each module to identify the "type" of file usage the current record relates to. A single module might keep to track of files in several different contexts, so this is important.

  Is file/node effectively the same as imce/file, or is it something different?

They're different. file/node is for usage of files attached to a file field on a content type; imce/file is for tracking files uploaded and (potentially) inserted into a WYSIWYG.

  Does user/user mean it is a file associated with the user?

It doesn't have to necessarily, just because it's called user/user, but in this case yes, it does.

  Further file_usage has an id column; can I assume:...

Yes, that assumption is correct. The ID can relate to anything at all though, not just an entity that lives inside Drupal, it's up to the module using the table to be able to resolve which object/item is being referred to from the data in that table.


In addition to Yuri's answer, I wanted to provide more detail for how I solved this issue, where I couldn't resolve the following error:

  No PDF generation tool found! Please download a supported PHP PDF generation tool

install the print module
install pdf php handlers and libraries for your environment from https://wkhtmltopdf.org/downloads.html; see note
create symlink in sites/all/libraries/wkhtmltopdf to library in server; make sure symlink is executable to the server sudo chown -h [owner]and sudo chgrp -h [group]
install and enable phpwkhtmltopdf
run drush make --no-core -y sites/all/modules/contrib/phpwkhtmltopdf/phpwkhtmltopdf.make
enable print_pdf_wkhtmltopdf
set up and customize; see recommendations in this blog for more
info

Note: My local dev environment is on a Mac OS X so I had to download and run the package, then create a symlink to sites/all/libraries/wkhtmltopdffrom /usr/local/bin/wkhtmltopdf

Sources:

https://www.drupal.org/node/2430561
https://www.sitepoint.com/effective-pdf-generation-drupal/
https://wkhtmltopdf.org/downloads.html


You can use the session that Drupal creates. Just add your data to an element of the $_SESSION variable:

$_SESSION['my_module']['some_key'] = 'some value';

It will


Make quiz link look like a button or apply css style

I just needed to apply custom CSS to a.quiz-start-link and .certificate-link respectively and then it worked.

I also learned about templates and this SE Post was helpful for creating a custom template for quizzes, so I could change the class that was being used like I originally wanted to: How to theme a quiz in D7?


I did end up increasing the RAM in the conf file. Since I've noticed no  evictions. In fact the eviction stat is at 0 at the moment.


It looks like your languages table is missing. I hope you backed up your database before starting the update. If you have a backup, try restoring it and retry the update again.


Hierarchical Views Catalog using Taxonomy in Drupal 8

Ubercart for Drupal 8 has a catalog example that might be a solution for you

https://ftp.drupal.org/files/projects/ubercart-8.x-4.0-alpha4.tar.gz


A request to a REST API should just return required data and end. If you want to do asynchronous tasks do not reuse request threads, use cron tasks.

If you want to get independent from Durpal cron use your own drush command executed by a system cron. So, you declare a drush command that makes whatever asyncrhonous tasks and then declare a system cron that runs drush on that command.

If you need to prepare data for that command (for example, if some REST API functions generates data that must be processed asynchronously) you can use Drupal Queues. When the API is called add a new element to a certain queue that will be later processed by the drush command.


Comma seperated text field into a HTML ol

You can make use of hook_node_view like this

function hook_node_view($node, $view_mode) {
  // explode the field contents with comma
  // replace the content with your exploded value.
  $node->content['yourfield'] = 'YOUR_EXPLODED_VALUE';
}

explode


How do I display user picture from profile fields?

Private Message displays the user picture via a theme('user_picture') so I'd just copy the user-picture.tpl.php template out of the system user module directory and into your theme's and modify it to display your field instead of the default.  You may want to put additional logic in there so that it doesn't do this everywhere but that's up to you.


Since you don't know the password, only the hash, you can't migrate it directly. (MD5 is weak, but not that weak.) The whole purpose of hashing is that the password should be unknown to anyone except the user. There are 2 solutions to this.

Reset all your users password and send a one-time-login password to them once they are migrated - as already suggested in the comments above.
Write custom code that rehashes the password at login: "If the password is hashed with MD5, rehash it and store the hash when the user (successfully) logs in." This works because at login you have the user's password because they just entered it. And you know which hashing algorithm is used from the stored hash.Initially, you migrate the users with the MD5 password hash.

It turns out that Drupal does rehashing automatically (see UserAuth::authenticate()), but not for MD5 unless you modify the  existing hash slightly by prefixing it with an "U". (Thanks, d70rr3s and  Souvik Das.) See also user_update_7000.


How to set programmatically Line Item Price?

I have struggled a bit with this, as have others apparently, but i found the solution in another thread.

Every time an order object is loaded the following function is fired:

commerce_cart_line_item_refresh()

In this function the unit price of the Line Item is set to the current price of the original product, so even if you change the unit price, when you create the line item, its changed back to the original price the next time you load the order object.

So rather than setting the unit price of a line item, when you create it, you have to do it every time it's refreshed - For this Drupal Commerce offers the following hook:

HOOK_commerce_cart_line_item_refresh($line_item, $order_wrapper)

Heres a coding example:

function YOUR_MODULE_commerce_cart_line_item_refresh($line_item, $order_wrapper){

$line_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

$label = $line_wrapper->line_item_label->value();

//Only alter price for a specific product type (you could choose other selection critirias here)
if ( $label == 'YOUR PRODUCT TYPE'){
    $new_price = calculate_new_price(); //I use a function to calculate a price, you could set a static price instead

    if(!empty($new_price)){
        $line_wrapper->commerce_unit_price->amount->set($new_price);
        $line_item->commerce_unit_price['und'][0]['data']['components'][0]['price']['amount'] = $new_price;
        $line_wrapper->save();
    }

}

}

function calculate_new_price(){

//Do what ever pricing logic you need here

//Here a static price of one dollor
$price = 100;

return $price;

}


entity reference as attribute, is it possible in commerce v2?

Since product attributes are entities in CommerceV2, the following module should cover your needs => https://www.drupal.org/project/entity_browser

Some points to consider:

It is still in alpha
It is strongly supported at the moment by the community and especially the Drupal Media Team
It has more than 5K downloads.

There is also a recent presentation available from DrupalCon Dublin 2016 => https://www.youtube.com/watch?v=VXor-HZiYrs

Update:
Following the documentation, you may also need to look into "Product Variations Fields", http://docs.drupalcommerce.org/v2/product/products.html.
This CV2 functionality seems to allow you to expose specific fields to the end-user for e.g. uploading images in order to modify/configure a product.

Good luck!


How to select only time without attaching a date?

You can use datetime element and disable date widget:

$widget['time_container']['time'] = [
  '#type' => 'datetime',
  '#title' => $this->t('Time'),
  '#size' => 20,
  '#date_date_element' => 'none', // hide date element
  '#date_time_element' => 'time', // you can use text element here as well
  '#date_time_format' => 'H:i'
];


While you could uninstall and delete core modules, I wouldn't recommend it.  They will be restored during updates and you'll have to constantly be vigilant to not go over your space limit.

Over time, the size of the site will probably grow slightly due to additional updates, and you may add files of your own (images, etc.) that also increase the site's size.

Drupal 8 requires significantly more space than Drupal 7 and is a very tight squeeze if you only have 250 MB.  Hosting recommendations are off topic for this site, but there are many hosts that offer more file space (say, 1 GB) at a reasonable rate.  If Drupal 8 otherwise fits your needs, I would pay more to increase the disk space, but if that's not an option, go with Drupal 7 since it's smaller, even with a fair number of contrib modules.


Files View, How to display Images related to Media Gallery?

In my view under relationships I used File: Content using Gallery media. This is now showing the images which are related media Media Gallery.


Use drush to install a module on all of the sites of a multisite at once

If you are using Acquia Cloud Site Factory (ACSF) then you can use ACSF command acsf-tools-ml

acsf-tools-ml (sfml): This command will run any Drush command against all sites in your factory. drush @coolsites.01dev sfml en admin_toolbar

 2. Other solution: It's not recommended to enable/disable module directly on the server in this way you lose access to Configuration management.(It will become difficult to manage it)

Recommended Approach:

Enable module in your local environment and then export it via `drush config:export`
import the configuration on the respected server via `drush  config:import`
You can write a simple bash command to automate drush  config:import on all the websites.


How do I add the edit link of a content in a custom view mode?

You can enable views_ui in module page, then go to structure/views and edit the views you are using for the widget. Add Content: Edit link in fields and save it. It will got the edit links for each entity as above image.

Override theme function by custom module

There is no easy way to add the edit link for the widget on node page. But you can still make it happen by overriding the theme functions provided by Entity Reference View Widget View

Below is the sample snippet with assuming the name of your custom module is mymodule. You can copy and paste it into a custom module for testing. (Remember to change the mymodule if you have different name for your custom module.)

<?php

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['entityreference_view_widget_widget']['function'])) {
    $theme_registry['entityreference_view_widget_widget']['function'] = 'mymodule_entityreference_view_widget_widget';
  }
  if (isset($theme_registry['entityreference_view_widget_rows']['function'])) {
    $theme_registry['entityreference_view_widget_rows']['function'] = 'mymodule_entityreference_view_widget_rows';
  }
}

/**
 * Override theme_entityreference_view_widget_widget().
 */
function mymodule_entityreference_view_widget_widget($variables) {
  $widget = $variables['widget'];
  $settings = $widget['add_more']['#ervw_settings'];
  $order_class = drupal_html_class($settings['element'] . '-delta-order');
  $required = !empty($settings['instance']['required']) ? theme('form_required_marker', $variables) : '';

  $header = array(
    array(
      'data' => '' . t('!title !required', array('!title' => $widget['#title'], '!required' => $required)) . "",
      'colspan' => 2,
      'class' => array('field-label'),
    ),
  );
  $header[] = array(
    'data' => "" . t('Edit link') . "",
    'class' => array('field-label'),
  );
  if ($settings['field']['cardinality'] !== '1') {
    $header[] = array(
      'data' => t('Order'),
      'class' => array('tabledrag-hide'),
    );
  }
  $rows = array();

  // Sort items according to '_weight' (needed when the form comes back after
  // preview or failed validation)
  $items = array();
  foreach (element_children($widget) as $key) {
    if ($key === 'add_more') {
      $add_more_button = &$widget[$key];
    }
    else {
      $items[] = &$widget[$key];
    }
  }
  usort($items, '_field_sort_items_value_helper');

  // Add the items as table rows.
  foreach ($items as $item) {
    $item['_weight']['#attributes']['class'] = array($order_class);
    $delta_element = drupal_render($item['_weight']);

    $cells = array(
      array('data' => '', 'class' => array('field-multiple-drag')),
      drupal_render($item),
    );

    $target_id = $item['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $cells[] = array(
      'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
    );

    if ($settings['field']['cardinality'] !== '1') {
      $cells[] = array('data' => $delta_element, 'class' => array('delta-order'));
    }
    $rows[] = array(
      'data' => $cells,
      'class' => array('draggable'),
    );
  }

  if (empty($rows)) {
    $rows[][] = array(
      'data' => t('No items have been added yet. Click "Add items" to launch the widget.'),
      'colspan' => '3',
    );
  }

  $output = '
';
  $form_errors = form_get_errors();
  $classes = array('field-multiple-table');

  // Add an error class to the table in case of error.
  if (isset($form_errors[$settings['element']])) {
    $classes[] = 'error';
  }

  $output .= theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array(
      'id' => $settings['table_id'],
      'class' => $classes,
    ),
  ));
  $output .= $widget['#description'] ? '
' . $widget['#description'] . '
' : '';
  $output .= '
' . drupal_render($add_more_button) . '
';
  $output .= '
';

  if ($settings['field']['cardinality'] !== '1') {
    drupal_add_tabledrag($settings['table_id'], 'order', 'sibling', $order_class);
  }

  return $output;
}

/**
 * Override theme_entityreference_view_widget_rows().
 */
function mymodule_entityreference_view_widget_rows($variables) {
  $zebra = array('even' => 'odd');

  $settings = $variables['rows']['#widget_settings'];
  foreach (element_children($variables['rows']) as $row) {
    $output[$row]  = '
';
    $output[$row] .= '	';
    $output[$row] .= '' . render($variables['rows'][$row][$settings['column']]) . '	';

    $target_id = $variables['rows'][$row]['target_id']['#return_value'];
    $entities = entity_load($settings['target_type'], array($target_id));
    $output[$row] .= '' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '	';

    if ($settings['cardinality'] !== '1') {
      $output[$row] .= '' . render($variables['rows'][$row]['_weight']) . '	';
    }
    $output[$row] .= '
';

    $zebra = array_flip($zebra);
  }

  return implode("\n", $output);
}

/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}

The key concept here is programmatically override the 2 theme functions with hook_theme_registry_alter:

theme_entityreference_view_widget_widget()
theme_entityreference_view_widget_rows()

So we can now modify the table output.

Add a new column header

$header[] = array(
  'data' => "" . t('Edit link') . "",
  'class' => array('field-label'),
);

Add link for new column

For static output.

$target_id = $item['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$cells[] = array(
  'data' => _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]),
);

For dynamic output. (ajax callback)

$target_id = $variables['rows'][$row]['target_id']['#return_value'];
$entities = entity_load($settings['target_type'], array($target_id));
$output[$row] .= '' . _mymodule_entity_edit_link($settings['target_type'], $entities[$target_id]) . '	';

Helper function to build edit link

/**
 * Helper function to build the entity edit link.
 */
function _mymodule_entity_edit_link($entity_type, $entity) {
  $uri = entity_uri($entity_type, $entity);
  return l(t('Edit'), $uri['path'] . '/edit');
}


Alter comment pager to jump to comment section right away?

The only hook Drupal uses to alter a pager is hook_preprocess_pager() but that is invoked for every pager on any page, not just the pager used for comments.
The alternative is adding a new formatter for comments, which by default is the CommentDefaultFormatter class, and make it the default one with hook_field_info_alter().
function mymodule_field_info_alter(&$info) {
  // Change the default widget for fields of type 'comment'.
  if (isset($info['comment'])) {
    $info['comment']['default_formatter'] = 'mymodule_comment_formatter';
  }
}

(mymodule_comment_formatter is the formatter ID used in its annotation.)
The relevant code that sets the pager is in CommentDefaultFormatter::viewElements(), which contains the following lines.
if ($comments) {
  $build = $this->viewBuilder->viewMultiple($comments, $this->getSetting('view_mode'));
  $build['pager']['#type'] = 'pager';

  // CommentController::commentPermalink() calculates the page number
  // where a specific comment appears and does a subrequest pointing to
  // that page, we need to pass that subrequest route to our pager to
  // keep the pager working.
  $build['pager']['#route_name'] = $this->routeMatch->getRouteObject();
  $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
  if ($this->getSetting('pager_id')) {
    $build['pager']['#element'] = $this->getSetting('pager_id');
  }
  $output['comments'] += $build;
}


How not to "fill up" a view when flagging

I figured out how to manage the problem without the need to write new code. I am posting it here, so that it may help others as well, even if the topic is very specific.

How to manage, that a view doesn't fill up immediately after flagging:

Create a "helper flag" and set the flag link to the helper flag on the nodes of your view.
Create a rule, that the flagging of the helper flag, adds the action of unflagging your original flag.
Put the filter in your view in this way, that not only all nodes are displayed that are unflagged with your original flag, but also those with the helper flag (or-filter)
Create a rules display of this view.
Create a rule that reacts on the event "user has logged out".
Add a view loop from the created rules display and add the action (unflag the nodes". choose the "helper flag" to be unflagged.

That's all. As long as the user stays logged-in, the view is not filled up, when he flags the nodes. As soon as he logs out, the helper flag is unflagged and the view is filled up.


Commerce PayPal wps sends to and gets data from sandbox but no payment method available

PayPal WPS has to send IPN to your Drupal website(application) in order for Drupal to process and store payment for the order. When IPN is received and payment transaction is registered in db you can then run some logic (via Rules) to set the order status accordingly and do other things.

You are not receiving IPN from PayPal because your website is on the local host. You have to host your website on live domain(sub domain, domain sub folder , etc.) so that PayPal server can ping yours and send you data.

Read your question a few more times, and here's more thoughts:

You may be messing up PayPal WPS module's logic by using that hook in a wrong way. Why not assign the role via Rules?


Can I add additional module to drupal distribution (all inclusive)?

In your installation you can add the module just like any other module yes.

If you want to add id to the distribution itself, you would effectivly make a new distribution based on Open Social with the module added - please read the guidelines here to learn how to add it.


Programmatically get current multi-site instance name

Thanks to @Clive for telling me about DrupalKernel::findSitePath which takes the current $request to then return the path of the matching multi-site directory.

And thanks to @4k4 for the tip that there's also a service for that:

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {

  $site_path = \Drupal::service('site.path'); // e.g.: 'sites/default'
  $site_path = explode('/', $site_path);
  $site_name = $site_path[1];

  $variables['attributes']['class'][] = 'site-' . $site_name;

}


field_attach_form removes image field default value when submit

I found a workaround: I just have the fields twice, one enabled and the other disabled. With the checkbox I show one or another.

function my_form($form, &$form_state, $node_id, $fields) {
  $node = node_load($node_id);
  $node_form = $form;
  field_attach_form('node', $node, $node_form, $form_state);

  foreach ($fields as $field) {
    if ($field->show) {
      $form[$field->name] = array('#type' => 'fieldset', '#title' => t('Field'), '#tree' => TRUE,);

      $form[$field->name]['override'] = array('#type' => 'checkbox', '#title' => t('Override'),);

      $form[$field->name][$field->name] = $node_form[$field->name];
      $form[$field->name][$field->name]['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => TRUE)
        ),
      );

      $form[$field->name][$field->name . 'disabled'] = $node_form[$field->name];
      $form[$field->name][$field->name . 'disabled']['#disabled'] = TRUE;
      $form[$field->name][$field->name . 'disabled']['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => FALSE)
        ),
      );
    }
  }

  return $form;
}

It seems that the action enabled / disabled is buggy.


use the module migrate, be sure you studied the example and modules like TYPO3_migrate or Wordpress migration.

Migrate has a learning curve, but it is worth it.


Just make sure your user does not have access to 'Access the content overview page' or any super admin permissions.


The percent sign in view arguments is to tell Drupal to expect a contextual filter within the view path. It is specific to Drupal 6 and 7, linux doesn't matter.

Drupal 8 uses curly braces to accomplish this instead.

From https://www.drupal.org/node/1578576, the example provided is that user/%/comments would provide a contextual filter to show the comments for the specific user.

This resource gives screenshots and examples about how to create a contextual view filter:
https://www.drupal.org/node/1578564


Alter field (multiple values) to add more items/values of another field

Here my current solution but I think it is better to use hook_preprocess_field()?

/**
 * Implements hook_node_load().
 */
function MY_MODULE_entity_load($entities, $type){
    if('commerce_product' === $type && !path_is_admin(current_path())){
        foreach($entities as $entity){
            if(in_array($entity->type, array('MY_PRODUCT_TYPE')) && property_exists($entity, 'sku') && !empty($entity->sku)){
                $query = new EntityFieldQuery;
                $query->entityCondition('entity_type', 'node', '=')
                  ->propertyCondition('type', $entity->type)
                  ->fieldCondition('field_product', 'product_id', $entity->product_id, '=')
                  ->range(0, 1);

                if ($result = $query->execute()) {
                    reset($result['node']);
                    $nid = key($result['node']);
                    $parent_product = node_load($result['node'][$nid]->nid);
                    $parent_product_images = field_get_items('node', $parent_product, 'MY_IMAGES_FIELD');
                    if (is_array($parent_product_images)) {
                        $pos = count($entity->field_images['und']);
                        foreach($parent_product_images as $ppi_field){
                            $entity->field_images['und'][$pos++] = $ppi_field;
                        }
                    }
                }
            }
        }
    }
}


Just move the files, you don't need to set a base URL like in Wordpress.

If you do run into any problems, uncomment rewritebase in htaccess


This isn't a direct answer to your question, but is probably the best option to move forward.

Drupal 8.2.0 (due 2016/10/05) will include the new datetime_range module, which provides date ranges in a single field.

I would wait until this is available, and then migrate your two datetime fields into a single daterange fields (one to the start value and the other to the end value).

Then, I would make a custom formatter for daterange fields that implements your logic to combine month/year when they are the same for start and end.

You can then configure your various vide modes to use this new formatter.


How to use Apache Solr as data source for a view

All you need is Apache Solr Views module.

  This module provides Views implementation for the Apache Solr Search
  Integration Project 7.x-1.x branch. Requires Views 3.

  This module will provide facet navigation combined with searching to
  make a powerful user experience.

After installing this module, you can able to create a Apache Solr view, which list all the fields which are available in the indexed documents in the solr.


I think you are looking for something like Sub Users module to set relation between two user types.

I also sell membership with help of Drupal Commerce in D7 & I have used same thing but some modified version of the module which you can find at my given link here --

https://drupal.org/node/2049703

I sell membership to have some access & sometimes I create a usertype who has got authority to create more sub user under him to have access allowed for that particular membership type.


How do I hide "View most recent blog entries"

unset($links['usernames_blog']['#links']['blog_usernames_blog']);

Might be correct, but make sure your module has higher weight, so your hook alter fires after the blog's module.

I suggest using the weight module to give your custom module higher weight. Else, you could run on Devel's Execute PHP module_set_weight('mymodule', 11); to give it higher weight.

If that doesn't work, If you look at the module's code, there is another link that gets added via hook_ENTITY_TYPE_view

Thus, all you gotta do is use hook_ENTITY_TYPE_view_alter

mymodule.module

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 */
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (!empty($build['summary']['blog'])) {
    unset($build['summary']['blog']);
  }
}


How can I override the search result page title dynamically?

Here comes an example snippet on how to override the page title by URL query:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  $current_path = \Drupal::request()->getpathInfo();
  if ($current_path == '/search/node') {
    if (\Drupal::request()->query->has('keys')) {

      // Get the searched string.
      $keywords = \Drupal::request()->query->get('keys');

      // As of https://drupal.stackexchange.com/a/232304/15055 we probably
      // need to ensure the cache gets busted.
      $variables['#cache']['contexts'][] = 'url.query_args:keys';

      // Set the new title.
      $new_title = new \Drupal\Core\StringTranslation\TranslatableMarkup('Search result for Article (@keywords)', ['@keywords' => $keywords]);
      $variables['title'] = $new_title;
    }
  }
}


drush omega-guard and missing or unreadable gemfiles

Found the answer.
here is the solution:
https://www.drupal.org/node/2323235#comment-9069731


Theme overrides for custom hook_theme() in Drupal 7

This should happen automatically. Most core modules define theme hooks which you wouldn't think twice about overriding in your theme. Take a look at node_theme for example http://api.drupal.org/api/drupal/modules--node--node.module/function/node_theme/7.

The devel themer module should help you out with such things. Needs some work for D7 but should help.


How can I theme the outgoing contact mail?

I was able to get Berdir's answer working in Drupal 8.1.0. But I had to do a number of things to get it going.

Install mailsystem, swiftmailer, contact_storage, and contact (core) modules
Setup a custom contact form, configure it and add fields as needed.
Configure swiftmailer message settings (/admin/config/swiftmailer/messages) to use HTML.
Configure swiftmailer transport settings (/admin/config/swiftmailer/transport) to preferred transport type
Configure mailsystem default mail system settings to use swiftmailer for both formatter and sender plugins. I assume you could also configure per module in the later section if you like, however I did not try it.
Under /admin/structure/display-modes/view add a new view mode for Contact message, setting it's namespace to mail. This is the view mode that will be used when sending the email (somewhere this is hardcoded from what I can tell).
If you want a pretty display of the Contact message nodes on the site then you will also want to create a full view mode and configure that too.
Configure your view modes under the custom contact form you created. The Display Suite module really allowed for customizing the markup with it's field templates made available in display suite extras.

Note, I also have Berdir's MessageViewBuilder override in a custom module but I am unsure it is any longer necessary. I have not attempted to remove it yet.


Add custom fields to the Apache Solr search results

I have forgotten to add the content type filters, everything is correct now. Another (better) way is to modify the snippet in module (like here) instead of the search results template.


Use the [Automatic] Comment Translation module

  Comment translation utilizes the Microsoft Translator to create translations of submitted comments on nodes that have existing translations available. Translated comments are placed in moderation for review.


How can I export shortcut sets and shortcut links in Drupal 7?

Finally, managed to programmatically create the shortcut sets and links with the following php script:

<?php
echo 'populating shortcuts...';
$shortcut_set = new stdClass();
$shortcut_set->title = 'Default';
$shortcut_set->set_name = 'shortcut-set-1';
$shortcut_set->links = array(
    array('link_path' => 'admin', 'link_title' => 'Admin',),
);
shortcut_set_save($shortcut_set);
echo ' shortcuts population finished';
?>

as mentioned in this drupal post.

A also had to apply this patch in shortcut module, which fixes the shortcut_set_save function called by the script.


SSL Issues with Mixed Content and Firefox

When you set $base_url, Drupal always uses it in email absolute links and whenever it has to build an absolute URL.

I have many sites running full-HTTPS, with only the $base_url set to the https URL.

We can't debug your site for you, but check the page source to see if any Javascript files are being served via HTTP.
Google Analytics, Google fonts, Google translate widgets, banners, ad serving scripts, CDN-served jQuery, etc.

Header tracking and other debug features won't probably work in your browser because when the page URL is in HTTPS, browsers do not load HTTP assets. You can still check the page source to see the HTTP references.


New Content type is not listing in Add Content in Drupal 7

Check the permission for node creation of that type in admin/people/permissions
Clear all caches and retry and it should be OK


Why does Drupal jump back to the calling function after submitting a form?

Where else would you expect the form to lead?

You can add ?destination=somepath to the URL, or a #redirect to the submit array, or a drupal_goto in the funnyform_submit() function, but if you don't tell Drupal where to go, it's just going to reload the current page.


feeds module cannot handle csv files exceeding 8gig?

8388608 bytes is 8MB, not 8GB. 40245470 bytes is < 40MB.

Your PHP settings are limiting the maximum POST content length to 8MB, which is why you're getting the error.

To fix, edit your php.ini file and add/update these lines:

post_max_size=50M
upload_max_filesize=50M


Migrating multiple values into a single file field in Drupal 7 with Migrate 2.2

I think what you need is prepareRow. Here is code from the migrate baseball example where multiple fields are merged into a single array field.

 function prepareRow($row) {
    // Collect all the batters into one multi-value field.
    for ($i=1; $i <= 9; $i++ ) {
      $key = "visiting_batter_$i";
      $visiting_batters[] = $row->$key;
      $key = "home_batter_$i";
      $home_batters[] = $row->$key;
    }
    $row->visiting_batters = implode(',', $visiting_batters);
    $row->home_batters = implode(',', $home_batters);
    $row->title = "$row->home_team vs. $row->visiting_team. " . gmdate('M d, Y', strtotime($row->start_date));
  }

(from the file migrate_example_baseball.migrate.inc)

However I have been having mixed results with prepareRow in my own code, so while this looks straight forward I can't guarantee that it will work.


Just a single flag for the rendered page view that displays all
  articles (i.e., a way to bookmark the "read all news" page.)

ok then doing it the way you were doing it, is the way to go.

$node->nid alone won't return the nid, you need to to use menu_get_object() function

<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

print flag_create_link('bookmarks', $nid);

}

?>

Note 1: If you're using a page view, the above won't work since it cannot fetch an nid since page view's don't have node id's. In order to get it to work, you can create a block view, and then create a node where you insert your block view. Then since the node has a nid, it's able to fetch the node id.

Note 2: You can ignore all the comments below, as they were due to using a page view (see note1)


How to show validate error of a node listing page

This may not quite answer your question, but I think it might help with whatever you're trying to do.

You can alter the node creation form to have extra validation and display it on the screen using the devel module, along with a custom module that calls hook_form_alter

function mymodule_form_alter(&$form, &$form_state){
    //add a function in #validate to read form_state and show it on screen
    $form[#validate][] = mymodule_read_values($form_state);
    //or if you want to make it happen before any of the other form validation, uncomment the next line and comment the one above
    //array_unshift($form[#validate], mymodule_read_values($form_state));
}

function mymodule_read_values(&$form_state){
    // make sure you have devel module installed or this will cause WSOD
    dpm($form_state);
    // if you want to prevent form submission you can uncomment the next line
    // throw new Exception('Cancelling form submit - see mymodule');
}

Remember of course, to replace any instance of 'mymodule' with the name of your module, particularly the first one, or the hook won't work.

Doing this will show the structure of the form_state on the screen when you try to save the node.

If you want to target a specific form you can change the first line to

function mymodule_form_FORMID_GOES_HERE_alter(&$form, &$form_state){


Add Additional Logic To Node Save/Submit Process

You can probably use either hook_entity_presave(), hook_node_presave() hook_field_attach_presave(). These hooks are all pretty similar right now. Actually not sure why there are 3 of them :)

Simply add a check for the content type and/or the existense of the field you want to alter.


Drush will pass any extra argument in the shell alias to the command. So define the shell alias as:

$options['shell-aliases']['git-checkout'] = '!git checkout';

and simply run

drush @mysite.test git-checkout my_custom_branch


How to get instance of Module / Plugin / Widget of Vote Object in THEME_preprocess_node?

Turns out, everything I need is in $variables['content'] as long as the widgets/plugins that I'm trying to display are set to display as part of the view mode.
So in my specific case I can for example access $variables['content']['field_upvotes']['#up_points'] and that contains the number of upvotes!
Easy enough! :-)


How to check if a password reset token is still valid?

Welp, I probably should have gotten the idea to follow where the form action actually takes you and see what its controller does. I pulled the timestamp and hash from the form action with the explode function, loaded the user object from the currentUser id, and used Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp));.


In which file should I write db_add_field function

I think you should write your code for adding new field in DB in your .module file.
Here is the code for you :

function xyz_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['node']['fields']['show_in_inbox'] = array(
    'type' => 'int',
    'length' => '4',
    'default' => '1',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by xyz module',
  );
}

function xyz_enable(){
    if (!db_field_exists('node', 'show_in_inbox')) {
        $schema = drupal_get_schema('node');
        db_add_field('node', 'show_in_inbox', $schema['fields']['show_in_inbox']);
    }
}

The new field will be added in your existing database on enabling this module.


Is there an alternative to themegarden.org - one that has Drupal 7 themes?

I haven't come across a really good site for Drupal 7 themes. Here are some sites that might be helpful:

http://www.leveltendesign.com/blog/colin/10-free-drupal-themes-7x
http://omega.developmentgeeks.com/
http://www.themesnap.com/drupal-themes.html (paid)
http://adaptivethemes.com/drupal-themes/all (paid)


I do not believe that a path such as %/% in views will work.  Have you tried it?

The path factsheet/%/%  is not intercepting other content, it is the path to the view page.  That means that views responds to any page with a factsheets followed by other path segments.  The reason for defining the view pages with % is to create a wildcard variable to be used in contextual filters (3rd column of the main view form).  These filters supplement the basic  filters defined in the first column.  Having two % filters means that you can use two contextual filters.  The top contextual filter takes the first % and the second takes the next % in the path.

The Views preview works because you are only testing the contextual filters.  The path is not being run through Drupal to determine content.


How can I filter by a term when on a sub-page of that term?

I'm a little confuse on what you're trying to show but I think you can do what you want with contextual filters.

To do so:

Add taxonomy to the filter critera (Has taxonomy term ID)
In the first section (when not available), select Provide default value
Type : Raw Value from URL
Select your path component (let say 2 for your term1, categories would be 1)
In the "When the filter value IS available or a default is provided" section, check "Specify validation criteria"
Validator : Taxonomy
Check the appropriate vocabulatory
Filter value type : Term name converted to ID

What that filter will do is check a part of the url and match it against the vocabulary. If a term is matched, let say term1, it will show nodes that have the term. You can add multiple filter to validate multiple part of the url. It's pretty much the same for the content types.

So /term1 could filter all node with term1. term1/activities could filter all term1&activities... You get the idea. Just don't hide the view if the filter doesn't validate, make it show all results.


As already stated in comments, you have one page but more than one link/path to access it. From the SEO perspective it is something to consider, eventhough Drupal "knows" this is the same content.

The /node/11 is the base URI for your English content, you can't be without it, it's a Drupal internal.

/conveniences/gift-cards is the path alias of the /node/11. It is usually created with the help of Path or Pathauto modules to improve the URIs for better UX and better SEO. They're usually coupled with Global Redirect or Redirect modules that automatically and permanently redirect to the alias. This way search engines only ever see one URI for this content.

/espanol/node/11 This link comes from Multilingual features, actually the specific way you have them configured. It's important to distinguish two independent parts of the website that can be translated: Interface and Content. Roughly speaking, Content is what usually goes into a node, and Interface is everything else surrounding the node.

Multilingual sites need a way to determine which Interface language to display, and which Content exactly when a request is made (a link clicked). Usually this is done by constructing links that contain both information. The language prefix is being used to determine the Interface language, and what follows it is a normal path to some content.

The /espanol/ is the language prefix and is telling Drupal to display the interface in Spanish language. /node/11 is the content path and is telling Drupal to pull the contents of node 11 from the database. When you put that together you have Spanish interface, but you're looking at English content. This might be the case for a Spanish translator: they are using their native language as the default interface language, but they might want to edit the English content.

In D7 every translation is a new node, but in D8 all translations of the same node share the NID, so some configuration might differ there.

Multi-Language Link and Redirect (MultiLink) module can help with some multilingual link handling, automatically changing the output of links to point to the translation of the content based on the current interface language, so you don't mix interface and content languages, unless you create it like that on purpose in menus.

The way to correctly tell search engines about pages being translations of one another is through hreflang: Hreflang.


Load nodes by property, including empty ones

loadByProperties() executes an entity query with ->condition() for each property. You can't use this for empty fields, you need
$query->notExists('field_example');

according to How get empty record on date field with entityQuery?