Setting fallback values for a template based on a parent entity via entity reference

Had to post an answer as I need to put more code.

The desired outcome is I can do this:

{% if property.multivalue.value is fallback %}
  {% if property.somevalue is set %} {# check property for a value #}
    {{ content.field_image }} {# from property's skin entity #}
  {% else %}
    {{ chain.field_image }} {# FALLBACK value, from chain's skin entity #}
  {% end %}
{% end %}

I've got as far as this in code:

function tap_preprocess_skin(&$variables) {
  // on skins where the owner node is a Property
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'property') {

      // set a flag to decide how to handle this skin (content = inherit|fallback|new)
      $variables['skin_source'] = $node->field_property_skin_source[0]->getString();

      // additionally set a parent (chain) skin in the template
      $variables['chain_skin'] = $node->field_ref_chain[0]->entity->field_skin[0]->entity;
    }
  }
}

This gives me a scenario where I have the raw entity in the child skin template. For example, in any given node, I have {{ content }}  and also there is a {{ node }}. Here, I have (for my skin), {{ content }} and {{ skin }} and {{ chain_skin }} (latterly, as per above code). However this means I have to render the fields manually, and some of the contents of the skin is more ERs and I don't really want to have to do some massive coding exercise when there's blatantly a way to make a preprocess take #skin from Chain and make let's say {{ chain_skin_content }}, rather than the raw {{ chain_skin }}.

I'd be perfectly happy at this stage to do the logic in the preprocess but I've had no luck there either. I'm sure there's some sort of entity API function that is the right point to tap into but I've not been able to deduce it.


What would be the minimal modules I need to have for a simple registration page?

You should be able to do this with the default installation of the core + Views, Views UI, and CTools.  (You may be able to strip it further down by doing a custom installation of the core with some of the default core modules not enabled - but why bother).

I assume you're going to handle multiple events, and here taxonomy (in core) is your friend.  Just enable the taxonomy module (if necessary) and create one taxonomy term for each event. Add a taxonmy field (or multiple to allow one user to sign up for more that one event) to the users' profiles.  Ask users to register the events they plan to attent in their profile when they register (or later).

Then use Views to generate lists of names and contact addresses for the various events.

You may want to add refinements, such as not letting users cancel after they've signed up, but the above is a rough sketch of how to meet your minimal requirement.


How to change date format in the webform date element?

The date format in the field depends on the operating system settings. So it will display the date format according to the format set in your OS.
For the date format in the email, You need to change it from admin/structure/webform/config/elements in the Element formats section by setting the default format for the date field.


Converting date into unix timestamp not giving expected result

I found the solution .

If we select Field type as Date(Unix Timestamp) then $entity->field_dob1[0]['value'] will return unix timestamp value which can be directly used.

So if anyone in same requirement can use the following code:

$bdayunix = $entity->field_date_of_birth['und'][0]['value'];
$nowunix = time();
$unixage = $nowunix - $bdayunix;
$age = floor($unixage/ (365 * 24 * 60 * 60));

$entity_field[0]['value'] = $age;

PS: Dont forget to select field type as Date(Unix Timestamp).


Autofill texfields based on select option in dynamic fieldset

Give the textfield wrappers unique ids, e.g. fuel_design_tool-wrapper-1 and fuel_design_tool-wrapper-2, and assign accordingly in the FAPI array.


How can I filter the entire contents of a site by region?

You can still use views then just use the views global filter module. This way they only enter their location only once then every other view on the site inherits this filter.


How to remove the value Search from the site search form?

Sorry: you can use an image as a submit button:

<input type="image" src="images/login.jpg" alt="Submit Form" />

alternatively you can also place an image an trigger a function that will call

form.submit()

by using the img tag's onclick handler


What is the correct way to iterate over multivalue items of a form element in D7?

element_children() returns any array's key that doesn't start with #, used for properties in form API arrays, and in rendering arrays. It doesn't return numeric keys, as the function would pass to your code an array key such as "item", for example.

Instead of using the constant LANGUAGE_NONE, I would use field_get_items(), which returns the values for the language currently set for the field, which could not be for the LANGUAGE_NONE language.


Display certain taxonomy terms in Select List?

Try reference-option-limit module. It has the ability to limit your reference field value.

Another approach is to use entity reference instead of term reference and add an entity reference display to a views and select what items you'd like.
Then in your content type reference field setting and under entity selection select the views you just created.

I hope this will help.


Create backup of MySQL database alongside Features module

It's hard to encapsulate every db configuration value into a Feature. And, Features was never designed to do that. A Feature was originally supposed to be a re-usable site component.

To capture more fully site configuration look at the Configuration module:

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.

  For the most part this module provides the same functionality as a
  subset of the features module. Features module is currently the go to
  tool for moving configuration from environment to environment and site
  to site, and it does a great job doing this, but "configuration
  management" was never really what features was intended to do. The
  goal of features module was to group configurations together to
  satisfy a certain use-case. Instead most people use features to export
  configuration to code to ease with deployment between environments.
  Many of us have experienced the shortcomings of using features module
  for configuration management and found where it doesn't quite work to
  easily manage configuration. A couple other modules have spawned off
  to help with some of these shortcomings: features override, features
  plumber, Features Tools.

Additionally since not everything can be captured in Features, look into building your site via a Installation Profile where you can codify new Users, Content Types and custom variables as well.

I am currently using Features + an Installation Profile to build a webapp that lets notified individuals via email submit a Drupal Webform via a secretly keyed url parameter. You can use features (to an extent) but you really have to use many small features to get the job done, and not all modules play well with Features (like exporting Webforms, which requires node_export, uuid and THEN features) ...


How to add sidebar to taxonomy page or node page?

Normally I'd advocate writing it yourself, but in this case there are modules that do exactly what you want.

Create a block for the taxonomy you want to display and only display it on certain URL's (I'd use the path alias module to create a specific URL for relevant content e.g. '/CONTENT_TYPE/CONTENT_TITLEand test for/CONTENT_TYPE/*` on the block admin page)

https://www.drupal.org/project/taxonomy_block

You can use the Menu Trail By Path module to indicate what the active trail should be in the menu.


Custom Views Bulk Operation using Batch API

Go to VBO settings (when editing the view, next to Style: Views Bulk Operations) and for your operation select the "Use Batch API" radio button under "To execute operations".


Views can create real bottleneck for scaling and often cause great head ache by becoming resource hungry if not optimized well. Especially the use of Left Joins instead of Inner Joins, the default pagination in views and features like Distinct are major causes for the same.

The below code is a quick sample implementation which probably could fix the join issue in a view.

/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

Also, check if you can enable views cache. You can set the interval to something based on your update frequency or try to clear views_cache when something is updated on the site.

Use of views_litepager instead of the default page can also help, if you are using pagination in views.

There are several things you can do. You could read this detailed post on the topic for a more detailed understanding.


as i read in an issue in feeds  that:

  The Data processor was removed from Feeds in 7.x because Alex was unsure of the future of the data module. Seeing as there's a release of data for 7.x, it makes sense to revive it.

but if you need to implement it manually i guess this comment will help.


Prevent "→" from being written in URL alias

The transliteration module does a good job on making ASCII urls and some other useful stuff. Works with path_auto.


Is there a module that changes "node" links to "alias" links?

Other than using a process to rewrite the URLs, I don't know how to fix this after the fact.

In the future, though, the Linkit module integrates with WYSIWYGs and use filters to add URLs, which then get properly updated to the alias.


Try the Marquee Block module

  Provides a jQuery-based scrolling marquee block that can be customized with your own text or HTML. Configure speed, scroll direction and scroll behavior easily on the Block setup page.

Image from module page:

Or else if you want to do it so simple. just create a block and use <marquee> in your custom block ;)


Setting Simple Sitemap Values Programmatically not reflected in form

I figured this out, but in case anyone else runs into this. The documentation in the readme.md file shows the following format the settings:

setBundleSettings('node', 'page', ['index' => TRUE, 'priority' = 0.5])

Instead of using TRUE/FALSE I changed the index setting to 0/1 and this was successfully reflected in the form as expected.

\Drupal::service('simple_sitemap.generator')->setEntityInstanceSettings('node', $node->get('nid')->value, ['index' => 0]);


Linking taxonomy terms that appear in content

You mean automatically? You probably want something like the glossary module

  The glossary module scans posts for glossary terms (including
  synonyms). The glossary indicator is inserted after every found term,
  or the term itself is turned into an indicator depending on the site
  settings. ... The glossary uses Drupal's built in taxonomy feature, so
  you can organize your terms in a Drupal vocabulary.


How do I make a profile select option on user registration?

Many problems in Drupal can be solved in more than one way. This is also one of them.

One way might be to use the Avatar Kit module.

Another might be to create a Select field with options linking to some images you uploaded to the files folder or similar. You'd probably have to do some custom formatting if you wanted to display the options as images, and not just links or text.

The complication comes in with your request to allow users to upload their own images if they don't like the present choices. Selecting one image from a set is simple enough, and allowing to upload their preferred one is simple enough, but the combination of these options isn't as simple, it's not so common, and requires more logic than is present in the core out-of-box.

A solution that is flexible and extensible is to create a separate Media Type for these user pictures, and use Entity Browser module to build a great user experience when filling their profile forms where they can choose from a set of images you chose, or are allowed to upload a new one. This solution isn't the easiest to implement though, or at least isn't to someone who expects these features should come out-of-box.

