Send newsletter action - after saving simplenews node

You need to enable the simplenews_rules module which comes packaged with simplenews - this has the action for sending a newsletter defined:

'simplenews_rules_action_send' => array(
  'label' => t('Send newsletter'),
  'group' => t('Simplenews'),
  'parameter' => array(
    'node' => array(
      'type' => 'node',
      'label' => t('The newsletter node to be sent.'),
      'description' => t('The newsletter node that should be sent.'),
    )
  )
),


D7; Just adjust your contentype, fields names, and token.

Your title


Can I set a theme's logo_path programmatically?

In Drupal 6, I believe what you are looking for is

variable_set('logo_path', '/path');

At first glance though, I'm wondering why there is only one such on my site, and not one per theme.
theme_get_settings appears to be grabbing defaults first, and then merging in theme specific settings on top of that.

In D7, the variable is called 'theme_themename_settings'.


Using EntityFieldQuery to order nodes in an OG Group using node_comment_statistics table

Add the custom TAG to the EntityFieldQuery and than use the hook_query_TAG_alter() to add the JOIN to the query as below:
// Create the query as below (Note: "CUSTOMTAG" added for altering the query)
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', array('post', 'document', 'link'), 'IN')
  ->propertyCondition('status', 1)
  ->fieldCondition('og_group_ref', 'target_id', $panel_args[0], '=');
  // Added the Tag, which we will be using to alter the query.
  ->addTag('CUSTOMTAG');
  // Complete the query (if you are having any other field condition).
  ->execute();

/**
 * Implements hook_query_TAG_alter()
 */
function MyModule_query_CUSTOMTAG_alter(QueryAlterableInterface $query) {
  // Add the join to the "node_comment_statistics" table.
  $query->join('node_comment_statistics', 'ncs', 'ncs.nid = node.nid');
  $query->orderBy('ncs.last_comment_timestamp')
}

Reference links:
https://drupal.org/node/1157006#comment-7634027
http://www.phase2technology.com/blog/or-queries-with-entityfieldquery/


Update multisite modules and core in one click

I think the simple answer is no. And generally you would want it to be so.

Running update.php can cause sites to fail, so you should back up each sites database run update.php and then check it works. Each of your sites will work slightly differently, depending on the combination of modules. So a broken update hook, or a conflict would be something that you would want to check carefully for.

Having said all of that there are tools such as aegir which may make this possible to do safely.


Possible to hide admin toolbar for testing display

If your using the built in D7 tool bar, take a look at Toolbar Hider.

  This module will hide/show the toolbar with the press of a key that
  you configure. It will optionally adjust the page padding to hide the
  white space. You can also configure if you would like to hide the
  toolbar by default.

If your using the contributed admin menu, there is also Admin Menu Hider, which does the same thing, but is in alpha.


Required modules: Views, Pathauto, Simple hierarchical select, Taxonomy Views Integrator.

Create content type "food".

Create vocabulary "food" add some example terms:

+ fruits
  - apples
  - orranges

+ vegetables
  - carrots
  - potatoes

Pathauto settings

go to: admin/config/search/path/patterns and set the taxonomy term paths:

pattern for all food paths -> [term:vocabulary]/[term:parents:join-path]/[term:name]

Thanks to this pattern our food paths will look like: food/fruits/apples and may contain more than one parent, for example: food/parent1/parent2/parent3/child

Go to: admin/structure/taxonomy/food and check if all paths are setted up correctly. If not, edit them and check Generate automatic URL alias.

Views

Create view showing taxonomy terms from food vocabulary and add these three displays:

Page: Title: "`All food content`"

Path: /food

Relatonship:  Taxonomy term: Content using Food terms.

Page: Title: `Food category`

Path: /food/%

Relatonship:  Taxonomy term: Content using Food terms.

Contextual filter:  (field_food_terms) Content: Has taxonomy term ID (with depth)

contextual filter settings: depth = 1 (use: this page override)

Override title: Food category - %1 This means, if we go to food/fruits, all items one level below fruits will be shown (all fruits)

Page: Title: `Food subcategory`

Path: /food/%

Relatonship:  Taxonomy term: Content using Food terms.

Contextual filter:  (field_food_terms) Content: Has taxonomy term ID (with depth)

contextual filter settings: depth = 0 (use: this page override)

Override title: Food subcategory - %1

There is no terms below, if we go to food/fruits/apples, all items with term name apples will be shown (only apples)

Use Views to override term paths

At the end you need to go back to: admin/structure/taxonomy/food edit each term and choose Use view override.

For each term you need to specify which view will be used to override, it's the main disadvantage of this solution.

Results

An example of article and blocks with relationship to the taxonomy.


What is wrong with my custom token to embed entities via token?

See the example : https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21token.api.php/function/hook_token_info/8.3.x

Inside tokens there must be 3  levels, tokens][token_type][token].

Also tokens don't usually work like that and it will not be possible to validate that token, it is always a token type and that has tokens, which can have a type which then again has tokens. So you'd need to define types for your nested structure.

Not quite sure why you aren't using the entity_embed project to inject tokens, I assume this is supposed to be used inside a formatted text. https://www.drupal.org/project/entity_embed


How to theme date combo input side-by-side?

Looking at the CSS provided by the module, the boxes are foreseen as block elements. Even the used classes on the form fields are date-no-float, so for some reason they don't want that the fields are shown in column layout ...

The fact that you used a sub theme for your admin, you can add these CSS styles (based on Seven theme) in your css file. These will create the desired result you want.

.date-no-float { float: left; width: auto; clear: none; }
.date-no-float > .form-item > label { float: left; margin: 34px 40px 0 30px; }
.start-date-wrapper { clear: left; }


You could use contextual filters with the year as parameter. Your views path could be "noticias/%". "%" is a placeholder for your contextual filter. So you have to add 2 filter i think. Global: Null and your year date as second parameter. This method is more SEO friendly.


Show form errors before opening AJAX modal

I see two things that stand out to me:

1) Setting the '#name' attribute on the submit button. You should never do that. I've learned over the days that there is always a better way to do whatever you're trying to do when setting the #name attribute, and setting it causes some wonkiness. This may be why your form is not rebuilding.

2) You are rendering your status messages in a D7 way. Use this instead:

$messages = ['#type' => 'status_messages'];
$response->addCommand(new PrependCommand('#target-div', \Drupal::service('renderer')->renderRoot($messages)));
It looks weird, because the messages aren't being retrieved, but by setting the #type to status messages, Drupal will handle the retrieval in the background. This is probably why you are seeing some funkiness with the messages.


Step 1: Getting started

To create charts in Drupal, you can (also) use the Charts module. It comes with a sample view which will give you a chart for each of your content types.

Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.

For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.

Step 2: Create the tabular format of the view

A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 3: Add the chart to your view

Do not try to start this step if you didn't first complete the prior step.

Just use the views display format "Charts", and select the various options that fit your needs. Refer to Steps to create charts using the views UI for detailed instructions about this.

Disclosure: I'm a (co-)maintainer of the Charts module.


How to get url of Product image field of Entity Reference field

As you're creating your view, you need one more relationship. Look for this relationship:

  Commerce Product: Referencing Node

  (Relate a product to the Node referencing it through field_product.)

This will allow you to harness the "reverse-relationship" going from the product to the reverse-node. Add this relationship, require it, and then use this to generate your links.


How to hide some fields from user in add content page?

If they are fields that the user is not permitted to use then there is a module included with CCK called content_permissions.

If you install that then you can set role based permissions for each field on the permissions page.

If it is not an issue of access control, but you just want to hide some fields that once, you can implement hook_form_alter() in a custom module to do it.

It would go along the lines of this:

/**
 * Implementation of hook_form_alter(),
 */
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    $node = $form['#node'];
    // Only for page content and only when adding a new node.
    if ($node->type == 'page' && empty($node->nid)) {
      // Hide the name field by restricting access.
      $form['field_name']['#access'] = FALSE;
    }
  }
}


Site off-line with correct data in settings.php

You probably haven't installed and/or enabled the PHP MySQL extension (it's a requirement). You can check by creating a phpinfo() page and searching for 'mysql'. If it's not there, you need to install and enable it. You don't say what server you're using, but if it's Ubuntu or a similar Debian-based variant, you can do this:

$ sudo apt-get install php5-mysql
$ sudo /etc/init.d/apache2 restart

If you're on another platform, the steps will be a bit different, but you get the idea.


Well, at last I was able to figure it out. Since the field was part of the form after creating the instance, I thought I could use hook_form_alter, and I was right!


Restrict IFRAME and OBJECT embeds certain domains

Allowing users to input , and doing validation on some subtypes of that, is certainly possible, but far from easy.

It's easy to think, "I can do that with a regular expression!". Read This SO question though, before you try, and save yourself a lot pain.

What you can do instead, is employ an XML parser and process the input from there, but that is far from trivial, and will require quite a bit of work.