You have to think about the images uploaded by users, are they available to all users to use or are they limited to the person who uploaded the image? This affects how you structure your Media type, different access treatment usually means you need a separate structure for it.


Can I move the description of a form field between the label and the field?

You need to override theme_form_element in your theme template.php to change the order of the form field description. See below code which will change order for all fields.

If you would like to change for only one field, then add a if condition by inspecting $element array only for your field !

function yourtheme_form_element($variables) {
  $element = &$variables['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Add element's #type and #name as class to aid with JS/CSS selectors.
  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  $output = '
' . "\n";

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }
  $prefix = isset($element['#field_prefix']) ? '' . $element['#field_prefix'] . ' ' : '';
  $suffix = isset($element['#field_suffix']) ? ' ' . $element['#field_suffix'] . '' : '';
   $element_description = "";
  if (!empty($element['#description'])) {
    $element_description = '
' . $element['#description'] . "
\n";
  }
  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= $element_description;
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";

      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= $element_description;
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;
  }
  $output .= "
\n";

  return $output;
}

Other way & simple way to solve this problem is use jQuery to change the position. This will help you !


Where do you edit the css of a basic bootstrap theme in Drupal 7?

Bootstrap for Drupal 7 requires a lot more setting up than ordinary themes.  Make sure you read and follow the instructions about installing and sub-theming Bootstrap.

If you intend to change the CSS, it is strongly recommended that you create a sub-theme with all the Bootstrap 3 source files. This method is the most dynamic and will grant you the ability to change the variables and utilize the mixins provided by Bootstrap. It entails downloading and extracting the latest Bootstrap source into your sub-theme and place it in a folder named boostrap. Note that you will need to uncomment the lines under "METHOD 1: Bootstrap Source" in your sub-theme's .info-file if you want to use this method for sub-theming.

If you've done all this correctly, the folder structure of your sub-theme (here called my_bootstrap) should look like this:

Bootstrap CSS is generated by means of the CSS preprocessor less, so you do not edit the CSS directly.  Instead look up the file my_bootstrap/less/overrides.less.  You add your CSS overrides to this file.  Then, to make your overrides effective, you can compile the file less/style.less (which includes overrides.less) to CSS with this CLI command (provided you're in the my_bootstrap root directory).

lessc less/style.less > css/style.css

If you want a simpler, but less flexible method, you may use a Bootstrap CDN.  It utilizes CDN Bootstrap via the base theme, but will still allow you to override the existing CSS styling in the sub-theme.

If you choose the CDN method, to override the default Bootstrap base theme settings, you copy the settings you want to change from the base theme into the sub-theme's .info-file. To override CSS, you edit the provided css/style.css with your own overrides.

As always, after changing the CSS, remember to clear the cache to make your changes effective.


Importing uid of the author into article nodes fails

The difference is that the fid you're migrating is part of a reference field with an internal structure, which makes 'iterator' appropriate. For nodes, however, uid is a simple property, not a field array, so you can map it more directly:

process:
  uid:
    plugin: migration
    migration: luxus_users
    source: uid


Help with content structure of a typical art gallery website

This problem is often solved using the Node Reference URL Widget. Here is a video podcast on Node References and another on how to create a gallery.

You should use taxonomy to categorize the different series. Use Views to show the series will take a node reference relationship as an argument as well as the taxonomy id of the series.


hook_module_preuninstall doesn't run early enough

Yes, there is currently no hook to do this.

The only thing you can do is have your own custom uninstall form that allows you to prepare the uninstall by deleting all data and then delete the field through the API, then point the user to the uninstall form.


The Themekey module will handle that for you.


How to create dependent fields in Entity:baseFieldDefinition?

Does Drupal provides ajax feature to use in baseFieldDefinition ?

Short answer: no

Long answer:

The base field definition method is used to define the entity structure and the database structure.

If you are trying to display different form items when the toe changes then you should do that on the form object level. By adding a #ajax attribute to the type field.


User can't access own private files via Views

Files in the private directory are not accessible directly through the web server;

You may have to use file_create_url or hook_file_download to access the files under private directory.

For More info on Accessing Private Files check here


Unfortunately, not sure what could be going on there. Drupal 7.59 is definitely the current version of core, so it may just be some odd bug generating a false negative. Does clearing the caches on the site help at all? If not, I'd just ignore it and / or look in the core issue queue for similar reports.


What database table can be emptied in order to make database lighter?

Usually all tables with cache_ prefix are safe to be emptied.

The log table records can take a lot of space, depending on your settings on how many log messages you want to save. You can configure this at admin/config/development/logging.

How many nodes/users do you have on the website? Do you have enabled the core search module? What other modules do you have?

If your website has tens of thousands of nodes and users, 1GB is a normal size of the database dump.


What is efficient way of updating drupal commerce product prices when your on a product display page?

You can make a nice edit contextual links with custom_contextual_links module in any view you would like to use this functionality.


How can I limit query results in hook_views_pre_execute?

No idea why setLimit(0) doesn't work as expected, but an alternative is to act as though you had limited the results to 0. When you add a contextual filter to a view, one of the options for When the filter value is NOT available is to Display contents of "No results found". This seems to be handled by ArgumentPluginBase::defaultEmpty(), which looks like
public function defaultEmpty() {
  // We return with no query; this will force the empty text.
  $this->view->built = TRUE;
  $this->view->executed = TRUE;
  $this->view->result = [];
  return FALSE;
}

If you drop this snippet into hook_views_query_alter() it appears to work exactly the same! I'd wager that you could drop it into any of the views hooks, actually, and it would have the same effect.
EDIT: Whoops, forgot to say you'd want to replace $this->view with $view if you're inside of the hooks.


When more than one Shipping Rules applies, select the highest

Maybe Total amount of selected products comparison in Commerce Order can be used for that condition.
A temporary solution is to apply the rule which only allows one product per cart.


How to find all views and panels that use a certain field

In D7, you can see this for views at least at
/admin/reports/fields/views-fields (Admin -> Reports -> Field list -> Used in views)

(Similarly for content types it is at
/admin/reports/fields/ (Admin -> Reports -> Field list)

Don't know about panels though.


Is there an hook_node_access() equivalent for users?

There isn't an equivalent of hook_node_access() for users, or generically for any entity.

To check which user accounts can be selected from the Entity reference autocomplete, you could change the menu callback for the autocomplete.

function mymodule_menu_alter(&$items) {
  if (isset($items['entityreference/autocomplete/single/%/%/%'])) {
    $items['entityreference/autocomplete/single/%/%/%']['page callback'] = 'mymodule_entity_autocomplete';
  }
}

function mymodule_entity_autocomplete($type, $field_name, $entity_type, $bundle_name, $entity_id = '', $string = '') {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
  $matches = array();

  if ($type = 'user') {
    // Populate $matches with the matching users the currently logged-in user can select.
    return $matches;
  }

  return entityreference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
}

Probably you need to change the access callback of the autocomplete path too, with $items['entityreference/autocomplete/single/%/%/%']['access callback'] = 'mymodule_entity_autocomplete';. The access callback defined from the module is the following one.

function entityreference_autocomplete_access_callback($type, $field_name, $entity_type, $bundle_name) {
  $field = field_info_field($field_name);
  $instance = field_info_instance($entity_type, $field_name, $bundle_name);

  if (!$field || !$instance || $field['type'] != 'entityreference' || !field_access('edit', $field, $entity_type)) {
    return FALSE;
  }
  return TRUE;
}

If then you want to avoid users can view a user account directly using the link to the account, you can change the access callback for user/%user/view.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/view'])) {
    $items['user/%user/view']['access callback'] = 'mymodule_user_view_access';
  }
}

The default access callback is user_view_access(), which contains the following code.

  $uid = is_object($account) ? $account->uid : (int) $account;

  // Never allow access to view the anonymous user account.
  if ($uid) {
    // Admins can view all, users can view own profiles at all times.
    if ($GLOBALS['user']->uid == $uid || user_access('administer users')) {
      return TRUE;
    }
    elseif (user_access('access user profiles')) {
      // At this point, load the complete account object.
      if (!is_object($account)) {
        $account = user_load($uid);
      }
      return (is_object($account) && $account->status);
    }
  }
  return FALSE;

Drupal 8 uses hook_entity_access() to control access to any entity (including users) to various operations, hook_ENTITY_TYPE_access() to check the access to specific entities on various operations (for which hook_node_access() is the implementation for nodes), and hook_entity_create_access() to check which users can create an entity.
Drupal 8 code is much simpler than the Drupal 7 code, as as a single hook implementation does the task.


How to combine two contents of same type and display in views

There is a module for that, Views Merge Rows. From the project's description:

  Sometimes when you use relationships in views you get a number of rows
  with the same content in some of the fields. This results in a huge
  table (grid, list, etc.) that affects the usability of your view. The
  Views Merge Rows module provides a way to combine rows with the same
  content in the specified fields.

Keep in mind that there is a pretty straightforward guide to configure the module in the project's page that includes very descriptive screenshots.


Initialize & override a Drupal7 jQuery module's (Superfish) provided .js, in code

The JavaScript that you have written for Drupal 6 and 7 does the same thing, only the targets has changed a bit ul.sf-menu vs .sitemenu-inner .sf-menu ul.

This gives a few options as to what could be wrong.

You have a different superfish version, that behaves a bit differently
Your markup has changed and doesn't work like it did for your Drupal 6 site.

It's hard to debug why you're not getting the desired result, you could try to test out superfish on a static page and see if you can get it working. That will reduce some of the complexity and reduce your problem to a JavaScript/jQuery problem.


How do I programmatically store a file reference in a node?

Assume, we have content type : Image

It have following fields in the content type.

title
field_imagedata for Image field

Now, we want to create custom node.

Step : 1  We need to get static image path which we would like to attach in the node. We have in "sites\default\files\2017-01\source.png"

So, In drupal, we could access this image uri by "public://2017-01/source.png".

Step : 2 We need to create file reference in our Drupal database. Se we need to use "File::Create" method.

Step : 3 After that, we could generate node using "entity_create".

Please look at the whole code.

    $uri  = file_unmanaged_copy("public://2017-01/source.png", "public://2017-01/destinatio.jpg", FILE_EXISTS_REPLACE);
    $file = File::Create([
      'uri' => $uri,
    ]);
    $file->save();

    $new_page_values = array();
    $new_page_values['type'] = 'image';
    $new_page_values['title'] = "PARAG";
    $new_page_values['field_imageda'] = array('target_id' => $file->id());
    $new_page = entity_create('node', $new_page_values);
    $new_page->save();

Also, you could update the node, by using the following code.

    // Load existing node and attach file.
    $node = Node::load(1);
    $node->field_imageda->setValue([
      'target_id' => $file->id(),
    ]);
    $node->save();

Using this code, you could create new node with the static file.


It could be this issue with features and menus, for which there is a patch: http://drupal.org/node/1283742

Something to be aware of: menu links don’t show up in the admin UI, or get added to the database, if their path does not link to an existing node.


Create a view with the contents of "self"

You need to use contexts which is located under advanced to the right.

See below:


How can I force Composer to install a dev branch over a stable release?

While it will install the latest dev release of the Drupal module/theme to simply do the following:

composer require drupal/bootstrap:3.x-dev

I would argue a best practice when installing a dev version of a module is to make sure you are going to get the commit you want (which might not be the latest), so I would do the following:

composer require drupal/bootstrap:3.x-dev#5670922dea05fffb6506a6cd5d53546b9fae8df9

Or you can manually add it to your require in composer.json (as below) and then on the command line run composer install

"drupal/bootstrap": "3.x-dev#5670922dea05fffb6506a6cd5d53546b9fae8df9",

To get the commit you should go to http://cgit.drupalcode.org/bootstrap/log/ and find the commit you want (the commit hash is the id on the commit's page).
btw: the above hash is not a real commit on the Bootstrap project


getFormId() must be compatible with Drupal\Core\Form\FormBuilderInterface::getFormId (Drupal 8)