What I recommend you should do instead, is create specific tags for what you want to allow. Something like [iframe:http://some.url.here], and then process these manually with an input filter. You would probably want to apply that filter in a text-format after you've run the regular "limited html" filter.

A filter is created by implementing hook_filter_info, and in your process callback you can do string substitution on the [iframe] tag, provided it references an approved domain.


Cannot use fields as product attributes if they are within a field collection

By default Drupal Commerce supports list type fields (list, term reference - list, etc.) as Product attributes, not sure but may be because pre-defined list of values.

It would be difficult to get the field collection as your product attribute, because attributes make the product Unique and using the field collection won't give you much feasibility to use every field value to differentiate between product. Instead you can re-use fields in every product type and get it working easily.

If you still would like to give field collection module a try, you can check Drupal Commerce module in detail for attributes implementation or refer Commerce Attributes Date module which allows date field to be used as Product Attributes (Drupal Commerce doesn't support Date type field as attribute by default).


How To Alter Web Form Elements Permanently?

You can alter the yaml source of a webform by loading the config entity and modify elements:

use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform->get('elements'));
  $elements['name']['#title'] = 'Please fill in your name';
  $webform->set('elements', Yaml::encode($elements));
  $webform->save();


How to set Target points to the User group?

You'll probably have to use the Rules module to make it happen.

Maybe create some kind of custom field (integer) to store the value of your target points value. ie. target points field = 100 points

Now, you can create a Rule to activate on the event "user awarded points", so that every time a user gets points, that rule is run.

Next, have that rule activate a different rule component, which is designed to compare the user's current points total with the value in the target points field. (So, every time somebody is awarded points, the system will check to see if they have met their target.)

You can set a condition such that, if the current point value is "less than" the  target value, run an action "display a message" with some text saying you need XX more points till you finish your target.

(You may need an additional step to run a calculation on the points needed, but I think you get the idea of what you need to do with my example.)


How to assign value from one file field to another programmatically?

I have done it. Here is the code that I used to solved the problem.

  $file = file_load($fid);
  $user->field_user_file = array(
    'und' => array(
      '0' => array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uri' => $file->uri,
        'status' => 1,
        'display' => 1
      )
    )
  );


After drupal 6> 7 upgrade attached pdf links not visible

Use CCK migrate module to migrate (import) the D6 fields to D7 . CCK migrate module is the part of CCK module in drupal 7.

Here is the documentation how to do it.


Drupal Commerce: How to validate payment method settings?

I found a solution - because it is a FORM I using the FORMAPI. More accurate hook_form_alter() to add my custom validation handler and next is trivial. Code:

/**
 * Implements hook_form_alter()
 */
function commerce_mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'rules_ui_edit_element') {
    if ($form_state['element_settings']['payment_method']['method_id'] == 'commerce_mypaymentmethod') {
      $form['#validate'][] = 'commerce_mypaymentmethod_settings_validate';
    }
  }
}

and validation function

function commerce_mymodule_settings_validate(&$form, &$form_state) {
  $deadline = (int) $form_state['values']['parameter']['payment_method']['settings']['payment_method']['settings']['mymodule_deadline'];

  if ($deadline < 1 || $deadline > 30) {
    form_set_error('', t('Enter only digit positive value between 1 -30 (days) in Order payment deadline. @value', array('@value' => $deadline)));
  }
}


Call to undefined function ctools_ajax_text_button()

I forgot to add ajax :)

ctools_include('modal');

ctools_include('ajax');

ctools_modal_add_js();


How to store HTML data in a database field?

Basic info about user input sanitization in Drupal.


Module: Extend "Authoring information"-tab and adding new field to it

Use hook_form_alter(), add your form item to $form['author'] fieldset (see node_form() function), add your own submit function to $form['actions']['submit']['#submit'] array (or $form['#submit']) and you're good to go! And always remember, Form API Reference is one of your best friends!


Where can I get permission string to use with user_access?

Pop Devel on your site and head to yoursite.com/devel/php and enter the following:

$permissions = module_invoke('node', 'permission');
dsm($permissions);

The key for each part of the array will be the string you want to apply the permission.

The following will get a list of permissions on every enabled module on your site (modules sorted by name):

foreach (module_list(FALSE, FALSE, TRUE) as $module) {
  if ($permissions = module_invoke($module, 'permission')) {
    // Print the module title
    dsm($module);
    // Print the permisions
    dsm($permissions);
  }
}


I've found a workaround. When I add the view's URL as path in routing.yml, Drupal always used the view's access check. So instead of directly using the view's path, I wrote a simple redirect controller in order to get an alternative path.

wt_poi.routing.yml

wt_poi.admin_list:
  path: '/admin/poi-redirect'
  defaults:
    _controller: '\Drupal\wt_poi\Controller\WtPoiController::redirectToPoiAdminList'
  requirements:
    _permission: 'administer nodes'
    _custom_access: '\Drupal\wt_poi\Controller\WtPoiController::isAllowedPoiAdminList'
  options:
    _admin_route: true

wt_poi.links.task.yml remains unchanged

src/Controller/WtPoiController.php

<?php

namespace Drupal\wt_poi\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;

/**
 * Controller for the POI node type tasks.
 *
 */
class WtPoiController extends ControllerBase {

  /**
   * The only purpose of this controller is to provide an
   * alternative path to the POI view, so we can attach an
   * _custom_access check to it.
   */
  public function redirectToPoiAdminList() {
    // redirecting to a view: view.VIEW_MACHINE_NAME.DISPLAY_MACHINE_NAME
    return $this->redirect('view.poi.admin_list');
  }

  /**
   * Used to limit visibility of local Task "List" to POI node types
   */
  public function isAllowedPoiAdminList() {
    $bundle = false;
    $route = \Drupal::routeMatch();
    $routeName = $route->getRouteName();
    $node = $route->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $bundle = $node->bundle();
    }
    // the first part ensures the local task is shown on node pages,
    // the second part makes sure it also works during the redirection itself
    return AccessResult::allowedIf($bundle === 'poi' || $routeName === 'wt_poi.admin_list');
  }
}

Two remarks:

A) Remember that the user still has to pass the view's own permission check after the redirection (and this is a good thing, otherwise anybody knowing the alternative URL could bypass the access check).

B) The access check must use an allowedIf($positiveCondition). Do not use an forbiddenIf($negativeCondition), because it only returns forbidden or neutral, which always hides the local task.

My solution still feels a bit hacky, and I still would be open for a cleaner solution, but at least it does everything I need.


How to display a specific page number of a views mini pager?

I have found the answer. I'm sharing here the solution.

I used the following code and it worked.

function mymodule_views_pre_build(&$view) {
  $view->set_current_page(5);
}


It was recently written that there are several benefits over EFQ, entityfieldquery over other methods:

OOP - EntityFieldQuery provides an object oriented programming approach that allows you to create abstract classes to extend.
Flexibility - An advantaged arised from #1, creating your own objects allows you to modify the entitycontroller to do more things: Store field data via mongo DB, return data into blocks only, etc.

Source: http://chris-on-the-web.blogspot.com/2012/03/drupal-7-views-vs-entityfieldquery-pt1.html


How to add custom class in body tag on form submit?

You can add through custom hook.

 function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}

OR

function YOUR_THEME_preprocess_html(&$vars) {
  $path = 'your-drupal-page';
  if (drupal_match_path($_GET['q'], $path) || drupal_match_path(drupal_get_path_alias($_GET['q']), $path)) {
    $vars['classes_array'][] = 'page-my-css-class';
  }
}

If you have any query related how to create then you can check this LINK.


AJAX form blocks getting internal server error

Try this

$build['form'] = \Drupal::formBuilder()->getForm('\Drupal\skb_subscription\Form\SubscribeTag');
 return $build;


How do I send a variable from PHP to JavaScript from a function that returns a render array?

It does apply to the method you are using. You can add metadata like #cache or #attached to any render element (#theme, #type, #markup, #plain_text):
return [
  '#theme' => 'theme_name',
  '#form' => $form,
  '#data' => [
    'customer' => $obj_customer,
    'customer_subscription' => $obj_customer->getSubscription(),
    'subscriptions_explanation' => $arr_subscription_text,
  ],
  '#attached' => ['drupalSettings' => ['do' => $something]],
];


Just needed to replace this one field with this:

$var_symbol = token_replace($payment_method['settings']['var_symbol'], array('commerce-order' => $order));

Now it works perfectly.


Automate the creation of settings.php and files directory

Try using the drush site-install command. Name your installation profile with the command argument.


Change icon class in "Add to cart" button

Simple Solution is achieving it with simple Jquery line

$('span.icon.glyphicon.glyphicon-plus').removeClass('glyphicon-plus').addClass('glyphicon-shopping-cart');


If you're looking to arbitrarily order nodes, that is the use case of Weight module. The module lets you add a field to any node type with a customizable weight range. Once added to your node types, you can configure any View to use this field to sort your nodes.


When using features to manage deployment, should I break my functionality into many little features or one big feature?

Make several little Features, split by conceptual layer.

Advantages:

Granularity when reviewing Overrides and performing Reverts — so you don't have to revert everything at once.
Modularity — even if you don't plan to reuse individual components, breaking things down into discrete modules will help with maintainability.

For deploying a single site from development to test to production, we use the following taxonomy (where "site" is replaced with a unique machinename for the site) —

site_types Feature — declares Content Types, Fields, ImageCache settings, User Roles
site_structure Feature — declares Contexts, Views, Menus and Menu Links, Blocks, User Permissions, Variables

depends on site_types Feature

site_content Feature — declares Nodes

depends on site_structure Feature

If there are multiple distinct site sections (for example, Public vs Private), consider splitting things up further:

site_types Feature
site_structure Feature — declares structural components common to both Public and Private

depends on site_types Feature

site_public_structure Feature

depends on site_types Feature

site_public_content Feature

depends on site_public_structure Feature

site_private_structure Feature

depends on site_types Feature

site_private_content Feature

depends on site_private_structure Feature


How can I prevent "Log in to post comments" from displaying for anonymous users?

You can do it using hook_preprocess_HOOK
The following hooks should be placed in YOURTHEME.theme file:

Remove comment links from node for Anonymous user:

    /**
     * Implements hook_preprocess_HOOK().
     */
    function YOURTHEME_preprocess_links__node(&$variables) {
      if (\Drupal::currentUser()->isAnonymous()) {
        unset($variables['links']['comment-forbidden']);
      }
    }

Remove links from the comments for Anonymous user:

/**
 * Implements hook_preprocess_HOOK().
 */
function YOURTHEME_preprocess_links__comment(&$variables) {
  if (\Drupal::currentUser()->isAnonymous()) {
    unset($variables['links']['comment-forbidden']);
  }
}


Try Content Access module Content Access

   This will allows you to manage permissions for content types by role and author.this will allow you to manage permission for node that you want to access to anomyous and authenticated users.


How do I programatically add a field to a node?

You need your own form ideally, right now you have a system_settings_form. That's typically for only setting variables and really simple stuff like that. see the documentation on system_settings_forms.

Instead you probably want to create and use a custom menu callback (you've already done that) which has a callback to a custom form you've defined. See the general drupal FAPI guide.

With your own form you create a submit callback. In that callback you take the selected node types and just create and assign instances of drupal fields to them. So you have to do 2 things: 1) create the fields, 2) assign them to the content types (entity bundles).

The form submit callback could look like this (not 100% tested code, fill in the blanks, add validation, etc):

function mymodule_form_submit($form, &$form_state) {
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field = array('field_name' => 'field_price', 'type' => 'number_decimal',);
    $field = field_create_field($field);
  }
  if (!field_info_field('field_price')) {
    # Create field singleton
    $field2 = array('field_name' => 'field_type_of_currency', 'type' => 'option',);
    $field2 = field_create_field($field2);
  }

  foreach ($form_state['values']['content_type'] as $machine_id => $machine_name) {
    # Create instance on bundle.
    $instance['field_price'] = array(
      'field_name' => $field['field_name'],
      'entity_type' => 'node',
      'bundle' => $machine_id,
      'label' => 'Price',
      'description' => 'The price of an item.',
      'required' => FALSE,
      'settings' => array(),
      'widget' => array(
        'type' => 'textfield',
      ),
      'display' => array(
        'default' => array('label' => 'hidden'),
      ),
    );
    // ... same instance code for currancy type field instance.
    // $instance['field_currency_type'] = ...;

    foreach ($instance as $instance_field){
      field_create_instance($instance_field);
    }
  }
}


Add title and alternate text to image automatically?

The most direct way might be to do something along these lines in hook_node_presave() in a custom module:

function YOURMODULE_node_presave($node) {

  if(isset($node->field_image)) {
    $node->field_image[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_image[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

where field_image is the actual name of the image field you have in your node.

If you don't want your users to be see or to attempt to change this, just make sure the alt and title boxes aren't checked in the field setup, eg:

as this is just for the field add/edit widget in the form; the above code will still work even if these attributes aren't "enabled."


Is it possible to use many plugin process for a field?

Yes, process plugins can be chained - see the documentation under "The full pipeline".


How can I import the configuration on a different site?

You can get the UUID with:

drush config-get "system.site" uuid

And you can change it with

drush config-set "system.site" uuid "fjfj34-e3bb-2ab8-4d21-9100-b5etgetgd99d5"

With that you gotta have the same sites.


How do do "Facebook style" image tagging?

It's called "image annotation" if you want to search for it.  There are a handful of modules, but not sure how great they work or how often they are maintained.  This one seemed the best:

http://drupal.org/project/image_annotate


What is required for a view menu item to show up as a link in the admin page?

In addition to the report views needing to have "Page" displays with URLs nested under admin/reports/data, I also had to make sure the following settings were enabled under "Page: Menu item entry" settings within the Views:

Type: Normal menu entry
Menu: Management

Without both of these settings, the menu links will not show up under the new custom reports page.


Modular Drupal content-type (variable sections)

You can do this with the Field Collection module.

Add a field collection to your Case node and then add then add fields of the types you require to the field collection restricted to the amount of images or videos you want to display. An with the correct image styles assigned.

You could use the Field Group module to collapse the fields to improve the admin interface.

Edit:

Another option would be use Conditional fields module and add image fields to the case content type set the the amount of images to be displayed in each and the image style required. Then add a list field to the case content type with option on 1 image, 2 images, 3 images etc and then use Conditional fields to link this to display and hide the image fields.


calculate sum of user's orders in drupal commerce

You can use the view Commerce Backoffice: User orders.

Clone the display users orders.
IN advanced settings, set use aggregation : YES
remove All fields from the display except order Total
In order total field aggregation settings, set type = SUM, group a column = Amount

That's it.

Alternatively, if you don't use Commerce Backoffice module, you can create a view from scratch if you have no user's orders view (I don't remember which default views are provided with Commerce) :

Create a view of orders
Add a contextual filter Commerce Order:UID
Add a field total and repeat steps above

This should be enough. Remain formatting details...


To answer the question, if an entity wants to be included in drupal search, it has to provide a search plugin, which is when discovered listed by the plugin manager from the search module. If not you should first check the annotations of the plugin, see for example the plugin from the node entity:

namespace Drupal\node\Plugin\Search;

/**
 * Handles searching for node entities using the Search module index.
 *
 * @SearchPlugin(
 *   id = "node_search",
 *   title = @Translation("Content")
 * )
 */
class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {

To debug this, clear the cache and list the discovered plugins:

drush ev "var_dump(\Drupal::service('plugin.manager.search')->getDefinitions())"

If all went well you have a third plugin here together with the node and user plugin and you should see it in the admin UI of the search module in the select box Search page type.

To give a recommendation, I agree with the commment from @Berdir. It's not worth the effort to write a custom search plugins, better use Search API:

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine.


Multilingual redirects don't work from node url

tl;dr: The Global Redirect module with the option Language Path Checking enabled may allow you to enforce redirects for all users.

Node translation can be quite mindboggling. Aliases are stored per language, but that language is determined by the current path language.

With English being your site's default language, if you visit /node/2 instead of /fr/node/2 Drupal will look up the English alias for node/2. Likewise if you visit /fr/node/1, you won't get redirected since Drupal is looking up the French alias (which does not exist).

The Translation Redirect module (part of the Internationalization project) solves this, but with one gotcha:

  Note that, by design, translation redirection does not work for the homepage or for authenticated users.

(Link added by me.)

As irritating as this may sound at first: Redirecting editors to a node's language prefix brings with it a host of problems that aren't obvious at first, but can render parts of the backend unusable.

Depending on your translation workflow you may want to consider using the Entity Translation module instead.


Collapsing some fields in add content page

You could try the Field group module. You can set field group settings "collapsed" and deselect "Mark group for required fields". It collapsed the field group by default.

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


tell drush to update anything not part of a profile

This would be a good feature request for the pm-updatecode command.  I'd say that the best workaround for this missing functionality would be to tell Drush to lock the modules you do not want it to update.  Do this one time:

drush pm-updatecode --lock=project1,project2,project3

Replace 'project1,project2,project3' with a comma-separated list of all of the projects in your installation profile.  When you do this, Drush will write a lockfile into the mail directory of each project you mention, creating a persistent lock.  Thereafter, you may run drush pm-updatecode without the --lock parameter, and Drush will remember that it should not update any of those modules.

If you wish, you may also lock the modules with http://drupal.org/project/update_advanced, and Drush should respect that as well.  Works great in Drupal 6, but I have not tried Drupal 7 (only a dev release is available).


Render date field in custom format in tpl file

Ive solved it a different way. Ive created a custom date format and I can chose that as the display option for the field for a specific view mode.

/admin/config/regional/date-time/formats


Creating node-based photo galleries with prev/next links within each taxonomy (specific gallery)

Well, it looks like the Drupal 7 version of Node Gallery has everything I need. I installed it, and it took care of it without any custom configuration needed.


How to terminate a batch when an error occurs

To set $current_set['success'] to FALSE, you can use the following code.

$current_set = &_batch_current_set();
$current_set['success'] = FALSE;

To set the messages to show to the users, you can use the following code.

$batch_context['results'][] = 'The error to be shown to the user';
$batch_context['finished'] = 1.0;

$batch_context is the last argument passed to the operation callback.

The "finished" callback receives $current_set['success'], and $batch_context['results'] respectively as first, and second argument. It can show the errors to the users using drupal_set_message().

References

_batch_process()
_batch_finished()


Print rendered field in views-view.html.twig

this does get the value

{{ view.field.field_my_field.value(view.result[0]) }}


I've pasted a sample code below. Hope that helps.

 function hook_menu() {
      $items = array();

      $items['demo'] = array(
      //other code here
      );

      $items['more-demos'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-1'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-2'] = array(
      //other code here
      );

      return $items;
    }


Form State in the field instance settings form

You can't access it directly, what you can do it use #after_build which will be called with the $form_state, but this will happen at a later step.


Add "email" to /admin/people overlay view

Have you tried using Views for this? This will work well if you want to make a new page that lists all of the users. It won't work out of the box if you want to add the email information to the existing admin/people overlay.

To use Views, enable the module and go to admin/structure/views/add
Give the View a name, and then for the 'Show:' option from the
dropdown select 'Users'
To create a new page, leave the 'create a new page' item checked, give the new page a title and path, and under Display Format select 'Fields' Hit Continue and Edit
On the next screen under Fields hit the Add button, and select User:email

There are tons of options to configure with Views - check out the Views Documentation for more information if you're new to Views.


Finally got it working, the following are the changes I've made. I am writing this here in case anyone faces the same problem.

I noticed there was another web.config file in root of Drupal folder (/content) and it contains a few rewrite rules.
I've changed the last rewrite rule which rewrite all requests to index.php, it now looks like this:

<!-- Pass all requests not referring directly to files in the filesystem to index.php. -->
<rule name="Short URLS" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="false" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
    <add input="{URL}" pattern="^/favicon.ico$" ignoreCase="false" negate="true" />
  </conditions>
  <action type="Rewrite" url="/content/index.php" /> <!-- CHANGES IN THIS LINE, ADDED '/content'/ in front of index.php -->
</rule>

Modified .htaccess file in root of Drupal folder and added this line RewriteBase /content, below this line # RewriteBase /
Modified the web.config file in root folder of Angular App (/) to the following:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- Install IIS url rewrite module. -->
  <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Angular Routes" stopProcessing="true">
          <match url="(.*)" negate="false" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{URL}" pattern="^/content/(.*)$" negate="true" />
          </conditions>
          <action type="Rewrite" url="./index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

</configuration>


How to disable the title field on the node edit form?

You can use hook_form_alter() function to alter any form (including node edit form) and disable Title field. Check sample code below:

use Drupal\field_collection\Entity\FieldCollectionItem;

function [MODULE_NAME]_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_[CONTENT_TYPE]_edit_form':
      $form['title']['#disabled'] = 'disabled';
      break;
  }
}

If you're altering only one form you can check hook_form_FORM_ID_alter() function and change FORM_ID with node_[CONTENT_TYPE]_edit_form where CONTENT_TYPE is your node type form.

EDIT :

To automatically set node title without allowing user to see title field, you can use Automatic Entity Label Module. The module is in dev version for D8, but we can give it a try if functioning properly.

If don't want to use Automatic Entity Label module, you can try doing same with custom code, check sample code here


Show / Hide administration menu (module)

Very simple... Just found it myself :)

'#attributes' => array('onmousedown' => array('alert("ok")')),


Conference Organizing Distribution (COD)

COD is a distribution that you can start a Drupal project with, but you can also take the COD features and implement them into an existing site. It's just easier to start off with COD.


As described on the jCarousel module page:

  Note that you will almost certainly need to do custom CSS in your
  theme in order to use this module.

Use Chrome Inspect, Right Click > Inspect aka Chrome Developers Tools or Even use Firebug on Firefox to inspect the applied css properties and override them in your .css file in your theme folder "sites/all/themes/themename"

A basic CSS Knowledge is what you really need.

To Change the Settings of jCarousel, Go to your views and find the "Format" Area. Make sure that the "Format" is set to jCarousel and click on "Settings" beside it. A new pop-up will open. Inside, You will find all the setting related to your jCarousel initiator.

To change from Horizontal to Vertical scrolling, Click on the Advanced, Scroll down then Check the "Vertical" checkbox. See Screenshot

This is the most easy way to do it. If I understod your question rightly.


Inserting jQuery corresponding to a certain element ID

You can add a javascript file from a module or a theme, whatever is most appropriate. For scripts that should be loaded on (nearly) all pages, just add a line to the .info file of your module or theme:

scripts[] = somescript.js

For scripts that you only want to load in certain occasions, use the drupal_add_js module. See Managing JavaScript in Drupal 7 for details.

That said, there are a lot of modules out there for drop down menus, so that may even be easier. Check Comparison of various drop down menus for instance, or simply search drupal.org or drupalmodules.com.


Combining a digital and a physical version of the same product (without making 2 different nodes/products) using Ubercart

I would add the digital download as another product option after the DVD and BluRay. Then alter the option’s weight so it’s zero. Then I would create rules that allow for the access or sending a downloadable link once the checkout is complete. Also have a think about how you want to handle a cart that has both physical and digital products together.


Commerce Paypal Payment Standard Currency Conversion

The PayPal Payments Standard module only supports the currencies PayPal specifically identifies in its API documentation as supported currencies. When it encounters an unsupported currency, it converts it to whatever currency you have set as the default currency in the configuration of the related payment method rule. Since the default conversion rate is 1:1, that's why this is being passed to PayPal as 1500 USD.

I don't know to what extent PayPal supports the Dirham. If your account does, then it could be you need to patch the PayPal module to support payment transactions in AED. Otherwise you're going to need to use the Commerce Multicurrency module to set an actual conversion rate between the AED and the PayPal supported currency you want to receive payment / maintain a balance in.


You could use the hook_form_FORM_ID_alter to modify your comment form.

Also have a look at How Theme Comment Form Drupal 7 wich will tell you exactly how to achive this.


Edit Content with out seeing the information in text box

You can use the Field Permissions module to enable create/edit/view permissions per role.  So you can remove the view permission on those fields you want to hide for all roles but the admin role. That way authenticated users cannot view or edit the fields but the admin can.


Render array to markup after submitting a form

Just try like:

'#markup' => '<pre>'.print_r($form_state['temporary'], true).'</pre>';

you could just save the print_r() value to variable and then output that to a Div or something ...


Warning: uasort(): Array was modified by the user comparison function in FacetapiWidget->applySorts()

Register your own function as FacetAPI sort callback. Then select it in the FacetAPI sort order.

http://example.com/admin/config/search/facetapi/search_api%40default_node_index/block/field_animal_type/edit

http://drupalcontrib.org/api/drupal/contributions%21facetapi%21facetapi.api.php/function/hook_facetapi_sort_info/7

NB: You also accidentally collapsed the space between array and $b

function zoo_facetapi_sort_animal(array $a, array$b) {...}

/**
 * Implements hook_facetapi_sort_info
 */
function zoo_facetapi_sort_info() {
  $sorts = array();

  $sorts['active'] = array(
    'label' => t('Animal ...'),
    'callback' => 'zoo_facetapi_sort_animal',
    'description' => t('Sort by whether the animal is ...'),
    'weight' => -50,
  );

  return $sorts;
}

function zoo_facetapi_sort_animal(array $a, array $b) {
  ...
}


View that shows all children content of parent

It doesn't seem your situation calls for contextual filters, you're not listing anything dependent on circumstances, you aim to list all of the Children, and group them by parent.

Since it's Children being referencing Parent nodes all you have to do to solve this is to a create Views that list Children, add the Parent field (the entity reference field you have on Child nodes), then under your Format settings set the Grouping field Nr.1 to the Parent entity reference field. This is how you display the children nodes in a sort of a hierarchy based on which Parent they reference.

You can edit that Field settings if you want to Exclude from display and you can change the Style settings, the grouping output will take that into consideration most of the time.


Migrate to data field with multiple values

I've worked it out.
Migrate can handle multiple values but due to the commerce price table having its own field type of 'commerce_price_table' I've needed to create a field handler for this field type.

Mapping is done like this in the migration class:(machine name for this field is field_volume_price)

$this->addFieldMapping('field_volume_price', volume_price);
$this->addFieldMapping('field_volume_price:currency_code',volume_price_min_qty);
$this->addFieldMapping('field_volume_price:min_qty',volume_price_max_qty);
$this->addFieldMapping('field_volume_price:max_qty',volume_price_currency_code');

Due to these fields holding arrays of data we need to create these in the prepareRow function in the migration class:

function prepareRow($row)  {
    foreach($row->product['volume_prices'] as $volume_price) {
        $row->volume_price[] = $volume_price['price'];
        $row->volume_price_currency_code[] = $row->product['currency'];
        $row->volume_price_min_qty[] = $volume_price['minimumQuantity'];
        $row->volume_price_max_qty[] = '';//this is unknown in our data, this is set in the handler
    }
}

If anyone is interested I've attached the handler. Also due to our set of data not containing the max qty value we had to work this out and set this in the arguments.(remove the loop if its set)

class ProductVolumePriceFieldHandler extends MigrateFieldHandler {
  public function __construct() {
    $this->registerTypes(array('commerce_price_table'));
  }

  public function fields($type) {
    // Declare our arguments to also be available as subfields.
    $fields = array(
      'currency_code'   => t('Subfield: Currency code for the field'),
      'min_qty'         => t('Subfield: Min Qty for the field'),
      'max_qty'         => t('Subfield: Max Qty for the field'),
    );
    return $fields;
  }

  public function prepare($entity, array $field_info, array $instance, array $values) {
    $migration = Migration::currentMigration();
    if (isset($values['arguments'])) {
      $arguments = $values['arguments'];
      unset($values['arguments']);
    }
    else {
      $arguments = array();
    }

    $language = $this->getFieldLanguage($entity, $field_info, $arguments);
    //we need to set the max value because the our data does not provide this
    if(isset($arguments['min_qty']) && !is_null($arguments['min_qty'])) {
        $minimumQuantity = $arguments['min_qty'];
        sort($minimumQuantity,SORT_NUMERIC);
        //create the max value of the ranges, eg:
        //min qty: 1,3,5,20
        //1-2,3-4,5-19,20--1

        //reconstruct the arguments array with qtys in order
        //$index becomes the new delta
        foreach($minimumQuantity as $index => $min){
            $args['currency_code'][$index]   = $arguments['currency_code'][array_search($min,$arguments['min_qty'])];
            $args['min_qty'][$index]         = $arguments['min_qty'][array_search($min,$arguments['min_qty'])];
            $args['max_qty'][$index]         = isset($minimumQuantity[$index+1])?$minimumQuantity[$index+1]-1:-1;
        }
        if(isset($args)){
            //set arguments array for new ording
            $arguments = $args;
        }
    }

    $delta = 0;
    foreach ($values as $value) {
        if(!is_null($value)) {
            $return[$language][$delta] = array('amount' => ($value * 100));
            if (isset($arguments['currency_code'])) {
                if (is_array($arguments['currency_code'])) {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'][$delta];
                } else {
                    $return[$language][$delta]['currency_code'] = $arguments['currency_code'];
                }
            }
            if (isset($arguments['min_qty'])) {
                if (is_array($arguments['min_qty'])) {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'][$delta];
                }else {
                    $return[$language][$delta]['min_qty'] = $arguments['min_qty'];
                }
            }
            if (isset($arguments['max_qty'])) {
                if (is_array($arguments['max_qty'])) {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'][$delta];
                }else {
                    $return[$language][$delta]['max_qty'] = $arguments['max_qty'];
                }
            }
        }
        $delta++;
    }

    return isset($return) ? $return : NULL;

  }
}


Form token wrong if logging in during rebuild

The only way I could fix it was to set $form['#token'] to FALSE when building the form. This disables the token checking functionality, which isn't ideal, but I think it's my only option.


Is the video processing of the ffmpeg transcoder done locally on my server?

FFmpeg is licensed under GNU Lesser General Public License (LGPL) version 2.1 or GNU General Public License (GPL) version 2, depending on compiling options. Both are free and open source.

As far as I see in the code (just glanced over it, mind), both Video Presets and FFmpeg Converter uses locally installed converter. Will it be free? Probably not. Looking on FFmpeg Converter page:

  Note: This module is not for beginners, since FFmpeg requires rather complicated server configuration.

Sysadmin's time usually isn't free, CPU power also is not. But you should be free from licence fees all right.


hook_node_insert() sporadically not being fired after node_save()

The only other note I'd make is to ensure that you don't have an & (ampersand) in front of $node in your function definition.  I was porting from a drupal 6 site's nodeapi function and was using hook_node_insert(&$node) and it wasn't until I removed the ampersand that it started working.


how to show html content when select box item selected

In custom form you can use ajax API for this. You can find the sample code from here

When you are using node form then use conditional_fields module for this purpose.


How does a user subscribe to a group with GCC?

When you add the GCC Subscription block to the sidebar, It will not show. The only time it shows up is if a user is subscribed to a group. And then the block shows up with the unsubscribe button.

That's not true.

Here are the basic steps to make the subscription block work :

Enable GCC, GCC Context Detection, GCC Node, GCC Block
Go to admin/config/gcc/permissions and make sure NON MEMBER has the "Subscribe" permission
Go to admin/config/gcc/context, check everything and save.
Place the GCC Subscription block where you want.
Create a group.
Go to your group page with another user and you will see the subscription block


you can create two resource files, one that receives the parameter and another that does not.

Example:

  demo_rest_api.info.yml.

name: Demo REST API
description: Define's a custom REST Resource
package: Custom
type: module
core: 8.x

  /src/Plugin/rest/resource/DemoResource.php

<?php

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "demo_resource",
 *   label = @Translation("Demo Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/item"
 *   }
 * )
 */
class DemoResource extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {

      $response = ['message' => 'Hello, this is a rest service:'];

    return new ResourceResponse($response);

  }
}

  /src/Plugin/rest/resource/DemoResource_item_id.php

<?php

namespace Drupal\demo_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a Demo Resource
 *
 * @RestResource(
 *   id = "DemoResource_item_id",
 *   label = @Translation("Demo Resource item id"),
 *   uri_paths = {
 *     "canonical" = "/api/item/{id}"
 *   }
 * )
 */
class DemoResource_item_id extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get($id= null) {

      $response = ['message' => 'Hello, this is a rest service and parameter is: '.$id];

    return new ResourceResponse($response);

  }
}


Where do views/panels get their source html code

It will depend on the contents of the panel or view display as to the actual content to be displayed.  For example a panel/view might contain a node, in which case a specific display mode would be used dependant on the output settings.  Using your example whichever module provides the Format: Bootstrap Thumbnails is likely to be the candidate which can either be further overridden with a different template, or with an appropriate hook_theme.


Is there a way to iterate on all Drupal modules on d.o?

Here is a sandbox module (from a Drupal user I trust) that does it:
https://drupal.org/sandbox/greggles/1481160


Override a node page of specific content with views page

Create a views of content, set path of it to something like mynode/%(or what you want(yourpath/%)), add contextual filter Nid, set default value Get Content ID from Url,and then customize views fields with what you want.
 This link can help you about how to pass Nid to views


Add a module dependency to a sandboxed project

I am afraid that is not possible.

One dirt-fix would be to add the following in your info file.

dependencies[] = sandbox/mihai_brb/2254845

This will make sure that users will not be able to enable this module by default and cause issues. And then you can add the instructions in your module page and README.txt you can add the instructions about the dependencies and how to download them and then remove the line from the info file.

A better approach would be to use hook_requirements and in phase = "install" you can check for the presence of a function that is present in the sandbox module. If that function is not present, you can block the module installation and show a message to the user to download the sandbox module and then try installing again.


There is no page type in Drupal 8. But you can get the route name in a page preprocess hook to identify the type of page:

Route name

function mytheme_preprocess_page(&$variables) {
  $variables['route_name'] = \Drupal::routeMatch()->getRouteName();
}

and in twig:

{{ route_name }}

Route parameters

For route parameters:

 if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }

This code for the node is already in theme.inc, so you can use it right away in twig to get the content type:

{{ node.gettype }}

The node is the only route parameter that is loaded by default. You have to get parameters from other routes in preprocess, for example the view id and display id from a view route:

function mytheme_preprocess_page(&$variables) {
  $variables['view_id'] = \Drupal::routeMatch()->getParameter('view_id');
  $variables['display_id'] = \Drupal::routeMatch()->getParameter('display_id');
}


Search in comments of specific content type

For this you need to enable vote up/down and voting api module enabled
Then enable voting for 'Proposal' content type mentioned in the image

Now import the below code mentioned in views.

$view = new view();
$view->name = 'proposal_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Proposal comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test comments';
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['link_display'] = 'custom_url';
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Comment: Votes */
$handler->display->display_options['relationships']['votingapi_vote']['id'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_vote']['field'] = 'votingapi_vote';
$handler->display->display_options['relationships']['votingapi_vote']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
);
$handler->display->display_options['relationships']['votingapi_vote']['current_user'] = 0;
/* Relationship: Comment: Vote results */
$handler->display->display_options['relationships']['votingapi_cache']['id'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['table'] = 'comment';
$handler->display->display_options['relationships']['votingapi_cache']['field'] = 'votingapi_cache';
$handler->display->display_options['relationships']['votingapi_cache']['votingapi'] = array(
  'value_type' => 'points',
  'tag' => '',
  'function' => '',
);
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Comment: Author */
$handler->display->display_options['filters']['name']['id'] = 'name';
$handler->display->display_options['filters']['name']['table'] = 'comment';
$handler->display->display_options['filters']['name']['field'] = 'name';
$handler->display->display_options['filters']['name']['exposed'] = TRUE;
$handler->display->display_options['filters']['name']['expose']['operator_id'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['label'] = 'Author';
$handler->display->display_options['filters']['name']['expose']['operator'] = 'name_op';
$handler->display->display_options['filters']['name']['expose']['identifier'] = 'name';
$handler->display->display_options['filters']['name']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Comment (comment_body) */
$handler->display->display_options['filters']['comment_body_value']['id'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['table'] = 'field_data_comment_body';
$handler->display->display_options['filters']['comment_body_value']['field'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['operator'] = 'contains';
$handler->display->display_options['filters']['comment_body_value']['exposed'] = TRUE;
$handler->display->display_options['filters']['comment_body_value']['expose']['operator_id'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['label'] = 'Comment (comment_body)';
$handler->display->display_options['filters']['comment_body_value']['expose']['operator'] = 'comment_body_value_op';
$handler->display->display_options['filters']['comment_body_value']['expose']['identifier'] = 'comment_body_value';
$handler->display->display_options['filters']['comment_body_value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Comment: Post date */
$handler->display->display_options['filters']['created']['id'] = 'created';
$handler->display->display_options['filters']['created']['table'] = 'comment';
$handler->display->display_options['filters']['created']['field'] = 'created';
$handler->display->display_options['filters']['created']['exposed'] = TRUE;
$handler->display->display_options['filters']['created']['expose']['operator_id'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['label'] = 'Post date';
$handler->display->display_options['filters']['created']['expose']['operator'] = 'created_op';
$handler->display->display_options['filters']['created']['expose']['identifier'] = 'created';
$handler->display->display_options['filters']['created']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);
/* Filter criterion: Votes: Value */
$handler->display->display_options['filters']['value']['id'] = 'value';
$handler->display->display_options['filters']['value']['table'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['field'] = 'value';
$handler->display->display_options['filters']['value']['relationship'] = 'votingapi_vote';
$handler->display->display_options['filters']['value']['exposed'] = TRUE;
$handler->display->display_options['filters']['value']['expose']['operator_id'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['label'] = 'Value';
$handler->display->display_options['filters']['value']['expose']['operator'] = 'value_op';
$handler->display->display_options['filters']['value']['expose']['identifier'] = 'vote';
$handler->display->display_options['filters']['value']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-comments';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
$handler->display->display_options['link_url'] = 'demo';

It will create a block in the admin/structure/block mentioned
 in the below image. Assign it to 'Proposal' content type.

It will be displayed under proposal node view page this way

Hope it will help you.


Drupal core 7.16 with Omgea 7x-3.1 theme and loads of modules. Just experienced the similar behavior where admin menu was locked at bottom of the page. Read through this, decided to not touch Skinr and instead:

Home » Administration » Configuration » Administration

Turn of the "Adjust top margin", save, clear cache, turn on "Adjust top margin" AND "Keep menu at top of page" - this solved the problem in my case.


Service Userpoints : Missing required argument points

I finally get it.

The XMLRPC format is belowed:

<?xml version="1.0"?>
<methodCall>
   <methodName>pointss.addpoints</methodName>
   <params>
     <param>
           <name>uid</name>
           <value><int>1</int></value>
           <name>points</name>
           <value><int>150</int></value>
           <name>tid</name>
           <value><int>18</int></value>
           <name>operation</name>
           <value><string>test for operation</string></value>
           <name>description</name>
           <value><string>test for description</string></value>
           <name>entity_type</name>
           <value><string>node</string></value>
           <name>entity_id</name>
           <value><int>1</int></value>
     </param>
   </params>
</methodCall>

If somebody use service3.x and userpoints service, i hope i can help you.


How to disable/enable cache of all views programmatically?

You could switch them all off with features and a bit of hacking. Also, as this involves changing lots of things in mass, make sure you back up your work before doing it and make sure you test it out on a dev server first.

With features, you can create a feature containing just your views. You can then download this feature, which will give you something that looks a lot like a module file.

One of the files in this module will be a file called your_feature.views_default.inc, which will contain a bunch of code that will look ALOT like a view export script (because that's exactly what it is.)

If you look at the lines of code, they each represent a configuration in your views, you should be have a bunch of lines that looks like:

  $handler->display->display_options['cache']['type'] = 'time';
  $handler->display->display_options['cache']['results_lifespan'] = '3600';
  $handler->display->display_options['cache']['results_lifespan_custom'] = '0';
  $handler->display->display_options['cache']['output_lifespan'] = '3600';
  $handler->display->display_options['cache']['output_lifespan_custom'] = '0';

depending how you set your caching. Regardless, if you want to shut off caching on all your views, all of those lines need to become:

$handler->display->display_options['cache']['type'] = 'none';

One your edits are done, save the file and upload the feature module back up to your site in your sites/all/modules folder.

Once it's uploaded, head back to your site, and head to the features admin at admin/structure/features, you should see your feature hanging out there, and it's state should be "Overridden." Click on "Overridden," and you see the overview of your feature, along with a handy-dandy button on the lower right hand of the screen that says "revert components." Click the checkbox next to the views list (to tell features what you want reverted), and then click on the revert components to revert the views to what is stored in code.

Now, there is a down side to using this method. The way features works is it actually takes your view and stores it in code, not the DB. So removing your feature would actually remove you views as well. This will be true until you edit your view, in which case it would go back in the database (just that one view though, not all of them).


Basically all this means is that the module maintainers haven't opted into Security Advisory Coverage yet. Seems they haven't even opened an application in the review queue.

I asked them to do so in a new issue. As also Acquia does not recommend implementing modules not covered under the Security Advisory Policy (article). Pantheon takes that as a red flag (article), too.

But I wouldn't be worried too much. Just remember to always update this module first. But yeah, I'm not a security expert :)


Best approach for a minimal HTML5 theme for Drupal

Less or SCSS are not that dissimilar to CSS (since they compile down to CSS anyway), they just have some additional features (such as mixins) and have in some cases a nicer layout. I personally have used scss and Compass to compile my scss, and also for the ability to include resets and things automatically without having to add in your own reset.css file.

In terms of learning Drupal themes, you have a choice, either use something like the omega base theme and subtheme that, or alternatively start from scratch with a clean, empty folder with the following in it:

exampletheme/
    css/
    templates/
    js/
    exampletheme.info
    template.php

And build up from there. The existing themes, whilst good for some information, are very content-heavy (by virtue of being mature, complex themes). Use a browser such as chrome/firefox with firebug in order to find out what elements are tagged or classed as. The drupal.org theme guide and the specific section on d6 & d7 is quite a good place to start.

As far as grid frameworks, I started using 960 grid as that was something which conceptually struck a chord with me. They all have similar features, though the way they work in practice is different.


How to return the whole entity referenced by a entity reference field with views

You have to add a views relationship to the user.

The relationship is usually called something like, Entity referenced from FIELD_NAME in your case User referenced from field_user_reference.

When you have added the relationship, the user's fields will then appear in the fields list.

For more information about views relationships, look here add a relationship to a view.


Programmatically remove exposed filter in a view

Implement hook_views_pre_build() and unset using unset($view->filter['field_color_tid']);

Else, you can also try altering the exposed form in hook_form_alter() using the code $form['field_tipologia_tid']['#access']=FALSE;


Try MultiBlock module.

  MultiBlock module solves this problem by allowing you to create
  multiple Block Instances of already existing blocks. Please read the
  README for more information.


Handling custom parsing and importing with Feeds

I finally got everything to work with some code voodoo and changing parsers. One thing that I didn't add to the original question above as an edit was the fact that using the common syndication parser, my custom items that I added to the source feed were never available. I then switched to using the SimplePie parser, and was able to extend that functionality to do what I need.

According to the Feeds module documentation for developers and this blog post, you can do some custom parsing by overriding the parseExtensions() method of FeedsSimplePieParser class. First, you have to declare the class with hook_feeds_plugins():

/**
 * Implementation of hook_feeds_plugins().
 */
function mymodule_feeds_plugins() {
  $info = array();

  $info['MyModuleFeedsParser'] = array(
    'name' => 'Custom Parser',
    'description' => 'Custom parser for my video import.',
    'handler' => array(
      'parent' => 'FeedsSimplePieParser',
      'class' => 'MyModuleFeedsParser',
      'file' => 'MyModuleFeedsParser.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/plugins/feeds/',
    ),
  );
  return $info;
}

You also want to implement hook_enable to clear caches.

/**
 * Implementation of hook_enable.
 */
function mymodule_enable() {
  //clear the cache to display in Feeds as available plugin.
  cache_clear_all('plugins:feeds:plugins', 'cache');
}

Next you create the class.

/**
 * Custom Feeds parser class used to parse custom info from source site video feed.
 */

class MyModuleFeedsParser extends FeedsSimplePieParser {
  /**
   * Add the extra mapping sources provided by this parser.
   */
  public function getMappingSources() {
    return parent::getMappingSources() + array(
      'source-nid' => array(
        'name' => t('Video NID - SimplePie'),
        'description' => t('.'),
      ),
      'channel-map' => array(
        'name' => t('Channel Map - SimplePie'),
        'description' => t('Target Channel tid - SimplePie.'),
      ),
    );
  }

  /**
   * Parse the extra mapping sources provided by this parser.
   */
  protected function parseExtensions(&$item, $simplepie_item) {
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'source-nid')) {
      $item['source-nid'] = $value[0]['data'];
    }
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel-map')) {
      $item['channel-map'] = $value[0]['data'];
    }
    // Filter out non-Tags terms.
    $categories = $simplepie_item->get_categories();
    // Cycle through the categories and delete any items
    // in feed item that aren't tags. The array id values
    // are synchronized between $categories and $item['tags'].
    foreach($categories as $id => $category) {
      if (!strstr($category->scheme, '/tag/')) {
        unset($item['tags'][$id]);
      }
    }
  }
}

This code does a few things:

getMappingSources() creates a couple sources that are available for mapping. You set these in your importer settings for your processor.
Gets the source-nid value from the feed source and add it to the item.
Gets the channel-map value from the feed source and add it to the item.
Filters out the non-tags terms from the categories (aka taxonomy terms). The scheme value is the URL to the taxonomy term (e.g. mysite.com/tag/tag-term), so I use that to identify non-tag terms and unset them.

Finally, I have to create the values for the video field and the Channel vocabulary. This is done with some custom callbacks defined in hook_feeds_node_processor_targets_alter().

/**
 * Implements hook_feeds_node_processor_targets_alter().
 */
function mymodule_feeds_node_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['field_source_url'] = array(
    'name' => 'Source Video URL',
    'description' => 'The URL of the source video',
    'callback' => 'mymodule_feeds_set_source_url',
  );

  $targets['channel'] = array(
    'name' => 'Target Channel',
    'description' => 'The target video channel',
    'callback' => 'mymodule_feeds_set_channel_target',
  );
}

And the callbacks themselves:

/**
 * Custom callback to set the video source URL in field_video.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_source_url(&$node, $target, $value) {
  $source_url = variable_get('emvideo_source_domain', '') . '/node/' . $value;
  $node->field_video[0]['embed'] = $source_url;
}

/**
 * Custom callback to set the target vocabulary term.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_channel_target(&$node, $target, $value) {
  $term = taxonomy_get_term($value);
  $node->taxonomy[(int)$value] = $term;
}

You then define these as targets in your Processor mapping (to coincide with the Source values above), and you're good to go.


How to create permission to allow access to an admin form?

I think you can omit restrict access and remove the _ from your permission name.

Anyway, you have a typo in your permission key. It should be _permission instead of _permissions. See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

Make that change and clear the cache.


How to Make File Description Field Required?

depending on your needs, this could be accomplished using Field Collection, adding an image field and a description field (which can be made required) to the collection:

  Provides a field-collection field, to which any number of fields can
  be attached.

  A field collection is internally represented as an entity, which is
  embedded in the host entity. Thus, if desired field collections may be
  viewed and edited separately too.


Creating multiple image crops with each instance of an image upload

You are using imagecache. Here you can create different type of image styles. And you can use below code for display multiple images of various sizes of an original uploaded image.

 $style = 'thumbnail_200_by_200';
 $image_uri = 'public://image_name.jpg';
 $img_url = image_style_url($style, $image_uri);

 <img src="<?php echo $img_url;?>"/>


Commerce - check if this very product in presented in user's previous orders

If you have the Entity API module installed, you can do it using entity_metadata_wrappers and EntityFieldQuery like this:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'commerce_order')
  ->entityCondition('uid', $uid);
$result = $query->execute();

if (isset($result['commerce_order'])) {
  $user_order_ids = array_keys($result['commerce_order']);
}

// Array for storing user's products.
$products = array();

foreach($user_order_ids as $user_order_id) {

  $o = entity_metadata_wrapper('commerce_order', $user_order_id);

  $line_items = $o->commerce_line_items->value();

  foreach ($line_items as $line_item) {
    $l = entity_metadata_wrapper('commerce_line_item', $line_item->line_item_id);
    $products[$o->status->value()][] = $l->commerce_product->product_id->value();
  }
}

This should give you a 2 dimensional array of products like this:

... (Array, 1 element)
  cart(Array, 2 elements)
    0 (String, 3 characters ) 203
    1 (String, 3 characters ) 158
  other_state(Array, 2 elements)
    0 (String, 3 characters ) 187


This one was more obvious than I thought. Client added bogus domains to the dev environment which caused the uli to go to the wrong site.


Git push to drupal.org always returns "Everything up-to-date"

This not a real "answer" to the question I asked, but only the method I finally found to get out of my blocking situation.

Since it seemed not possible to make the remote repository to accept push attempts from its associated local repository, I took the problem from the opposite end.

After all it appears as a quite simple solution:

I renamed my local repository, say to myModule.old
I cloned the remote repository with
git clone --branch 7.x-1.x [myName]@git.drupal.org:project/myModule.git,
so getting a new myModule local repository
then I pasted whole contents from myModule.old into myModule, added and committed them
and finally used a simple git push origin (NOTE: without tag mentioned), with success

BTW, it's interesting to notice that trying with the tag mention again returned the "Everything up-to-date" message.
In the other hand, once pushed new contents, the myModule.info file displays normally rather than with the previous weird fashion.

Hope this helps somebody.


How to output a custom field in my template?

This is a perfect use case for the Field Formatter CSS Class module.

After adding a text list, radio, or taxonomy field to a content type, you then put the field on the view mode you would like for the class to be on. Use the CSS Class formatter and what level you would like to apply the class (generally node is fine), then you can add your CSS rules for whatever you want.

For example, you can change the individual caption background color on slides in a rotator, or specific stylings per post in a blog feed.


How to manipulate field with Number of value "unlimited" through php

Those if($counter++ = 8) lines look whacky to me.

don't you mean:

$counter++;
if( $counter == 8 ) {
  /* do stuff */
}

checking for equality is == or === not =


Echo taxonomy description based on specific value of a field in a custom template

So, here's what we ended up with:

$fterm = taxonomy_term_load( (int)$facil->field_facility_type['und'][0]['tid'] );
        $fname = $fterm->name;
        $description = $fterm->description;

        if( $fname == 'Hospital' ) {
            if( !empty($description) ) echo '<div>' . $description . '</div>';
        }


Showing Discount labels for products that are linked to any discount offer?

If by "ID field" you mean the name of the discount shown to customers, this is doable.

You must have a product that is the object of a "Free product" offer.

Once that is done, you'll need to add two relationships to the view. The first, you've already gotten is the link from the product to the offer:

  Commerce Discount Offer referencing products from commerce_free_products
  Trade Discount Offer referencing products from commerce_free_products

The other relationship is the link from the offer to the Discount entity itself:

  Commerce Discount referencing Commerce Discount Offer from commerce_discount_offer
  A bridge to the Commerce Discount entity that is referencing Commerce Discount Offer via commerce_discount_offer

Then you can add fields attached to the Commerce Discount entity:

Commerce Discount: Name
Commerce Discount: Admin title

And now your labels should be visible.


Hotel Diamond and Metatag: the META information doesn't appear in front page

To change/set the front page go to admin/settings/site-information, where you can set the path for the node that you want to be your front page.


You need Taxonomy Menu Trails module if you have a nested menu tree with taxonomy terms.
Try this: https://drupal.org/project/taxonomy_menu_trails


Views contextual filter using entity reference field

The usual approach for this would be to expose the images view as a block, and to show that block in the 'context' of the photographer page. In the Contextual Filter configuration for the entity reference, select 'Provide default value > Content ID from URL' under 'When the filter value is NOT available'.

This will display each photographer's gallery as a part of his page. If the URL is important, give the photographer content type a default alias of "photos/[node:title]" under "/admin/config/search/path/patterns".


Normally date labels (months, day, etc. in short and long version) should be translated automatically according to the language configured for Drupal interface (admin/config/regional/settings).

However, in case there might have been an issue somewhere, with Drush and the module Localization update enabled the following command forces the translation to be updated and it solved the issue in my case:

drush l10n-update


Can one domain be hosted on two drupal instances?

You can use a reverse proxy for this, both Apache and Nginx support this. What you do is that you make the Drupal 6 site available on a different URL. This might be even a local url, like sitename2.local. Add this to the hosts file on your server (/etc/hosts on Linux) and point it to 127.0.0.1. Make sure you set up a virtual host in your webserver to point sitename2.local to the root directory of your Drupal 6 site.

By using a reverse proxy you tell your webservice to forward calls to /topic/4 to sitename2.local/topic/4 and return it to the user, just like a proxy. In Nginx it should look something like:

location /topic/4 {
    proxy_pass http://sitename2.local/topic/4;
}

For Apache you need to enable the proxy modules:

> a2enmod
> proxy proxy_ajp proxy_http rewrite deflate headers proxy_balancer proxy_connect proxy_html

Your virtual host file should look something like this:

<VirtualHost *:*>
    ProxyPreserveHost On

    ProxyPass /topic/4 http://sitename2.local/topic/4
    ProxyPassReverse /topic/4 http://sitename2.local/topic/4
    (...)
</VirtualHost>

If you Google around for reverse proxy you will find tons of information on how to exactly configure them.


Adding extra button on node edit form with save functionality enabled

You need to add your own extra submit function to your form. The big question is - where is default one?

If default function is attached to form itself, all you need to do is:

$form['#submit'][] = 'my_callback';

Then in callback test if it was your button that triggered it.

If it's attached to button, you need to copy original button's submit array to your button, and attach your callback:

$form['yourbutton']['#submit'] =  $form['originalbutton']['#submit'];
$form['yourbutton']['#submit'][] ='my_callback';

If it's attached to form, but you want yours attached to button, the way is of course:

$form['yourbutton']['#submit'] = $form['#submit'];
$form['yourbutton']['#submit'][] = 'my_callback';


Where does drush store the different module versions for a multisite installation?

If you are using a multisite installation with shared modules stored in sites/all/modules, then Drush pm-update will also put the new modules in this same shared directory.  This means that you must also run updatedb on all of the other sites that share the same module code, as all of the sites will need to be upgraded at the same time.

It is far more convenient to use a single-site installation, and give every site their own complete copy of Drupal core + contrib modules, as you will then be able to update each site independently.  Fortunately, splitting up a multisite install is as easy as cloning your Drupal files, and changing your web server virtual hosts configuration file to point at the new site's location.


Views, show block on nodes where the node author has specific role(s)

Change access settings from access:Permissions to access:Roles and select the desired roles you want.

And for users use the contextual filters.


Cant see how it could be drupal, how are you determining that its returning empty? Are you doing a

var_dump($arr); die;

directly after your code?


Views Remember Last Selection Back Button D8

Looks like you have to subscribe to an event and manipulate the headers from there. I originally found this answer on how to manipulate headers in D8 here.

This will force a request to the server:

This file will go into your mymodule/src/EventSubscriber folder.

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class NoCacheSubscriber implements EventSubscriberInterface {

  public function RemoveCacheHeaders(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Cache-Control', 'private, must-revalidate, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('RemoveCacheHeaders', -10);
    return $events;
  }
}

Then this will go into the your mymodule folder as mymodule.services.yml

    services:
  remove_cache_options_subscriber:
    class: Drupal\mymodule\EventSubscriber\NoCacheSubscriber
    tags:
      - { name: event_subscriber }


I haven't done this, but it should work to do something like this: Once you've created the webform, on the settings for your webform, under "Submission access" you can choose to restrict "Roles that can submit this webform" to "authenticated user" and under "Advanced Settings" there's a checkbox to make the webform "Available as a block." Once you have the webform block, restrict the block to authenticated users only. Put the content that should be available to anonymous users on a new page and add your webform block to that page. The webform should then only show up on that page for authenticated users.


The Profile 2 module isn't in Drupal 7 core yet. You can download it here.

If you'd like to set up user profiles without Profile 2, you can add more fields to the user profile at Administration > Configuration > People > Account Settings > Manage Fields and play around with Panels and Views afterwards.

You can find more information here too:

How can I create user profiles in drupal 7?
How to create a profile page?


Address module PHP error due to missing interface

The command Bojan offered above did the trick:

composer update drupal/address --with-dependencies

This gave the following message:

Nothing to install or update
Generating autoload files

However, the site now displays correctly and doesn't log the message posted above.

Since it didn't seem to install anything, I presume it was the Autoload files that were the problem.

Thanks!


Strange Page not Found, Permissions, Clear cache

An answer to part of your question:

Then I noticed the strangest thing, that whenever I would clear the
cache at, I would would get an entry in the drupal_debug.txt
it entered in hook menu
I do not get this entry in the drupal_debug.txt when accessing the
wrong-answer page, I only get it when clearing the cache.

If Drupal built the menu for every page load, it would result in heavier page loads. As such, hook_menu() is only called after the cache is cleared, as the menu cache is rebuilt the first time it is needed and no cache exists. Once it's been cached, hook_menu() does not get called anymore.


Do you really need SSL on local dev environments?

It depends on the site.

Some third party tech, services, etc require SSL to be enabled and working for basic functionality. Meaning for those cases any/all development/staging environments would need to be running SSL for development and quality assurance.

In all cases the closer your development environments are to the live environment the better quality assurance can be.


I played with the domain access module and I remember I had to set the cookie domain in settings.php to ".example.com", in your case ".sscsoftweb.com".
But I'm not sure this will fix your problem.


I am afraid that Seven's page.tpl.php does not render these menus. You will need to subtheme it and modify tpl.php files to render the menus. I know you stated that you want to avoid this; however, you really should do this anyway because if you are using the theme in your app then you will at some point likely want to modify it in some way, and you don't want to customize a core theme because it will break on updates, etc.

It's worth it, because Seven is actually a great theme for internal web apps (I use it for this).

Seven's navigation was meant to be provided by Drupal's tab system. I suggest rendering your main menu and secondary menu as tabs to leverage the navigational design of Seven.


Is there a way to include jQuery-1.10.2 for specific php functions?

The issue is that the admin is trying to load two different versions of jQuery and causing conflicts.  The latest version of jQuery Update 7.x-2.4 allows you to control the back and front end versions of jQuery.  This may still cause problems with using the overlay but for the most part seems to fix the issue.  If you are still having issues you will need to look into a solution on loading two different versions of jQuery, outlined here or disabling the overlay module.


Try deleting the existing migration by doing drush cdel migrate_plus.migration.MIGRATION_ID
I think the id in your YML file is not the same as the MIGRATION_ID part of your YML file name.


How to place a library in DRUPAL_ROOT/libraries?

In drupal 7 the shared libraries were provided by a contrib module. Because a lot of modules had this as a dependency, it was very common:

Libraries API

I don't know, if this will be used this often in drupal 8, you can follow the development here:

https://www.drupal.org/node/1704734

So at the moment you are stuck with the libraries in *.libraries.yml, when you don't want to use the dev version of the Libraries API.

The libraries in *.libraries.yml were not designed for libraries in a shared directory. But they have one very useful feature, you can borrow a library from another module. There are a lot of useful packages already in core modules, like jquery ui elements. If you define a library in one of your modules, they also become available for all other modules. But the files will remain local to that module, which defines the library.


You could look at the Quick Tabs and Vertical Tabs modules.  Otherwise you could write your own custom module if you had super specific needs and are proficient with drupal menu callbacks and php and of course jQuery.


How to create entity reference field from custom entity to another custom entity?

Yes, I was right, right after I posted the question I checked if I'm missing the entity_key label, and I was. I added it in the entity annotation definition, like so:

entity_keys = {
  "id" = "id",
  "uuid" = "uuid",
  "label" = "title",
},


Can a block span more than one region in a theme?

Not by default, but the MultiBlock module will solve this for you, out of the box.


It's a guess, but the php module was removed from core in D8 and is now supplied by a contrib module: PHP

You will need to install it additionally.

Edit 1:

If you don't intend to use the module in the future, enable it only temporarily, find alternatives for the fields/text formates currently using it (if needed, the filter may be available but not actually used for php) then uninstall it again once you are done.


Create a Display Suite Custom Block Field Programatically

As already reported in this DS issue, you need to alter DS_BLOCK_CONTENT to DS_BLOCK_TEMPLATE.

We had a similar issue where from a certain point in time, the block was no longer rendered.
That point in time was a security update on the DS module, we applied somewhere a month ago :
https://www.drupal.org/sa-contrib-2018-019


How to compare two fields in a preprocess_field()

hook_preprocess_field() is invoked while rendering a single field, but (basing on the documentation for field.tpl.php) $variables['element']['#object'] is the entity object to which the field is attached. Through that, you can get the value of the other field you are looking for.


That functionality is provided by the Field Group module.

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

There is a Drupal 8 version available.


Why are two url aliases being generated for some users?

Then first go to /admin/config/search/path/delete_bulk and delete the aliases in question.

Disable Pathauto for the migration process.

Once your site has been migrated, then enable pathauto and do a bulk update /admin/config/search/path/update_bulk


admin/config/people/signup is where the settings page is located.

admin/content/signup displays "all signup-enabled posts, and open or close signups on them"


After some more research, I found the solution in a comment on this article - basically, every article I could find on the subject seems to have been written prior to some API changes being made, in how a dialog or modal is invoked.

An example link would be:

Show me a 500px wide modal

So, the key thing is that data-accepts attribute is replaced with data-dialog-type.


Getting a linkable table of children in hook_block_view from taxonomy_get_children (Drupal 7)

You can use the l() function to create the link to each term, and the theme_table() function to build your table:

function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();
      $header = array('Link', 'Vocab ID');

      $children = taxonomy_get_children($term->tid, $term->vid);

      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      $block['subject'] = t('Children');
      $block['content'] = theme('table', $table);

      break;
  }

  return $block;
}

I've put a second column in there (Vocab ID) just as an example of how to add extra columns to the table.


Displaying grouped view of node comments in a view listing nodes

So far I've only found a couple way of doing this, non of them seem very elegant.
If you choose the group by option, it does indeed duplicate all of the fields with the exception of the one you are grouping by. If you omit all the fields form the display, then click on the the grouped field and "rewrite the output" you can use tokens to output all of the fields, and they only display once. Unfortunately, this  kinds defeats the purpose of using fields in the first place. The other option is to use the node or teaser view, and make alterations to node.tpl.php and comment.tpl.php as needed ....


How to save values on each form submit without overriding saved datas?

Config items can be arrays, so something like this should work. (Note that I haven't actually set it up to try it).

      $new_filter = $form_state->getValue('ldap_filter');
      $filters = \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->get('ldap_filter');
      $filters[] = $new_filter;
      \Drupal::configFactory()->getEditable('amu_import_ldap.settings')
        ->set('ldap_filter', $filters)
        ->save();

Of course that's a very naive example, you may wish to check you are only adding unique items to the array, and so on.


is $node always available in page.tpl.php

$node isn't necessarily defined, from the page.tpl.php Drupal 7 API:

  $node: The node object, if there is an
  automatically-loaded node associated
  with the page, and the node ID is the
  second argument in the page's path
  (e.g. node/12345 and
  node/12345/revisions, but not
  comment/reply/12345).


Is bypassing Drupal's #token protection against CSRF safe for search forms specifically?

I think the biggest question when judging a potential CSRF problem is whether some form of damage will be done if a user is tricked into taking the action. If there is a CSRF vulnerability that deletes a user or unpublishes a node, that would be a problem. But being tricked into executing a search is only potentially a problem in terms of the resources a search takes to execute (which is not that much). Even if the core search doesn't bypass the token, it is accessible as a GET url (search/node/keyword) so someone could be tricked into visiting that URL bypassing the form in front.

Another way to think about it is whether the action is idempotent. A search is an idempotent action (by the W3 definition, log records might be created, but that's not a big deal), so it doesn't need CSRF protection.