In my project it works as public function without arguments since drupal beta 1 until today (i've updated today to rc3):

 public function getFormId() {

You only have to add public to your function.

Otherwise your error suggest, that there are the two arguments form and form_state missing, what is also described in the api.drupal.org:

public function FormBuilder::getFormId

But I don't think, that you need these arguments in the definition of the getFormId(). This is probably a false alarm. You only need these arguments, when using the function in the context of formBuilder, when you don't provide the form through your class, for example like this:

this->formBuilder->getFormId($form_arg, $form_state)

Edit:
Berdir has the right clue, you have to change this:

wrong: class AddForm implements FormInterface {
right: class AddForm extends FormBase {

and the use statements for this are:

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

This is a complete example:

<?php
/**
 * @file
 * Contains \Drupal\mymodule\Form\OrderForm
 */

namespace Drupal\mymodule\Form;

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

/**
 * Implements an form.
 */
class OrderForm extends FormBase {

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

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

  }

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

  }

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

  }


Running an "is all of" filter on a field collection

I have a solution that's a bit of a work around, but seems to work fine. I ended up using the same relationship multiple times and increasing the delta value by 1 with each new relationship which pulled in each option in the subcategory (think first field in the field collection). I then grouped the fields and used a combine filter to run the "is all of" search. Seems to work great and isn't overly resource intensive. This will give you a 1 to 1 result based on whatever is in the the field collection field item you build the relationship off of.

Hope this helps.

Best,
Shawn


I think DraggableViews is what you are looking for. Here is a quote about it (from the module's project page):

... makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
Have you ever rearranged Blocks, sorted Taxonomy terms or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
With DraggableViews you can apply this tabledrag.js to any Views-generated table.


How can I disable theme update notifications?

The Update Status Advanced Settings enables you to disable any project, including themes, that you don't want to be alerted about updates for.

  Extends the administrative interface for Drupal core's "Update status" module (added to core in 6.x).

  Users of the 5.x Update status contrib module will probably want to use this once they upgrade to 6.x, since some of the functionality in the contrib version was deemed too complicated to include in core. In particular, the per-project settings to ignore certain projects or even specific releases, is absent in the core version of the module. The "Update status advanced settings" module restores these settings, and might eventually provide additional functionality for the core "Update status" module.


How can I get all fields and values of a node at once?

This is how you can add all values in a custom array. The EntityManager class and the entity.manager service are deprecated; you should use the entity_type.manager service instead.

$publications = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->load($node_id);

foreach ($publications->getFields() as $name => $field) {
  $myFields[$name] = $field->getString();
}

kint($myFields);

You need to improve this code because for some field types that can be different.

For multi-value fields you use $field->getValue()
For entity reference fields, $field->entity->field_name->value


Why aren't you using facets?

That's how blocks which list search results grouped according to a certain criteria are called and it's a built-in feature of Search API.

All you need to do is get Facet API, enable the integration module search_api_facetapi, enable the type field, set it up as a facet and enable the block.

That block then doesn't just list the content types, you can also click on it and the results are automatically limited to that type.


'Flags: Node flag relationship' - Search Api - Solr - Views

Forgot the close this a long time ago.  Anyway, I wrote a custom module for solr to index some extra data, and a views handler to do what I needed.


How can I control class="active" in a submenu


You can add custom fields to Ubercart orders the same way you add custom fields to content types. They can be added by going to Store -> Configuration -> Orders -> Manage Fields (admin/store/settings/orders/fields)

These fields would then be available on the order admin pages.

Hope that helps.


drush open_basedir restriction in effect on media temple

drush topic docs-ini-files

That command tells more about creating a drush.ini file. In it, you want to remove the listed restrictions (you didn't provide them).


checkboxes on submit not showing correct values. Shows 0 always

While we can't see how your form is built completely, it might be that your custom attributes are affecting the element "name" in the form state.

i.e change

'#attributes' => array('name' => 'field-'.$code.'-'.$id),

to

'#attributes' => array('data-name' => 'field-'.$code.'-'.$id),


Creating a view that shows multipule blocks containing content with filtered by differnt taxonomy terms

You could make a parent block view that has all of the subsequent views as attachment display type.  Or add the other views in the footer of your first view...


How do I create a Zen's sub-theme using Drush?

Reading How to build your own sub-theme (7.x-5.x) using Drush, I get that the commands should be the following ones.

drush dl zen
drush en zen
drush cc all
drush zen "Name" machine_name --description="Description." --without-rtl

In order, the commands:

Download the Zen theme
Enable it
Clear the cache
Create the sub-theme
The reason of the second command is explained in the linked page.

  Ensure drush knows about the zen command

  After you have downloaded Zen and placed it in your sites/all/themes directory, you need to enable the Zen theme and clear Drupal's (and Drush's) cache so that it will notice the Zen drush command. Type drush en zen followed by drush cc all.

As for running Drush on the remote server or in the local server, see this answer from one of the Drush maintainers for How to use Drush in remote server?

  It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed.  This is possible because the Drush commands drush rsync and drush sql-sync work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.

  In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias.  Otherwise, Drush will try to use Drush on the remote system to look up these values.  See example.aliases.drushrc.php for more information.

  Note that it is really useful to be able to at least run drush updatedb on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster.  The Resources page on drush.org lists some hosting providers that are Drush-friendly.

Keep in mind that you could create the theme on your local site, and then copy the files over the remote site, or in a git repository that you then use when deploying your server.


The Exif Autorotate module

  Automatically rotates any uploaded image file according to the EXIF
  orientation information.

This EXIF data is embedded into the photo by the camera (and is often lost in compression). It contains the author, aperture settings, shutter speed, camera position and much more.

So if your photo is not created by a camera, or is already in the upright position, or has been compressed or downloaded, nothing will happen.

  My requirements are as the image is uploaded the user sees the image
  and if wants to rotate it by clicking on it to do so.

EXIF Autorotate does not rotate the photo by clicking on it, it rotates the photo to the position the camera shot it in (landscape or portrait).


Add Custom Line item API or Method Drupal Commerce

Why not use Commerce Product Options which provides this functionality out of the box, directly in the default Add to Cart form?

To adjust the price based on the chosen options, you can use the Commerce Pricing module, which comes as part of the Commerce project. It basically provides a number of rules conditions and actions which allow you to adjust the price of a line item and e.g. add a fixed amount or multiply it by a certain value.


I want to add an include_path but don't have access to php.ini

settings.php would probably be the safest bet.

The template.php file might well be included too late in the process to have the desired effect, but settings.php is included indirectly from drupal_bootstrap() so should take effect before any of your custom code has a chance to run.

If you don't want to alter settings.php in that way you could implement hook_boot() in a custom module which is also invoked very early on in the page build process.


For future users, there's a bunch of confusing examples out there. Based on the above link example this is my working setup:

URL: /rest/user.json

Headers:

"X-CSRF-Token":"fsddfhbusoibdfbdsbfoubewbfw"
"Content-Type":"application/json"

Body:

{
 "name":"username",
 "pass":"password",
 "mail":"email",
 "field_user_full_name":{"und":[{"value":"CHECK1 n CHECK2"}]},
 "roles":[4],
 "status":"1",
 "language":"und"
}


How to add attachment in views slideshow

All you need to do is to add your text field to the "Fields" section of this view. Not as an attachment. As a field.


Why does the Configuration Management module warn not to use in production?

As you can see module is in Alpha phase. It's available for community testing so that they can able to fix issues and make it stable.

Every project in Drupal.org go through different phases. Please see more above Project Versions here.

Alpha version refers to

  These are the first to come out, and are therefore the least stable.
  Most reported errors are resolved but there are most likely still
  outstanding known issues, which might include security issues.

  These releases are not yet stable enough for production use, but are
  essential milestones on the way towards the official release. They
  allow a much wider pool of users to test the latest code and provide
  feedback before the official stable release. These releases should
  only be downloaded and used by developers very familiar with Drupal or
  those wishing to help find bugs in the software.

Since Drupal projects entirely community driven, Module maintainers releases projects for testing. Once they are stable you can use them in Production Environment.


Change Standard Title for Adding Content Into Something New? Also Redirect to the Page You Were On?

For the dynamic node titles you might want to take a look at Automatic Nodetitles module. It allows you to use tokens in the node title. These token can represent text from node fields.


visually resize images when uploaded inline in ckeditor

There's a pretty simple solution, but it does feel a bit hack-y.

Add a CSS file to a module/theme with contents like

img { max-width: 200px; height: auto; }

Implement hook_ckeditor_css_alter() to get that CSS file loaded in the WYSIWYG iframe:

function hook_ckeditor_css_alter(array &$css, Editor $editor) {
  $css[] = drupal_get_path('module', 'mymodule') . '/css/mymodule-ckeditor.css';
}

Once that's up and running images in the WYSIWYG should be constrained in width to whatever you set in the CSS file. You might need to resort to !important, depending on what other styles are already active; it'll need some tweaking no doubt.


This is a bug in core, see https://www.drupal.org/node/2543726
In the meantime, you could write a new normalizer service that is only for terms.


How to skip client side validation for draft node?

You can add a 'cancel' class to your draft button and it will skip clientside_validation, we do this out-of-the-box for the delete button, code can be found in clientside_validation.module, line 278


What is the equivalent of hook_user with $op='form' in Drupal 7

hook_form_user_profile_form_alter(&$form, &$form_state)
I think its what you need


Print exposed filter in different postion

Are you trying to display it in a different region? Views has an option for that. When you have one or more exposed filters, you'll find an EXPOSED FORM option in the advanced tab that will allow you to detach the form and display it in a block.

From there you can place it anywhere just like a regular block.


How to connect to multiple Databases in Drupal 7?

Two steps:

Add database credentials to the $databases array in settings.php file. You can have as many additional databases as you want. Example code:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_DEFAULT_DATABASE',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'your_second_db_alias' =>
  array (
    'default' =>
    array (
      'database' => 'YOUR_SECOND_DB',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Use the following code to change the database and run queries. Note that you must switch back to the original database afterwards.

// Change active database.
db_set_active('your_second_db_alias');
// Run queries.
$query = db_query("SELECT * FROM yourtable");
// IMPORTANT: return current active database to the default one. If you
// don't do this, everything after that point will be executed against the
// above database, and cause errors most probably. If you are connecting
// multiple Drupal installations, you can cause a pretty big mess if data is
// partially saved in the other database.
// Always double check that you have this line!
db_set_active();

Hope this helps!


Why do I get the following errors when I install themes and modules on the website locally running on my Mac?

Go to /admin/config/media/file-system
and change the 'Temporary directory' from
/tmp to tmp


Execute a file in the body of a specific content type

Looks like you are looking for Code per Node module:

  Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system.


Afaik, there's no requirement that a Content Entity must store the id of the user who created/edited it. However, many entity types do use a common method to store the owner information - Drupal core's user module provides an EntityOwnerTrait that many entity types use. (At least Node, Media, etc, all use this trait.)
For example, if you're looking for the owner of an entity that uses this trait, you can use the getOwner() method like:
$owner_user_object = $entity->getOwner();

It's unclear if user U2, in your example, would be the owner of the entity or just the author of a particular revision. If your entity is storing revision information, and the entity extends EditorialContentEntityBase (Note that they probably do. Node, Media, etc, all extend this base class) then it's also possible to load the author of a particular revision.
First, load the revision. See @baikho's comment pointing to Preferred way of loading a specific entity revision.
$entity_revision = \Drupal::entityTypeManager()
  ->getStorage('MY_ENTITY_EYPE')
  ->loadRevision($MY_REVISION_ID);

Once you'd loaded the revision, you can get the author of that revision with the getRevisionUser() method like:
$revision_user_object = $entity_revision->getRevisionUser()


Can I use the CTools modal functionality under HTTPS adn Display Suite?

HTTPS should just work, or I would say there's a bug in ctools.

I haven't used DS much, so can't really comment, but DS handles View modes, and I would expect all ctools modules to deal nicely with those.


How do I add a menu subtitle to field sets displayed as vertical tabs?

The tab summary is set by JavaScript (I don't think you can do it in PHP), per the comments in misc/vertical-tabs.js:

  Each tab may have a summary which can be updated by another script. For that to work, each fieldset has an associated 'verticalTabCallback' (with jQuery.data() attached to the fieldset), which is called every time the user performs an update to a form element inside the tab pane.

The node module has a good example of how to do this, the code in node.js should be pretty easy to adapt for your own module:

Drupal.behaviors.nodeFieldsetSummaries = {
  attach: function (context) {
    $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) {
      var revisionCheckbox = $('.form-item-revision input', context);

      // Return 'New revision' if the 'Create new revision' checkbox is checked,
      // or if the checkbox doesn't exist, but the revision log does. For users
      // without the "Administer content" permission the checkbox won't appear,
      // but the revision log will if the content type is set to auto-revision.
      if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) {
        return Drupal.t('New revision');
      }

      return Drupal.t('No revision');
    });

    ...

I think the only PHP change you'll need to make is to add a specific class to the fieldset so the JS can target it:

$form['episode'] = array(
  '#title' => t('Episode details'),
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#collapsible' => TRUE,
  '#group' => 'vertical_tabs',
  '#attributes' => array('class' => array('mymodule-node-options')),
);


How do I redirect from /index.php/event/* to /event?

You can use Match Redirect module.
How to use:
1) Enable module as usual
2) Go to configuration page /admin/config/search/match_redirect
3) Add redirect settings there


Views: Is it possible to Group "exposed" filters in a  and add css to it?

Exposed filters appear in a form so you have to use hook_form_alter
as well as hook_theme to theme any form.

Using hook_form_alter assign a new theme to that particulat form.
hook_theme is usead for register a new theme.

For more information about form theming visit here


Drupal - Just want to add HTML to a node's form element how?

Create own helper module. Use hook_form_alter(), specifically hook_form_node_form_alter() variant. In it, just add #markup element.

$form['my_markup'] = array(
  '#markup' => "Your HTML here",
);

But in content of your question, it seems you want more than own html. It looks like you want to add some active elements. So see Form API Reference for elements you need. To process values, you will need to define submit handlers.


Redirect from edit page and prepopulate form

You can try using Node Clone module...

Project page says

  The module provides two mechanisms to clone current content. The
  default pre-populates the form for adding a new node, but nothing is
  saved to the DB until that form is submitted. With the alternative
  save/edit method, a copy of the current node is saved to the DB, and
  then presented in the edit form. When using the save/edit mode, the
  admin can set whether a confirmation screen is required, and in all
  cases you can set whether to reset the publishing options on a
  per-content-type basis.


How to set up a 'review-like' view that connects users to nodes?

I've created these types:

Item (node) : has entity reference field to node of type endorsement.
Endorsement (node) :  has entity reference field to user (which I guess has role advocate in your case)

The View:
Base table of nodes, filtered by type 'Endorsement'

Two relationships:

A bridge to the Content entity that is referencing Content via field_endorsement (as we have nodes of type endorsements in our base table, we need to link it to 'Item'. 'Item' has the entity reference field containing endorsement, hence we go in reverse: ie referencing)
A bridge to the User entity that is referenced via field_advocate (as we have nodes of type endorsements in our base table we need to link it to User. Endorsements has an entity reference to user, hence it is a simple forward relationship, ie referenced)

Now add the Contextual filter of type nid. Set its relationship to 'Content referencing Content from field_endorsement', which was the first relationship added. The nid we are passing it is of type 'item', hence we must link it via the relationship to 'items'. Set 'hide view' 'when filter value is not available'.

For argument input: From panel argument, First argument.

Add your fields as you want. There is no need to add nid as a field unless you need to do so for a specific reason.

done with the view, back to the panel: add the view to the panel content for the page, and tick 'Send arguments'


How to create an editable table (by users) from Webform submission data?

You could use Editable Views

Drupal Editable Views demo


You're piping the output of the Drush command to gpg, but it's expecting a file path.

By default the output will not be something that gpg can use, but archive-dump has a handy --pipe option which will print just the path to the output file; gpg can use that:

drush @mysite archive-dump --pipe --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" | gpg -e -r mypublickey &>> /var/log/mysites/$(hostname -s)/drush-cron.log


Roles can be added to users who are authenticated users, which means they logged in. Anonymous users are only anonymous users; no other role can be added to them.

If you are just trying to show a page differently basing on the what selected from the anonymous users, then you can use a cookie to store a value that is used to alter the user interface. In Drupal 7 there are two helper functions that can be used to delete and save a cookie containing values for an anonymous user: user_cookie_delete(), and user_cookie_save().


How do I keep l() from escaping my link's text?

@Kojo's answer is getting a bit crowded and confusing IMHO so let me post my recommended approach here.

'html' => true

The key to the problem is passing the html option to the l() function like this:

<h3>
  <?php print l(
    $fields['title']->content,
    'node/' . $fields['nid']->content,
    array('html' => TRUE)
  ); ?>
</h3>

This tells l() to bypass the check_plain() function which normally escapes the link text.

Security

Using 'html' => TRUE is a security risk if you are not sure if the author can be trusted (ie. it is user generated content).

Depending on where the variables in your template come from, $fields['title']->content may already have been sanitized. You can test this by setting the title to <script>alert('hi');</script>. Load the page. If you see a javascript popup, you have an XSS vulnerability to fix. Fortunately, Drupal has a couple of functions built in for that.

Solutions for an XSS vulnerability

Use filter_xss(). A filter that only allows a small selection of HTML tags, fixes invalid markup, and filters out XSS risks. Example:

l(filter_xss($unsafe_text), $path, array('html' => TRUE));

Use filter_xss_admin(). This is a very permissive option, like filter_xss(), but only recommended to filter content entered by trusted site admins. Example:

l(filter_xss_admin($unsafe_text), $path, array('html' => TRUE));

Use check_markup(). This is the most configurable option. It uses one of your configured text formats, such as "filtered html", to filter out all but the whitelisted html tags (it will call filter_xss() for you). It will also apply other filters enabled on the text format. Make sure you choose a text format which has the "HTML filter" enabled in its configuration. Example:

l(check_markup($unsafe_text), $path, array('html' => TRUE));


"Source database does not contain a recognizable Drupal version."

At this stage, I don't think there is a simple option to upgrade from 7 to 8. As you can see on the release note:

  Once you are ready, Drupal 8 core also includes the Migrate module to
  update existing Drupal 7 and 6 sites to Drupal 8 directly. Migrate is
  marked "experimental" in Drupal 8.0.0, but will be fully supported in
  an upcoming release.
  https://www.drupal.org/news/drupal-8.0.0-released

A little bit technical behind the scene:
From 7 to 8 version, they keep the same concept when building site (like node, entity, permission, views...) but not the core. I would say: they changed everything to OOP, Symfony component, architecture...
So there is no way to upgrade your drupal site directly from decent version to 8.0, you have to migrate. Here is how the migrating process should look:

Recreate the site with the same functionality to your d7 site.
Recreate the theme (using twig template)
Migrate content over

The cost to this process is (unfortunately) same to recreate a new site or more.
With the no 3, take a look at this article by Phase 2: https://www.phase2technology.com/blog/upgrading-to-a-drupal-8-site/


POST taxonomy item using Services module

Here is the JSON format to add taxonomy term. I've tested it and works perfect.

{
    "vid": "2",
    "name": "Term Name",
    "description": "your description"
}

Here vid: vocabulary ID

Make sure the current logged-in user has privileges to add taxonomy term. and make sure to add token in Headers like follows

name: X-CSRF-Token

value: your-token

To know your token access the following path

yourdomain/services/session/token


Best way to show another site's page via Drupal?

You should be able to use this.  Enable PHP code mode and paste it into a page:

<?php
  $curl_handle = curl_init();
  curl_setopt($curl_handle,CURLOPT_URL,"http://www.google.com");
  curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
  $html = curl_exec($curl_handle);
  curl_close($curl_handle);
  print $html;
?>


How to insert a image gallery into node body?

This may or may not work for you, try WYSIWYG FIELDS module. If it doesnt work, I cannot think of another turn-key solution.

  The Wysiwyg Fields module is bridge between CCK Fields and the Wysiwyg
  module, allowing most (if not all) CCK fields to be turned into a
  Wysiwyg button for a convenient inline solution.


Related nodes by taxonomy term in a view block of drupal7

There will be a significant amount of customization (in the form of a module) to get this done through views. I've created a sandbox module that you can install to get things working and so you can play around with it (see views.api.php in the views module).

Once enabled you should find a new contextual filter value called "The node whose taxonomies you want to relate". This contextual filter default will take the current node ID and return nids of nodes that share the same terms in vocabularies that you select. Therefore, please set the view display as a block.

If you need to know how to group by term using views, please see this answer.


What's the best way to create a booking form?

If you're new to Drupal, I would first try the webform module.  This is a very popular, well tested module that often gets security fixes which less commonly used modules may not get.

It has all the basic functions you need for creating the options for the form and can easily be configured to send an e-mail upon submission.  It will also leave a record of all submitted data in the Drupal database.

To be honest, off the top of my head I'm not sure if webform can do the computation you request or not.  However, for that there is the computed field module, which will allow you to write a simple function in PHP to compute the value.  Alternately, you could use the rules module's "on node save" event with the action "compute data value" to calculate the total price.

There are a number of other approaches as well but these are commonly used Drupal modules with fairly good documentation and thus are, I think, a good place to start.


Disable Internal Page Cache And Enable Dynamic Page Caching

There are two different topics involved here.

You can disable the Internal Page Cache if you want to replace it with Varnish (both are reverse proxies for anonymous traffic, delivering content before the request reaches Drupal, and you don't need two of them).
Memcached on the other hand is a memory based cache backend, that sits behind Drupal caches (you can configure which ones, this can also be the Internal Page Cache if it is still enabled).

  Can we enable and use both varnish and memcache?

Yes, they work independently from each other, one in front and one behind of Drupal.

  Does enabling of varnish or memcache will disable drupal's default
  dynamic page caching?

No, it doesn't make a difference for the Dynamic Page Cache, because it won't see any traffic served by Varnish or the Internal Page Cache and Memcached only makes it faster, but doesn't change how it works.

  And also how to enable and configure varnish or memcache in drupal.

There are modules to configure them. For Varnish to make it invalidate cache tags and for Memcached to set up the cache backend.


Well after much trial and error  which included rebuilding permissions more times that I want to count. I came up with a solution based on the following link:

http://drupal.org/node/200631

A combination of Taxononmy Access Control and Taxonomy on content type, which allows for a almost module-less solution.

Hope this helps someone else.


Change view & edit route or URL of Entities generated by Drupal Console

You need to edit the entity class's annotation, at e.g. module_name/src/Entity/FooEntity.php.

This is an example of what you need from the Node entity class:

links = {
    "canonical" = "/node/{node}",
    "delete-form" = "/node/{node}/delete",
    "edit-form" = "/node/{node}/edit",
    "version-history" = "/node/{node}/revisions",
    "revision" = "/node/{node}/revisions/{node_revision}/view",
}

You'll probably need to rebuild cache for the changes to be reflected.


Check out Twitter validator tool for possible reason. The Twitter specification may help you as well.


You can do it by creating templates for different types of pages.

e.g. If you have different layouts for front page, you can create page--front.tpl.php.
It will work for front page only, for rest of the pages page.tpl.php will work.

If further you have different layouts for page types, e.g a normal layout for pages and different layouts for article type of pages then you can create two types of tpl.

node--article.php, if you have the same header and footer content and just content part design is different.
page--article.php (page–[node-type].tpl.php), Here you can customize the content part as well as different layout for header and footer part.

Also there will a customization option in the manage display part of the content type.

Hope it will help you.


Adding extra parameter to hook function in custom module / get custom variable inside a hook from outside of that hook

You're already doing it the right way. You aren't in control of that particular hook so you can't control how it's invoked, and what parameters are passed.

Couple that with this information from the drupal_alter() docs:

  A maximum of 2 alterable arguments is supported. In case more arguments need to be passed and alterable, modules provide additional variables assigned by reference in the last $context argument:

And that means that in order to make changes to the arguments you'll need to patch the module that provides the hook.

You might want to consider variable_get() and variable_set() if the $foo variable is likely to change at all, or DB storage if it's something major.

But using a helper function to return that data is perfectly good practice; there are dozens of examples of the same in Drupal core itself.

Or....you could use the global keyword (emphasis because I wouldn't personally recommend it, it's not particularly good practice to pollute the global scope).

That would go something like this:

$foo = 1;
function hook_tapir_table_alter (&$table, $table_id )  {
  global $foo;
  echo $foo;
}


Drupal uses renderable arrays, so there is probably something like this:

'location_outter' => array(
  '#type' => 'fieldset',
  '#title' => 'location',
  'location_inner' => array(
     '#type' => 'fieldset',
     '#title' => 'location',
     'city' => array(
        '#type' => 'textfield',
        '#title' => 'City',
     ),
   ),
);

So i think you can, if it is form, try use alter hook, for example yourmodule_user_form_alter and modify that renderable array.


Commerce limit the quantity of product to 1

What you will want to do is add an event subscriber to the Add to Cart event (https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/cart/src/Event/CartEvents.php#L30).

Here is an example piece of code that would react to that event. This is for a Drupal Commerce site which only allowed purchasing one product at a time with a quantity of one.

/**
 * Sets quantity to 1 and ensures only one product in the cart.
 *
 * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
 *   The cart event.
 */
public function onProductAdded(CartEntityAddEvent $event) {
  // We only want 1 quantity.
  $cart = $event->getCart();
  $added_order_item = $event->getOrderItem();
  $cart_items = $cart->getItems();
  foreach ($cart_items as $cart_item) {
    if ($cart_item->id() != $added_order_item->id()) {
      $cart->removeItem($cart_item);
      $cart_item->delete();
    }
  }

  $quantity = $cart_items[0]->getQuantity();
  if ($quantity > 1) {
    $cart_items[0]->setQuantity(1);
  }

  $cart->save();
}


Adding Background image in Views template file

Adding CSS background image hardcoded in the Twig (or TPL in D7 sites) isn't a best practice. You should do this via your theme's css file like style.css, or via a module (some theme's give you the opportunity to add it directly on your site).

I would suggest to restore any such changes in the Twig and redoing it in the css file.


Adding a reference to a bundle in a node

Enable the Entity Reference module that is the part of drupal 8 core.
Create the two content types.

I have two content types: (1) Articles (title, author, body) (2)
Authors (First name, Surname, Biography). Authors are not users.
When adding a new article, I want the option to select either (a) An
existing author from a list, or (b) Add a new author to the list, and
select it.

Add a entity reference field in the Articles content type.
Go to Home Administration Structure(admin/structure/types) click on Manage fields in front of Article content type.Add a new field(Authors) and choose its field type to be Entity reference and after save, The field configuration screen will open.Choose "Type of item to reference" to Content. Then on the next screen choose the reference type(authors content type).

When displaying the article, I want to see the author's First Name and
Surname, and optionally a Biography teaser, and then the body of the
article.

There are several options to do so :
1)Load the authors entity in articles template and display its result like that.
2)Use the Display suite module which is still has alpha available.
3)Create the view block which displays the author information like you want to show.and embed this view in your node article template.
4)Go to Manage Display of that content type(admin/structure/types/manage/article/display) and use a separate display mode to do so.
5)etc....
I would suggest to use the Display suite because I love to use it as it made my life easier at many places.


Panels are page nodes and can not be put into regions as we do with blocks. Try mini panels to create panels for regions or itself panels.


How to use union with a query of view itself?

You can look here (https://drupal.org/node/409808) for information on creating custom sql statements in a View.


How to avoid showing duplicate content in Views?

I have came across this question in past looks like it is same as your Question: Filtered View gives duplicates

Referring that, I came to know you can use Views Distinct.

And you can follow this video tutorial: How To Remove Views Duplicates (Drupal Tutorial).


How to customize the "Remove" button in a multiple field (collection)

The solution is easy, but it took me a couple of hours wading through Drupal Core nevertheless:

foreach($form['field_termine']['und'] as $k=>$v) {
  if(!is_numeric($k)) //we only want the individual items...
    continue;
  $form['field_termine']['und'][$k]['remove_button']['#value']="Kill";
}

Note that you will get in trouble with multi-language support with this, YMMV.


files[]=lib.php fails to autoload classes of different namespace?

Yes, Drupal 7 knows nothing of namespaces unfortunately (namespaces were only introduced in PHP 5.3 and D7 is compatible with earlier versions than that).

However, life gets infinitely better with the XAutoload module, which is PSR-0 compliant an thus knows all about namespaces.

  xautoload is a comprehensive and yet highly efficient PHP class loading suite.
  Most importantly, it provides Drupal-8-style PSR-0 autoloading for Drupal 7.

The latest release is even moving towards PSR-4 which is great news.

If you install that module you can remove all of the files[] references from your info files, as long as you follow the \Drupal\my_module namespacing pattern. Even if you don't, XAutoload has hooks to let you define your own patterns.


How can I use different database backend for certain tables?

That's actually more than one question because the answer is different.

To use redis as the cache, you can use our port on github: https://github.com/md-systems/redis

The README isn't been fully updated yet but the quickstart part tells you how to configure it (after enabling the module):

  $settings['redis.connection']['interface'] = 'PhpRedis'; // Can be "Predis".
  $settings['redis.connection']['host']      = '1.2.3.4';  // Your Redis instance hostname.
  $settings['cache']['default'] = 'cache.backend.redis';

To use redis for the cache tags checksum service, which most cache backends use, you need to override a service, for example in sites/default/services.yml, add the following:

To use the redis cache tag checksum implementation, put this in
sites/default/services.yml or any other yml file that is loaded after
core.services.yml:

services:
  cache_tags.invalidator.checksum:
    class: Drupal\redis\Cache\RedisCacheTagsChecksum
    arguments: ['@redis.factory']
    tags:
      - { name: cache_tags_invalidator }

In the same way, you can replace any service that is defined in the core or one of the module services.yml files with a different implementation, for example some of the mongodb service implementations provided by https://www.drupal.org/project/mongodb.

In general, you don't think in terms of tables but services and API's, and you either replace them directly or by configuration he factory service (cache/key value/queue/...)


Dropdown SubMenus Based on Roles Stopped Working

just posting my solution for those who may come after.

As I stated above, I did suspect that it was something I had or had not done to cause this issue.  Knowing for certain that the only changes made were related to stylesheet updates, which I knew could not cause this problem, and loading of new modules,  I decided I would have to uninstall them one-by-one, but before doing that, I went over the modules I installed yesterday [just a note: the reason I didn't see this issue yesterday was because the correct display had been cached] and thought about the problem and which module would most relate to that problem, so I started with jquery_update. [jquery/javascript typically used for these types of effects, hover onClick, etc.]

I installed jquery_update yesterday.  I did change the admin display option to version 1.7, but I left the working option at 1.10.  I disabled the module, refreshed my page and the submenus did appear on hover.

I was going to uninstall the module completely, then decided to set the working version back to 1.8 and the dropdown on hover continued to work.

I have not had time to really look, but the original developer set up the site with an older theme and I bet there is a conflict in the version used in the theme he/she chose and the most recent version of jquery.

Hopefully this will save someone a few hours of their life.

I do still love Drupal.


Get taxonomy term field from where is attached

You can implement hook_views_query_alter()

In your view create a filter (not exposed) to field_category_user, with default value -1. If field_category_user is not aviable you need create a realation to taxonomy.
Create a hook_views_query_alter() in file [module_name].views_execution.inc with some like this:

// Implements hook_views_query_alter().

function [module_name]_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
$id = $view->id();

switch ($id) {
    case '[your_view_id]':
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $field_category_user = !$user->field_category_user->isEmpty() ? $user->field_category_user->value : null;

        if(!$field_category_user){
            return;
        }

        //Set field_category_user id to where condition
        foreach ($query->where as $key => $item) {
            foreach($item['conditions'] as $items){
                if ($items['field'] == 'field_category_user') { //Verify if field_category_user is the id of filter
                    $query->where[$key]['conditions'][0]['value'] = $field_category_user->id();
                }
            }
        }
    break;
}}


Is there a module for limiting CCK select list options per role?

You dont need a module, this is in core.

  $values = array(1|one, 2|two, 3|three);

  global $user;

  // Check to see if $user has the administrator role.
  if (in_array('administrator', array_values($user->roles))) {
    $values[] = 'special|special';
  }
  return $values;


How do you exclude 'drush' & 'drupal console' requirements from a drupal-composer/drupal-project install?

You can remove these after the fact:

composer remove drush/drush
composer remove drupal/console

However, it is recommended that you should use local installs of Drush and Drupal Console when using Drupal 8. If you use global versions of these tools, then you run the risk of running into dependency hell - incompatibilities between requirements of Drush or Drupal Console that do not align with what is used in Drupal 8.  When you use a global cli tool to bootstrap Drupal 8, then the cli tool will load two autoloaders.  If the same library exists in both autoloaders at different versions -- even just a "dot release" difference -- then you could get into a situation where every command aborts with an unrecoverable error.

If you only maintain a single version of Drupal 8 on your system, and carefully keep the versions of Drush and Drupal Console in alignment with that, then it will typically work, so you may remove the local version if you wish. The diagnostic efforts required when something goes wrong is quite extensive, so be cautious if you make this choice.


Why is the drupal.org site not using the more recent Drupal version?

Drupal.org is huge website the migration can take some time. The migration from Drupal 6 to Drupal 7 was finally done 2 years ago and it took forever. Moving forward to Drupal 8 is going to take a lot time. I do not see that happening like in 3 to 4 years.

Moving to Drupal 8 is not a higher priority right now for Drupal.org, compare to adding new features and improving the current website.

Drupal.com is a smaller website is been running Drupal 8 since Beta.


How do I get a custom script to run when using hook_cron in my custom module?

Welcome to drupal! One of the first things that will learn is that Drupal keeps an internal cache of all hooks implemented on the site. Just because you implement hook_cron() in your custom module, and then run cron, does not mean it will work.

Steps I would suggest to help fix

Install drush (this is Drupal's Swiss Army knife)
run drush cc all
run drush cron

Hopefully it will all be resolved

To check if your module is installed and enabled correctly you can

drush pml | grep get_weather (or alternatively look at the modules list in the UI)

Or to check if there is something wrong with your function update_weather();, you can run it in the context of drupal (i.e. alter a full drupal bootstrap with all modules loaded)

drush php-eval "print update_weather();" - you can also place additional logging or printing in your function to see what is going on.

Of course, don't forget to define all you functions that you want to execute in the .module file, as every enabled module, has it's .module file included on every request. On a side note, why don't you do away with calling another function from hook cron?

function get_weather_cron() { update_weather(); }

Simply use something similar to the following one.

function get_weather_cron() {
  // more actual weather getting code here
  variable_set('get_weather_temp', 23);
}

It should be easier to read for the next person too.


You can try using hook_node_view for doing this.
What it does is:

  Act on a node that is being assembled before rendering.

Here is an idea to try out:

/**
 * Implements hook_node_view
 */
function yourmodule_node_view ($node, $view_mode, $langcode) {

  // use a one-timer boolean for this action
  if(user_is_logged_in() && !isset($_SESSION['autoflagging_once']))
  {
    $_SESSION['autoflagging_once'] = true;
    $flag = flag_get_flag('wishlist');
    $flag->flag('flag', $node->nid, user_load($uid), TRUE);
  }

}

Good luck!


How to access webform field labels in a twig template?

Your last comment:

  Well that isn't very intuitive. It would be nice to just access
  everything directly in the twig template.

OK, then try different templates:

When the form theme wrapper is executed the inside of the wrapper is already rendered in {{ children }}. Don't try to render the form again, use this template only for the form tag and the outside container:

webform--contact.html.twig

   <form{{ attributes }}>
   {{ title_prefix }}
   {{ children }}
   {{ title_suffix }}
   </form>

Use for the inside of the form the #theme template itself:

webform-submission-form--contact.html.twig

        {{ form.name }}
        {{ form.email }}
        {{ form.subject }}

        {{ form|without('name', 'email', 'subject') }}

Finally you can theme the form element in form-element--webform-email.html.twig


How to display, search, and edit form submissions from a table with WebForm?

No, it would not be better to hand-code everything in PHP.  However, if you need heavy customization of the display of data the Webform module is probably the wrong approach.  Webform is good at getting data in but the options for getting data out are somewhat limited.

Instead, I would make a custom content type and use Views to handle the display.  To do so, navigate to /admin/structure/types/add and call it something like "People."  Once you perform the basic configuration and click save, you will be taken to the Content types administration page; click manage fields for the content type you just created.

Here, you should be able to add the same kinds of fields that you added in Webform.  This interface is not quite as clean as Webform's but it will allow you full flexibility with Views.

Once you have configured the fields as you like, go to the permissions page (/admin/people/permissions/roles) and make sure only the admin role has access to create and edit content of that content type.

Then, configure your view(s).  Basically, you'll want a view of node content of the content type you just created.  Add the fields you want to display under Fields.  To get search filters, add Filters and check Expose this filter to users.  When you set up the view(s), make sure to set the permissions using the Views edit interface so that only the admin role can access the views.

This is a very rough overview but hopefully it can get you started in a productive direction.


URL Link to Calendar Month view from Existing View

I was able to resolve this. I was trying to redirect to a second calendar from the global header text of another calendar.  I took a closer look at the second calendar and noticed that it did not have a default date in the contextual filter.  It may have gotten deleted after the fact.  I deleted the second calendar view and recreated it according to required specifications. I then edited the first calendar's global header text to use "<a href=>" and it successfully redirected to the second calendar.


Is it possible to retrieve partial forms?

This is how I might end up doing it:

When a JavaScript callback is triggered by a user editing the body field (this can be done via the #ajax property), clone current node found on form_state.
Create a render array for the whole node by using FAPI's drupal_build_form($form_id, $form_state).
Extract the body field from the render array.
Render the body field.
Return HTML to the front-end (JavaScript) so it can be placed on a preview DIV.


Have you checked the image preset is created fine after applying the resize/crop function on
admin>config>media>image-styles

Just check the thumbnail(right one) is created fine by clicking on it.

Now when we add any image field in any view, make sure to use this style for display of this field

Please check with these points.
And it works with Global text fields also.


Out of the several possible ways, what is the best practice for getting a field value for an entity?

There's likely no fast rule-of-thumb here because you're describing a few different things that will greatly depend on context (what entity, what fields?).

First, let's disregard ::getName(); it's a Taxonomy specific-wrapper around ::label() (whatever the entity has defined as its readable label in the entity definition it will return it). There's no such things a multiple labels so let's get to the main question being asked here: best practice on pulling field values.

It really depends on what you're trying to do.

If you look into ::get() method on the entity, you'll see its basically pulling data out of the internal $fields property which is is an array of objects that implement FieldItemListInterface. Classes that implement the interface supply the various get(), first(), getValue() methods that you can use when you're dealing with fields that may have one, none, or many values. They do extra overhead of checking for the existence of data or making sure it exists.

If you know for sure the data exists in your class you can skip the chaining of methods/properties and just get to the directly (e.g. $node->title->value), if not, these methods exists when you're dealing with uncertain structure in your entity/fields. Whatever the case, it depends on the specific entity class and the specific implementation of FieldItemListInterface to really decide what is best.


What does 'op' exactly mean in an submit button?

I'm pretty sure it's shorthand for the word operation.

It doesn't 'do' anything as such, it's the name assigned to all submit inputs so that the form processor can identify which button has been pressed (and perhaps fire off different submit handlers based on that).

And it looks like it's gone in Drupal 8 (in favour of $form_state['triggering_element']), so enjoy it while you can :)


If you mean literally only show that level, you can do this with Menu Block module using the Make the starting level follow the active menu item option.

If you mean that only that level should be expanded, you can do it like this: go to edit your Taxonomy Menu vocabulary. Under Taxonomy menu -> Structure options, uncheck Auto expand menu items.

But I'm not sure if Taxonomy Menu can be used with Menu Block like this.


How to do something BEFORE a view is updated via ajax submit button?

You have to capture the mousedown event on the submit / apply button, prevent submission using e.preventDefault(), validate and if everything is fine submit the form using $('#form-id').submit()

Update:

Here is a fully tested and working code:

(function ($) {
    Drupal.behaviors.ValidateAjaxForm = {
        attach : function (context, settings) {

            var $form = $("form#views-exposed-form-list", context); // ajax form selector, or better specify by class name
            var $submitButton = $('#edit-submit-list', $form); // ajax submit button selector, or better specify by class name

            // Use off to remove any existing submit handler
            $form
            .off('submit')
            .on('submit', function (e) {
                e.preventDefault();
                var $form = $(this);

                var valid = false;

                // Run some validation on $form object.
                // check conditions here and if all is fine declare valid = true

                // If vaild, trigger event on button
                if (valid) {
                    $form[0].submit();
                }

            });
        }
    };
}
    (jQuery));


How can I output a text string when my dynamically built form is empty?

I don't know what's the code before/after and exact context in which you are using it., but this could work for you:

if(empty($options)) {
  $form['empty']['#markup'] = t('None');
}
else {
  // Form defintion.
  $form['posts'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Member responses to:'),
      '#options' => $options['post'],
  );
  $form['terms'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Posts tagged with:'),
      '#options' => $options['term'],
  );
  $form['groups'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Group posts for:'),
      '#options' => $options['group'],
  );
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Remove'),
  );
}
return $form;


How to let views's sort criteria random equally

If you enable core Statistics module, you get some more filters in views:

Content statistics: Most recent view
Content statistics: Total views
Content statistics: Views today

You can select one of them, and sort ascending. So that it will always show the least recent viewed node, or least viewed node in all times, or least viewed node today, respectively which filter you've chosen.


Enable the Use Ajax option under the Other Tab..


How to use PHP Mail function or sendmail to send and/or receive emails from my live site

Based on the comments above:

Since your server does not permit direct SMTP communication, and since SMTP Authentication Support specifically overrides the default behaviour "This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server."

I would suggest disabling the two modules, SMTP Authentication support and PHPMailer, and use the default drupal mailer which by default uses php mail() as permitted by the server.


If you're really trying to restrict the character count at the point of entry you need to set the field in your form to have a #maxlength in your form definition.


How do I get the username from the user ID?

You can use user_load or \Drupal\user\Entity\User::load to do this. Below code will provide the solution

 public function content() {
     $account = \Drupal\user\Entity\User::load('uid'); // pass your uid
     $name = $account->getUsername();
     drupal_set_message($name);
 }

$name gives the username of the user.


Generating an absolute node URL from its node id

Drupal 8
$nid = 5;
// Or $nid = $node->id();
$node_title = 'Node Title'
// Or $node->getTitle();

Create absolute URL:
// Will output http://example.com/path-to-my-node
$options = ['absolute' => TRUE];
$url_object = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ url_object }}.
// In PHP (outside a render array) use $url_object->toString().

Create absolute link object (and inner span):
// Will output Node Title
$options = ['absolute' => TRUE, 'attributes' => ['class' => 'this-class']];
$node_title = \Drupal\Core\Render\Markup::create('' . $node_title . '');
$link_object = \Drupal\Core\Link::createFromRoute($node_title, 'entity.node.canonical', ['node' => $nid], $options);
// In Twig use {{ link_object }}.
// In PHP (outside a render array) use $link_object->toString().


Before blocks get to the theme layer, they can be altered. Blocks are represented as "render arrays", which means you can manipulate them with the Render API.

You can use hook_block_view_alter() to change the contents of a block.

Any module or theme can implement this hook. For example, a theme named YOURTHEME would have code like this:

function YOURTHEME_block_view_alter(&$data, $block) {
  // Remove the contextual links on all blocks that provide them.
  if (is_array($data['content']) && isset($data['content']['#contextual_links'])) {
    unset($data['content']['#contextual_links']);
  }
  // Add a theme wrapper function defined by the current module to all blocks
  // provided by the "somemodule" module.
  if (is_array($data['content']) && $block->module == 'somemodule') {
    $data['content']['#theme_wrappers'][] = 'mymodule_special_block';
  }
}

Or, if you know in advance the module and delta you'd like to alter, you can use hook_block_view_MODULE_DELTA_alter() like this:

function YOURTHEME_block_view_MODULE_DELTA_alter(&$data, $block) {
  // This code will only run for a specific block. For example, if MODULE_DELTA
  // in the function definition above is set to "mymodule_somedelta", the code
  // will only run on the "somedelta" block provided by the "mymodule" module.

  // Change the title of the "somedelta" block provided by the "mymodule"
  // module.
  $data['subject'] = t('New title of the block');
}


dump() not working in Drupal 8 (blank page, debbugging is enabled)

I agree with the comment left for the question: It seems you have an out of memory issue. Check the error log for the server.

I had the same problem with dump() and kint() in an implementation of template_preprocess_views_view_field(), while trying to output the content of a row, on a clean and fresh Drupal 8 installation.
I found a workaround for kint(), which seems to temporary fix the memory issue. Add the following settings in the config.default.php file for the Kint module.

/** @var int max array/object levels to go deep, if zero no limits are applied */
$_kintSettings['maxLevels'] = 4;

Take it as a hint: Print a specific variable, not the whole array of variables.


subject and body of mail messages empty using drupal 8 mail api - hook_mail

Ok, I found the problem.  You're gonna laugh!

My code for hook_mail was within the code block for the function above it!  D'oh!  All good now. Sorry for the false alarm.


Creating a new Form element in ajaxcallback function not affecting form state

You cannot add fields in ajax callback functions - assuming that level2SelectedCallback() is your ajax callback (you named it something different in your form element defintion).

All form elements need to be added in the form definition. The ajax callback is only used for determining which elements need to be inserted into the page when the AJAX is returned.


I'm not quite sure why this started working, but all went right with the world when I added the "Book page: Edit own content" and "Book page: Edit any content" permissions for the "book author" role.

Two odd things with this though:

I'm sure I tried this at least once before earlier today
I immediately disabled both permissions again to see what would happen, and nothing did, i.e. the book author role is still able to create and edit draft Book page content... which is good, but weird


How to use a tpl.php file for a theme function

Create a template file lt-unified-login.tpl.php in your theme directory and put this function inside template.php to override theme_lt_unified_login_page & return the HTML output of lt-unified-login.tpl.php.

function YOURTHEME_lt_unified_login_page($variables) {
  $template = drupal_get_path('theme', 'YOURTHEME').'/lt-unified-login.tpl.php';
  return theme_render_template($template, $variables);
}


Placing exposed filters (with BEF) in various Panel regions

did you finally find a solution for this? You could use the module MEFIBS which allows you to put your filters (and sort) into different blocks.

Anyway, MEFIBS didn't work for me because of the fact that all blocks get seperate submit button. So it would be interesting for me to hear how you finally ended up with this.

Best,
Thomas


Did you happen to be using one of the latest 6.x-2.x-dev versions of imagecache?

I spent an entire day trying to figure this one out (because unfortunately this was the only relevant page that came up in a google search). Once I finally decided to try the 6.x-2.0-rc1 version, everything seemed to work fine.


You could use the Group module. All you'd have to do is:

Create 1 group (pick your name) in 1 group type (pick your name).
Give access to all users to that group.
Use the group permissions to indicate you do NOT want to give anonymous users access to the content type you have in mind.

Done.


You can use the Redirect module for this: https://www.drupal.org/project/redirect


Statistics module has less functionality

Based on Drupal 8.3.1, it appears that documentation is incorrect. Well, they seem to primarily relate to Drupal 7.

The statistics module doesn't appear to store IP addresses or user names.

The module does provide a popular content block, which is based on view statistics.

The module also provides views integration, so you can create reports that have statistics data using views, but it doesn't add any default views similar to the reports mentioned in those docs.


TWIG if/else to filter through templates

If not rendered at all, for sure, Twig not found your template file.

There is a var that store the base dir of your theme, just use it to define where is your template file.

Twig file:

{% include "#{directory}/templates/node/node--customer--featured-full.hmtl.twig" %}


how to create node for ecommerce display page?

There is a module Auto Product Display

This module will do automatically create product display for you.

  This module is created in order to solve that problem. This module can
  simplify the Product Display creation process by providing option the
  create it at the same time with Product creation.

  Features

  Provide the Product Display creation form along with the Product
  creation form. User can fill that form to create Product Display at
  the same time with Product creation.
  That form, which used to create Product Display, will be the same as
  the form when user try to create Product Display manually. So, If
  you have additional fields in your Product Display node type, those
  fields will also appear in the form.
  If the product is referenced by only one Product Display, the
  Product Display content is displayed directly to the form, so it
  will be automatically updated when you save the product.
  If the product is referenced by more than one Product Display, the
  referencing Product Displays will be displayed in list, so you can
  also update the Product Display by clicking the link from that list
  first.

If you want to create manually, this will guide you

"Product Display" is the default content type that Commerce Kickstart 1.x creates and it has a product reference field. Technically, any entity that has a product reference field could be considered a product display. Nodes are the obvious product display entity type, and they're privileged because they're the default and standard entity type to use for the front-end display of content. But you could use taxonomy vocabularies, or even users as product displays.

Taken reference from here

Basically you need to add product reference field field for your node.


How to grant access to a user to all content created by certain users?

Sorry telling you that as far as I know there is nothing like this out of box.
Maybe if you mention the requirement we will be able to help you.
For now don't think about users and think about roles. if you want to make it more flexible I suggest using workbench access so the created content will have a section (Taxonomy term) and the section will be accesed by user A and B only.
Hope that help


if function getValue() on null return nothing

You can check if a field is empty or not before asking for getValue() with:

if (!$entity->get('field_name')->isEmpty()) {
  $value = $entity->get('field_name')->getValue();
}


I managed to fix this issue with a combinations of a relationship and a custom formatter.

First, in a (User) view, I created a contextual filter with User: Uid. Of course, no contextual filter will be given at the page, so I provided the default value User ID from logged in user.

Then, I created two relationships. The first one User: Profileand the second one Profile: [your custom name]. The second relationship is created with the first one as relationship.

Next, in my Fields section of my view, I added a Profile field and gave it a custom formatter. By using this custom formatter, I was able to display all the needed data.

If someone is interested in more code, please let me know!


Can't install modules from UI when site placed in subdirectory

You have to uncomment this line.

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal

Another option is to update module using drush.

drush up


Can I use Views query in my custom code or not?

Long story shory, if you run the same query that the views module runs, you will get the same result.

If you are getting a different result this means that you

Don't run the same query (where do you get the views query from)
Don't provide the same dynamic variables if any is used

You should also note that Views has it's own magic variables in views, that only works in views, like ****CURRENT_LANGUAGE**** which maps to the current language.

You should also note that views does a lot of work in the theme layer to output data. Getting the same data from SQL doesn't mean that the actual output will be the same.


How to change upload destination from public to private when there are uploaded files in database?

$dest = 'private://';
$file = file_move($file, $dest)

Change individual file from public to private and vice-versa


SQL command to remove hypens from data value

To ensure caches are invalidated properly, and contrib modules get the chance to act on data changes, you should always make this kind of global change with the API.

If you've checked, and you're sure you won't suffer any ill-effects by not using the API, then:

UPDATE commerce_product SET sku = REPLACE('-', ' ', sku)
UPDATE commerce_product SET title = REPLACE('-', ' ', title)

And the same for the commerce_product_revision table. You may also need to run something like

UPDATE node SET title = REPLACE('-', ' ', title) WHERE type = 'product_display_type'

And the same for node_revision depending on how you have node revisions and product displays set up.

But direct DB access is not the recommended way to perform a task like this. Take a backup before trying anything just in case


In Drupal 7 cron is run by Drupal by default.

You can configure it at: admin/config/system/cron

It is preferable to disable that cron and run it automatically from the server in some way.
That method is really only preferable if for any reason you have no other choice.

That said, you really should be automatically running cron regularly.
Not necessarily every hour but at least once a day.


Custom content types and fields: how do I set it up properly?

The first step is to create the content type and fields with the built-in UI of Drupal core. There are then several ways to export the configurations into code, but the simplest is probably Features, which will export a fully-functional module for you including all fields and content types you select.

To get your content into nodes of your content type, I'd suggest you create one node with the UI, use devel to look at the structure, then create the same object structure in code, which would look something like this:

$node = new StdClass;
$node->type = 'content_type;
$node->field_something = array(
  'und' => array(
    array(
      'value' => 'some value',
    ),
  ),
);
node_save($node);

Drupal's search defaults to searching nodes of all types, so that part should just work. Same with theming. You can use permissions (also exportable via Features) to remove the content type from the "Add content" list.