How to get a form field to allow additional values?

If you want to allow a field to get multiple values.you need to edit the field and allow the numbers of values to unlimited.
Suppose you want to allow multiple images to upload in Article content type.

1)Go to Administration » Structure » Content types » Article » Manage fields
2)Edit the field and under field settings,choose the values to unlimited or number of values you want a user can upload.
See the similar in screenshot url below.
https://www.evernote.com/shard/s496/sh/15655bf1-104c-40ed-ab26-bc6da6ebe7a5/bd1bce151edec9956746845474f3ba95


Yes, Views Column Class is the best way to do it in my experience.

All you need to do is set the row class to an alpha grid class, and the number of columns for the display mode you're using, e.g.

and the module will take care of adding the alpha/omega classes to the appropriate elements on your page, giving you properly responsive views for very little work.

It's worth remembering that a 'row' in the context of a floated list is each individual item, not a row of x number of elements. So when you apply grid-4 etc, it's applied to each individual element, not the whole row. It can be confusing at first.


Filter a view by a field on a referenced entity

I figured it out. Configure in this sequence:

Show: "content" of type "page"
Relationships: "Content referenced from art_ref"
Use Aggregation: Yes
Add filter criteria: fishy, Aggregation: "group results together", relationship: "art_ref:content", operator: "is equal to" "1"


How to use drush with a specific PHP Instance

Drush is just a PHP script at heart so all you need is this:

/path/to/my/php /path/to/my/drush  ...


Default sort order on the other table columns

No, it isn't possible at this point.

There is an issue for that, I suggest you try that out and report back so that it can be commited soon: http://drupal.org/node/109493


drupal 7 workbench: Can I limit different users/roles within a particular section via taxonomy?

You use the submodule of Workbench, called Workbench Access to limit users to a "sub section" of the content based on Taxonomy or Menu path.

  Workbench Access creates editorial access controls based on
  hierarchies. It is an extensible system that supports structures
  created by other Drupal modules.

  When creating and editing content, users will be asked to place the
  content in an editorial section. Other users within that section or
  its parents will be able to edit the content. A user may be granted
  editorial rights to a section specific to his account or by his
  assigned role on the site.

There is a great documentation page and associated web video for Workbench Access on configuration within the project page.


How to link price to the product display?

You normally don't link all fields to your product display, but you reference the product from your product display using the commerce_product_reference that ships in the Drupal Commerce package.

You can create a content type and a product type. Then on the content type add a product reference field. Now the node and the product are linked and all fields (including price) and other properties are accessible for both entities in Views, Rules, etc.

Optionally you can enhance the experience using Inline Entity Form as a widget for the commerce product field. That allows you to fill all the product properties (such as price) when creating a node.


how to delete modules which are alredy uninstall?

Unless you disable and uninstall the custom modules you should not remove that custom module . This can cause performance and other issues. Get back those modules from backup. Then disable and uninstall them. Then you can remove the module.

There is even a module in Drupal 7 which will tell you deleted but not disabled modules which I'm not able to remember.


How to get a custom field label in a specific language?

Turns out that using t(), doesn't work for translated field labels.

To get the translated field label text (in the current language), just use the i18n_field_translate_property function

  $field_instance = field_info_instance('node', 'field_application_area', 'products');
  $label = i18n_field_translate_property($field_instance, 'label');

Or, for a specific language :

  $label = i18n_field_translate_property($field_instance, 'label', 'fr');

Found on this related answer.


When should one use #value_callback and when #element_validate?

#element_validate:

  A list of custom validation functions. The validation functions must use form_error() or form_set_error() to flag the element as having an error if the validation fails.

Use this when you want to validate the input into your custom element, and inform users of any failures. Code example of such a validation function:

function myelement_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

#value_callback:

  Specifies the name of a custom value function that implements how user input is mapped to an element's #value property.

Use this when you simply want to change the state of something in your element based on contextual information. Don't use this method if that state-change has the potential to cause an error that the user should be made aware of; use a validate function in that instance instead.

Code example:

function file_field_widget_value($element, $input = FALSE, $form_state) {
  if ($input) {
    // Checkboxes lose their value when empty.
    // If the display field is present make sure its unchecked value is saved.
    $field = field_widget_field($element, $form_state);
    if (empty($input['display'])) {
      $input['display'] = $field['settings']['display_field'] ? 0 : 1;
    }
  }
}

So to your question:

  when should you go trough the individual inputs and create the SQL connection string from them?

If this is a process that needs to be validated, then in a validation function. If it's something that just needs to be done, regardless of the input, then it goes in the value callback function.

Reading through the code in a bunch of the core value callbacks should clear up the confusion even better:

form_type_select_value()
form_type_textfield_value()
form_type_checkbox_value()

Notice that nothing in any of those functions relates to validation of the input.

Also see form_builder(), where the callback is actually used.


How can I implement AJAX form submission?

When working with ajax in forms you have to keep in mind the following things:

know if you are rebuilding the whole form or only part of it and wrap the form accordingly with div element that has ID attribute that you will use in the #ajax definition on the triggering element as 'wrapper'. Use #prefix and #suffix attributes for this($form['#prefix'] = '
'; $form['#suffix'] = '
';). Also keep in mind that if you have custom template for your form to NOT render the prefix and suffix in this case({{ form|without('#prefix', '#suffix') }}) otherwise they will get rendered twice - by your template and also by the form theme wrapper. You cannot prevent this by setting #theme_wrappers to empty array since the form template contains the actual form html element.
in your ajax submit handler, return the whole form or portion of it that you've wrapped and want to rebuild(return $form or return $form['myelement']). You can additionally use ajax commands instead of just returning the form structure but that is more advanced stuff.
store every value in form state's storage until you submit the form. Do this in the submit handler($form_state->set('somevalue', $form_state->getValue('somevalue'))) and always call $form_state->setRebuild() if you are not doing the final form submission. I prefer having custom submit handlers but having more logic in the primary submit handler is totally ok as well.
always use #name attribute on the button that is doing the submission and if you have only single form submit handler use $for_state->getTriggeringElement()['#name'] to detect which element has submitted the form.
if you are using 'trigger_as' in the #ajax definition, in case you want to submit the form with select element for example, always use the same #ajax definition like you do on the button. In my experience it is required - although not stated in the documentation.
using #limit_validation_errors can get very tricky sometimes and to figure out why the form is not working can take quite some time, so use it carefully(this is good for isolating form errors only on the element(s) that you are actually rebuilding so that your code does not influence other parts of the form).
always use buttons to submit the form and if you want to have something fancy, like select being the triggering element, use the 'trigger_as' option of the #ajax configuration and hide the real button with 'js-hide' class for good UI.
in the form definition, get the default values from the form state's storage if they exist or assign them into the storage if they don't. Otherwise the form won't work properly.
don't use $this or anything else that you don't have access to externally, otherwise it will break the ajax. always use static ajax handlers.
when finally submitting the form, depending on the fact that you (don't)have  a custom form submission handler for the ajax, disable the form rebuilding by calling $form_state->setRebuild(FALSE).
you can use the :: shorthand calls in the ajax submit element($element['#ajax']['callback'] = '::ajaxFormRebuild'; and $element['#submit'] = [['::ajaxFormSubmitHandler'];).
the ajax callback is purely to return the rebuilt form or ajax commands. Never return altered form(ie. do not alter the form array in this callback).


Views: Change path and redirect old to new path?

Use this Path redirect module to redirect path.

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.


Is there a way to make a body field automatically become the first comment on a node?

Without coding, I'd go for the module Rules :
You can create action that are triggered after certain events, under certain conditions.
In your case you can try to create a rule like this one :

Event : When a Node is Created
Conditions : You probably want to filter the node type maybe ?
Action : Create an entity

Select Comment as your entity type
Node referencing the comment : Use the available token "node" (the newly created node that triggered your rule)
Comment body : Use the available token node:body

And you're done .. 0 code, 1 module, 2 mins to setup your rule :-)


Drupal 7 - How to display the TID of a term reference field in a content type?

The best way to do this is to make a new field formatter.  You need to implement two hooks, hook_field_formatter_info() and hook_field_formatter_view().  The info hook tells Drupal about your formatter and the view does the heavy lifting.  You can then use this on the Manage Display for the field in your content type.

The easiest way to do this is to clone them from taxnomy.module, and modify.  Something like this would be a start

/**
 * Implements hook_field_formatter_info().
 */
function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_term_name_with_tid' => array(
      'label' => t('Term name + tid'),
      'field types' => array('taxonomy_term_reference'),
    ),
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'MYMODULE_term_name_with_tid':
      foreach ($items as $delta => $item) {
        $name = ($item['tid'] != 'autocreate' ? $item['taxonomy_term']->name  : $item['name']);
        $element[$delta] = array(
          '#markup' => check_plain($name) . '(' . $item['tid'] . ')',
        );
      }
      break;
  }

  return $element;
}


How to make author name hyperlinked to its profile in node template

Normally {{ author_name }} already comes as renderable markup containing the linked author name. But there's also {{ node.getOwnerId }} (the author's user ID) and {{ node.getOwner.label }} (the author's user name) you could simply use to build the link yourself.

    {{ node.getOwner.label }}

Note you can easily inspect what variables are available for a template by installing the Devel sub-module Kint and then in your template print {{ kint() }}, flush cache and reload. You now will get all available variables pretty-printed to easily find out which ones you could use to solve your problem.

To make that snippet a little bit more sustainable use the path() function to build the link target. By that also path aliases (built with Pathauto for example) will be taken into account.

    {{ node.getOwner.label }}


I have just created a views page with tabs. Following are the instructions.
Add a views display of type page

Set its path to "/test"
Then its menu option: Select "Default menu tab" and on next screen    select "Already exist" under the "parent menu item".
Then adds another page display
set its path to "test/tab1"
and in its menu option: select "Menu tab" and save.

Visit the "/test" page and both tabs appear.
Hope it may help you.


How to remove tag from SelectQuery object

I still can not find a way to remove a tag from query, but I found solution for my case of count query. The idea is to use another tag to stop endless recursion:

function mymodule_query_mytag_alter(QueryAlterableInterface $query) {

  if ($query->hasTag('counted')) {
    return;
  }

  // Prepare count query
  $countQuery = $query->countQuery();
  $countQuery->addTag('counted'); // Abort hook recursion

  $tables =& $countQuery->getTables(); // Query may have sub-queries

  foreach ($tables as &$table) { // Tag all subqueries
    if ($table['table'] instanceof SelectQueryInterface) {
      $table['table']->addTag('counted'); // Abort hook recursion
    }
  }

  $total = $countQuery->execute()->fetchField(); // execute() will initiate recursion!

 // Rest of processing

}


Didn't we used to be able to type "entity:node/####" in a typeahead field?

Ooooooooookay.

The entity:node/[node_id_number] only works in a Drupal link field. It does NOT work in a Drupal entity reference field.

Although both of those fields feature the typeahead function and link to other nodes, you cannot use  entity:node/[node_id_number] to fill in an entity reference typeahead field.

Thanks @Clive for making me clarify my field types and start down the path to seeing my wrong assumption.


How to resolve this fatal error '2006 MYSQL server has gone away'?

A few minutes to send 40 emails indicates that this cron job is computationally expensive. You are probably hitting against MySQL's wait_timeout limit.

I wouldn't necessarily suggest changing your MySQL configuration. Drupal's cron runs aren't meant to take more than a few minutes at a time. Instead, this may be better suited to a cron queue.

In a cron queue, each individual email to send would be a job in this particular queue. During each cron run, as many of those jobs in each queue are processed until some set time limit has passed, and the remaining jobs are deferred for the next cron run.


Get a list of all entity reference fields that reference specific entity types

Answering this myself based on the investigation I did using field_entity_bundle_delete for inspiration.  Would be great if someone could take this code and improve it.

  /**
   * Helper method gets a list of all entity reference fields that reference
   * the specified entity type.
   *
   * @param $entity_type string
   * @param $entity_bundle string (optional)
   * @return a filtered field map of entity reference fields.
   */
  protected function getEntityReferenceFieldsByEntityType($entity_type, $entity_bundle = '') {

    // Gather a list of all entity reference fields.
    $map = \Drupal::entityManager()->getFieldMapByFieldType('entity_reference');
    $ids = [];
    foreach ($map as $type => $info) {
      foreach ($info as $name => $data) {
        foreach ($data['bundles'] as $bundle_name) {
          $ids[] = "$type.$bundle_name.$name";
        }
      }
    }

    // Determine if any of the reference fields reference a specific entity type
    // and bundle type.
    foreach (FieldConfig::loadMultiple($ids) as $field_config) {
      $field_name = $field_config->getName();
      $target_type = $field_config->getSetting('target_type');
      if (!empty($target_type) && $target_type == $entity_type)) {
        if (!empty($entity_bundle) {
          $handler_settings = $field_config->getSetting('handler_settings');
          if (isset($handler_settings['target_bundles'][$entity_bundle])) {
            $filtered_map[$entity_type][$field_name] = $map[$entity_type][$field_name];
          }
        } else {
          $filtered_map[$entity_type][$field_name] = $map[$entity_type][$field_name];
        }
      }
    }

    return $filtered_map;
  }


In the end I did all of this with jQuery alone.

I created a block that contains the

All (23)
Alpha (10)
Bravo (4)
Charlie (0)
Delta (1)
Echo (8)

options, I add the number with jQuery by counting the grouped results, and by JQuery again, I hide the appropriate grouping blocks. So the Facet API block was of no use to me and neither was the View's exposed filter.


Page rendered correctly but display errors

First of all, the 'und' is not prefered, you should use LANGUAGE_NONE constant instead. This is not part of the sollution, but part of the Drupal coding standards.

This is a tricky one. The function render() expects a string, but you give a part of an object with some deeper array keys.
The simplest way to get around the strict warning is to use the following code:

<?php $uri = file_create_url($node->field_header_image[LANGUAGE_NONE][0]['uri']); ?>
<div id="hero-container" class="hero-container" style="background:linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url('<?php print render($uri); ?>');">


have you try any alter functions to implement ?
if you can try with alter then try #states in hook_form_alter() to hide field, if primary field default value is empty/null.
here is e.g
/**
 * @param type $form
 * @param type $form_state
 * @param type $form_id
 * Implements hook_form_alter()
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'form_id') {
    // Hide secondary field.
    if (isset($form['secondary_field'])) {
      $form['secondary_field']['#states'] = [
        'visible' => array(
          'input[name="primary_field"]' => array('!value' => ''),
        ),
      ];
    }
  }
}

'input[name="primary_field"]' => array('!value' => ''), change this as per need i.e if its select list then 'select[name="primary_field"]' => array('!value' => ''), etc.
hope this will solve your issue.


How do I disable the cache clear on comment form submission?

Should be reasonably straight forward with a form alter (mileage may vary slightly here but this is the general idea):

function MYMODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $key = array_search('comment_form_submit', $form['#submit']);
  if ($key !== FALSE) {
    $form['#submit'][$key] = 'MYMODULE_comment_form_submit';
  }
}

function MYMODULE_comment_form_submit($form, &$form_state) {
  // Copy code from comment_form() here, remove what you don't need.
}


You can do this using Views Argument Substitutions and I'm just assuming the Title field here. It should work for any text field.

Add some Global: Null contextual filters to take each raw component of the url. (Provide default: Raw Value from URL 2 / 3 / 4 etc.
In your views filters, add Title: Contains: ***!1***. Repeat this for however many url components there are. ***!2*** ***!3*** etc. for each Title filter.
Use AND / OR in between your Title filters section to control your final result.


Unable to install lullabot/amp and sensiolabs/security-checker

Try these commands, in this order:
1. Go to the docroot and type: drush composer-json-rebuild
2. In the same place: drush composer-manager install
3. If this doesn't work, go to sites/default/files/composer and type: composer install
4. In the end you can run: drush composer-manager update


There's an infinite loop in your code...

The function zillow_api_info() returns a call to itself, which will result in an infinite recursion from which PHP can't escape. As you're calling this function during the call to drupal_set_message() I'd guess that's why you're getting the timeout.

FYI You're not passing the @zipcode replacement to the t() function, it shouldn't cause an error but it might be a bug :)


It sounds like you are using Menu block module, and you would have already successfully placed the menu-tree in your region. If your desire is to access raw menu data from a menu block, just use TEMPLATE_preprocess_block(&$variables).

$variables['content'] is rendered.
$variables['elements']['#content'] is raw.


The module that creates a URL like localhost:8888/mysite/?q=user/bwadmin (or localhost:8888/mysite/user/bwadmin, with clean URLs enabled) is the Pathauto module, which creates path alias for user, node, and taxonomy term URLs.

Check the module settings; there is a set of options that allows replacing some specific characters that would cause some problems; one of those characters is the underscore. In your case, the module is set to strip off underscores from the path alias it generates.


Wrong User Image Display - Weird Twig Cache?

When you add data from the current user you also have to add this cache context:

$variables['#cache']['contexts'][] = 'user';

You can also add the cache dependencies of the user, file and image style. Then modifying one of these entities will be effective immediately, see https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays


How to search on date ranges using apachesolr module?

Take a look at the Lucene search syntax, for dates use a filter query like
created:[2011-10-01T23:59:59Z TO 2011-10-31T14:11:00Z]


You could create a small module that will be called through ajax:

function MYMODULE_node_menu() {
    return array(//$items
        'MYMODULE/%' => array(
            'page callback' => 'MYMODULE_display_view',
            'page arguments' => array(1),
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        )
    );
}
function MYMODULE_display_view($view_name) {
    // display your view depending on $view_name
   $view = views_get_view($view_name);
   $view->execute();
   echo $view->render();
}

Get a views html by making an ajax call using jQuery:

$(document).ready(function() {
   $.ajax('MYMODULE/YOUR_VIEW_NAME', {
           sucess:function(data) {
              // data will contain the html for your view
           }
   });
 });

You might find the following Drupal 7 Advanced Ajax helpful.


For whatever whack reason, I had to click on the file-name in the views, which was already set to "output with links", change it to without links then back and it works.

Thanks you, JimaJamma and jerdiggity; your answers made me focus on the field in the view.


Add different paragraphs block on translated nodes

That is an open issue. At the moment you can only translate the fields inside of paragraphs, not the outside structure of the paragraphs.

See this issue:

[META] Support translatable paragraph entity reference revision field


Remove dots ( ... ) from default search results descriptions ( snippet )

You use incorrect variable name.

Take a look for the search-result.html.twig template.
We have a snippet template variable.

Your code should looks like:

function theme_preprocess_search_result(&$variables) {
  $variables['snippet']['#markup'] = str_replace('…', '', $variables['snippet']['#markup']);
}

Pay attention to …, this is a special symbol, not ... (three dots).


Custom field type validation in field type definition class

Form validation checks the user input before it gets submitted. The submitted values don't necessarily go into the database, they can be used for other things. Presave can check values before they are stored in the database. The values don't need to come from a form, they can be generated by other code. So those two things are not connected.

If you want to validate a form, you have to use form validation. Presave doesn't know about forms. It is no problem to double check in presave, then you prevent wrong values to enter into the database from any code. But if you want to give the user a feedback in the form, use form validation. In presave you can only throw an exception after submit.


Even if it is the front page is located at the default mysite.com/node, there are dozen's of way of populating it in Drupal with stuff that aren't nodes.

Have you looked if blocks are used to populate the front page?  To check, navigate to Home » Administration » Structure » Blocks, and examine the configuration of the blocks that are enabled.  The RSS feed, for instance, is probably a block.  You can edit the content of blocks, or moving them to region - None - to disable.

One problem here is that we don't know whether you predecessor has done this the right way or his own way.  For all we know, he may have hacked the core or theme template directly.  Things also depends on version and theme.  You haven't told us what version of Drupal you're running or what theme the site uses.  To answer this question with more accuracy than this general answer, all this must be known by the person writing the answer.

Three things to try:

If you're using Drupal 6, navigate to Home › Administer › Site configuration › Site information.  See if there is any contents on that page that account for material on the front page.  If so, you may now edit it.
Change the site's theme.  In particular, get rid of any sub-themes and revert to the default theme for the Drupal version you're running (depends on version).  If you're already running the default, install the admin theme as default (depends on version).  If the content on the front page disappear, it's in the theme templates.  Update your question with this information, and ask how to fix it.  I (and others) will then update our answers.
Back up your configuration (Important!) Upgrade Drupal to the newest major version of the branch you're at (depends on version).  If it is already the latest major version, upgrade anyway.  If the content on the front page disappear, your predecessor has hacked the core.  Restore from backup, and hire a consultant.


Getting the id of all the elements in a form with errors

You might need to write a custom module for this:

Use hook_form_alter for the specific form and call form_get_errors.
Theme the results of form_get_erros with hook_theme to pass the results back to your theme.


Batch API on a Dreamhost dedicated server

I solved this by updating "FcgidIOTimeout" in httpd.conf. I set it to an hour.


How can I alter the list of available layouts in the Panels IPE?

I've been trying to curate the Panels IPE more to my liking, and so far, it seems like overriding the controller is a decent way to go.

Say you're wanting to do this in my_example module:

Inside your custom module, create src/Controller/CustomPanelsIPEController.php. We want to extend from panels_ipe/src/Controller/PanelsIPEPageController.php into this file, and change the namespace declaration and change the class name to match:

<?php

namespace Drupal\my_module\Controller;

use Drupal\panels_ipe\Controller\PanelsIPEPageController;

/**
 * Contains all JSON endpoints required for Panels IPE + Page Manager.
 */
class MyModuleIPEController extends PanelsIPEPageController {
...

Now, we need to have our routing subscriber tune in to panels IPE being called, and re-route it to our new method. Create src/Routing/MyExampleRoutingSubscriber.php, and add the following:

namespace Drupal\my_example\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class MyExampleRoutingSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('panels_ipe.block_plugins')) {
      $route->setDefault('_controller', '\Drupal\my_example\Controller\MyModuleIPEController:getBlockPlugins');
    }
  }
}

So now what will happen is our Panels IPE is now calling our method.

So now, we can do some more precise altering. For a simple example, when it comes to creating blocks, let's say we wanted to only give users a single module called 'awesome_blocks' for their choices when creating content.

public function getBlockPluginsData($panels_storage_type, $panels_storage_id) {
   $panels_display = $this->loadPanelsDisplay($panels_storage_type,
   $panels_storage_id);

   // Get block plugin definitions from the server.
   $definitions = $this->blockManager->getDefinitionsForContexts($panels_display->getContexts());

   // Assemble our relevant data.
   $blocks = [];
   foreach ($definitions as $plugin_id => $definition) {
     if ($definition['provider'] == "awesome_blocks") { // Added this logic
     ...

In this simple example, I've altered the logic to ONLY show blocks from the awesome_blocks module. Now of curse, I was altering the blocks, and you were asking about the layouts. The layouts can be altered the same way! Inside of the getLayoutsData() function that is in this same class, you could implement custom logic. To alter the layouts in the same way, we could add another function inside our custom Routing controller, inside the alterRoutes() method:

    if ($route = $collection->get('panels_ipe.layouts')) {
        $route->setDefault('_controller', '\Drupal\my_example\Controller\MyModuleIPEController:getLayouts');
    }

Now, just implement custom logic in the getLayouts method:

public function getLayoutsData($panels_storage_type, $panels_storage_id) {
    $panels_display = $this->loadPanelsDisplay($panels_storage_type, $panels_storage_id);

    // Get the current layout.
    $current_layout_id = $panels_display->getLayout()->getPluginId();

    // Get a list of all available layouts.
    $layouts = $this->layoutPluginManager->getDefinitions();
    $base_path = base_path();
    $data = [];
    foreach ($layouts as $id => $layout) {
        if ($layout['provider'] == 'my_layout_module') { // Added logic check here
        ...
        }

Hope this helps!


What hook do I use to add a field to a content type after it was programmatically created?

Try the hook_update_n function
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_update_N/7

You would define a hook_update_n function in your install file in which you place the functionality to add your field to your content type.
See for example:
http://cgit.drupalcode.org/entity/tree/entity.install#n35

After added this functionality run http://example.com/update.php

A second option would be to use the features module to export your content type to a feature and when you are making changes in the UI to that content type (like adding a field for example) you can export the content type again to the feature and deploy that feature to your other (live) environment and revert the feature (which will bring the new code (the newly added field) into the database.


Advantages of utilizing Entity Field query over views?

Advantages of EFQ:

It's in Core, so you don't actually depend on an extra contrib module. Sometimes Views isn't considered an option.
It's very easy to handle programmatically, while Views is kinda awkward to handle in code.
I have made no performance measurements, but based on the fact that EFQ's are simpler than Views, I believe it will often have better performance.

Advantages of Views:

You can do (almost) arbitrary joins and collect most any kind of data. EFQ finds entites and their fields, period. It's also fairly easy to expose new data to Views. There's even a module for that.
It has a UI, and is as such far more user-friendly than building everything in code.
Views can easily be cached. An EFQ needs custom logic for this.


Is it possible to do a user search by taxonomy?

Create a "User" View

Add a "Filter Criteria" with your taxonomy field

Click "Expose this filter to visitors, to allow them to change it"

Done.


Restricting access to specific nodes for specifc users?

I had to do something similar in a project last year and ended up using Taxonomy Access Control (TAC). If you make your location field a taxonomy and use the same taxonomy field on your user profile and content type, you can set perms for your curator role relative to the taxonomy term. It has to be enabled on a role by role basis so it won't impact any other roles on your site.


Got it resolved, the problem was, i was not passing the parameter comment type. Made the following changes to body parameter and it now works.

let body = [
        "entity_type": [
            [
                "value": "node"
            ]
        ],
        "entity_id": [
            [
                "target_id": self.nodeID
            ]
        ],
        "field_name": [
            [
                "value": "comment_x",  // Machine name of the field on the node
                "format": "no_html"
            ]
        ],
        "comment_body": [
            [
                "value": "How are you?"
            ]
        ],
        "comment_type": [
            [
                "target_id": "comment_x"  // Machine name of the comment bundle
            ]
        ],
        "uid": [
            [
                "target_id": self.UID
            ]
        ],
    ]


How do I remove the default 'my cms' text from my drupal 7 webpage with the bartik theme?

That My CMS text is the Site name setting value. You can change it from the setting page on /admin/config/system/site-information.


UC Orders and Webfrom Submissions in same view

check this out... I had the same issue and was able to solve it: http://archive.org/details/DisplayWebformSubmissionDataInViews


Disabling some modules installed via a feature

As far as I know, you can’t.

But, if you are 100% sure that these modules are not used by any component of your system you can do it in a hacky way. Only if you patch the feature’s .info dependencies and then revert it.

If it’s not very important to disable these modules (let’s say conflict with something?) do not do that!


How to load page content by url programmatically in custom region

You can accomplish this with the Form Block module

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for including forms on panels.

Then in blocks (/admin/structure/block), assign the Form Block to your desired region.


No content types showing under 'Add content'

I found this :
http://drupal.org/node/997444
it seems like it's a very strange behaviour.

Basically I guess Drupal looks at that specific main menu to see what types of content can be created by users, so if even if you move all the options to a different menu none will be available.

I had to re-add the add-content link to the administration menu and re-check all the submenu items, then set it to display:none; and add the 'Add content' link to the user menu again.


Display selected menu parent with children in sidebar

I get it working by using this module : Hierarchical Taxonomy Menu https://www.drupal.org/project/hierarchical_taxonomy_menu

Thanks


Restrict comments on nodes of a content type based on user role

You can perform a hook_form_alter on the comment form in a custom module. This will allow you to change the form so it checks if the current user has a premium role. If the acting user has the premium role the option to submit a comment is displayed. If they do not show a message like "only premium members can comment".

MODULENAME_form_alter(&$form, &$form_state, $form_id) {
if ( $form_id == 'comment_form') {
  global $user;
   if (!user_role('Premium'){
    // Form alter here to unset comment form and show "only premium members can comment"
    unset($form['author']);
    unset($form['subject']);
    unset($form['comment_body']);
    unset($form['actions']['submit'] );
    unset($form['actions']['preview'] );
    print "Only Premium members can comment";
  }
 }
};

You can look in comment.module for the default code for comments....


'drush field-create' with type INTEGER from command line? drupal (ver 7.22) | drush (ver 6)

for an integer field type, try this :

drush field-create user streetnumber, number_integer, number_textfield

Or :

drush field-create user streetnumber, number_integer

(because you can ommit the widget type and the default one will be used).

If you are looking for the name of another field type, create the field in the admin panel, then look in your database, in table field_config, you will find it in the type column.


How to control resource usage of my website?

Use the Devel module It should show you a list of queries run when
the page is loaded and the time taken to run the query. From there
you can check which query is coming from which module.
You can also try a PHP profiler which gives you a lot of metrics.
Or try disabling your modules one at a time to decide when the load
time gets really high
Another option lies in smarter caching


creating custom content comprising both static and dynamic data

Panels and Views is the way to go.  However, this question is way too broad; in fact, a book could answer it.  That book is Drupal's Building Blocks: Quickly Building Web Sites with CCK, Views, and Panels by Earl and Lynette Miles.

Also see the Views tag wiki on this site, which links to Node One's excellent screencast.


How to make content creation form more organized. Taxonomy Checkbox list

If you are familiar with using CSS to change the layout of your drupal site already, something like this should work:

/* Make categories field 2 columns */

div.form-item.form-type-checkboxes.form-item-field-categories-und {

    -moz-column-count: 2;
    -moz-column-gap: 20px;
    -webkit-column-count: 2;
    -webkit-column-gap: 20px;
    column-count: 2;
    column-gap: 20px;

}

If not, it will depend on what theme you are using. We are using the seven theme for our admin pages, which include the node create pages. In the seven theme, I could just add the chunk of CSS above to the style.css file. Technically however, this chunk probably shouldn't be added into a core theme because it might get wiped out when/if you upgrade drupal core.

If you want to do it properly, you should create a new stylesheet with something similar to the CSS chunk above and give it a name. Then, add that stylesheet in your theme's .info file. (You can see specific instructions on how to do that here: https://drupal.org/node/171209)

Be sure that you don't have your CSS optimized when you are updating your stylesheets. If you aren't sure how to check this setting, go to admin/config/development/performance and make sure the option to aggregate and compress CSS isn't checked.

Without knowing more about your setup, what theme you are using, etc. it's hard to make a more specific recommendation.


Install and activate the Views Tree module.

Add a new 'Taxonomy Terms' view. (Choose the vocabulary or 'All').

Add a relationship to Taxonomy Term:Parent Term. Do NOT set this relationship as required.

Add two fields for Taxonomy Term:Term ID.
The first label as Main Term ID, and exclude from display. This one does not use the relationship.
The second label as Pareent Term ID and exclude from display. This one Does use the relationship.

Add any other fields you wish to include (Name, Description etc) and style as you wish.

Change the view format from Unformatted List to Tree (Adjacency model), and under settings, set the Main field to Main Term ID and the Parent field to Parent Term ID.

Create a page display, give it a path, and save the view. Go to the path and look at your taxonomy tree. (The tree styling sometimes does not display in the live preview, particularly if you use Seven as an admin theme.)


How do I add an attribute in an anchor tag?

You can do it using hook_link_alter

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {

    $variables['options']['attributes'] = array('data-anchor' => 'arial');

}


Why do I get an error after adding a .theme file?

I suspect that your .theme file was not actually empty. Please try the experiment again and check the file size. If it is 3, then your file starts with a Unicode byte order mark (BOM).

The BOM is typically invisible in editors, but it gets sent to the browser before Drupal internally calls the header() function. This causes the error message you have seen.

From a glance on your paths, I would not conclude that the OPcache plays a role here.


Views: add custom no result behavior to a view?

This is not an option in views panes because a 404 should be returned by the page_callback handler, which in this case is the panel that is holding the pane.

Option 1, see if this module works views404, but I have not used it so I do not know for sure.

Option 2, use drupal_not_found(), though I have not tried this in a panel.  Or if you are using contextual filters try this.

Option 3, stop using panels and use view page with Bean and Context and theme regions and a bunch of other things. This way the page_callback is being handled by the view, so the view has the authority to return a 404 instead of theming the frame and other blocks and presenting those.  Downside is you have to restructure the whole site so you probably dont want that.


Database query to check if current user has created a node reference?

Took a while to spot this, but you're not selecting any fields in the query so the SQL syntax here SELECT FROM {node} n is invalid.

Just select a field and you should be fine:

$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', 'b', '=')
  ->condition('uid', $user->uid, '=');


The path alias is a field, so you just need to alter the form and set the #required property on the element:

function module_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['path']['widget'][0]['alias']['#required'] = TRUE;
}


What indrock says in the comments is right, you should be using a placeholder like %user.

But you'll also need to pass the argument through to the form callback like so:

function my_module_menu() {
  $items['user/%user/foo/bar'] = array(
    'title' => 'My Title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_nameform', 1),
    'access callback' =>array('user_is_logged_in'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

The signature for my_module_nameform() would be:

function my_module_nameform($form, &$form_state, $account)

user_is_logged_in() doesn't accept any parameters so there's no need for the access arguments. Again as indrock says, clear the caches whenever you make a change to the hook implementation.


The Drupal built in RDF module works automatically and cannot be directly influenced from the user interface. There is however the Schema.org configuration tool (RDF UI) module.

  The module enables you to specify mappings between content types and
  fields with types and properties of Schema.org and build Content types
  based on schema.org. Through the rdf module, specified mappings will
  be embedded in HTML as RDFa, to provide semantically rich data.

The video on the module page explains the process quite well.


"Send email" action not working to send email to poster of comment

This question can be very hard to answer -- email is tricky as PHP just hands off your email to the underlying/remote mail system. I suspect nobody can tell you exactly what's wrong without in-depth examination of your setup.

But, the Mail Developer module will allow you to "try" to send and log raw emails without actually sending them, you can likely look for differences between mails that do send -- and the emails you think are not sending correctly.

  Maillog provides an easy possibility to log all Mails for debugging
  purposes. It's possible to prevent the mails to being sent, so there
  is no need for an extra mail server to test the mail functionality of
  other modules or the drupal core. Additionally you can immediately
  display the mail through the devel dpm() facility.

  If you like to upgrade from a previous dev release, please disable,
  uninstall and reinstall again. There's no upgrade procedure yet.

Also see the similar modules on the project page -- for additional tools to debug and resolve your problem.


Does anyone know how to use the Ubercart UC VAT module?

VAT module adds 'VAT settings' tab to your Store administration > Configuration > Tax Rates and Settings (/admin/store/settings/taxes), where you can specify global VAT value.


In your .theme file, add this suggestions alter hook (and flush caches so the new hook definition is picked up):

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) {
  $entity = $variables['item']->getEntity();
  $field_name = $variables['item']->getParent()->getName();
  $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name;
}

Then if you look at the twig_debug output, you should see something like:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'image_formatter' -->
<!-- FILE NAME SUGGESTIONS:
   * image-formatter--node--article--field-image.html.twig
   x image-formatter.html.twig
-->

Once that is done, you can create your template file called image-formatter--node--article--field-image.html.twig in the templates directory of your theme, flush caches again so the template is picked up, and override the template with any changes you'd like.

This should include a caveat that the code hasn't been thoroughly tested :)


Add custom classes or theme a custom form

You can add classes in #attributes:

$form['submit'] = array(
     '#type' => 'submit',
     '#value' => $this->t('Go'),
     '#attributes' => ['class' => ['button']],
);


How to display $date in node.tpl.php using a preprocess function in template.php

function thebridge_preprocess_node(&$vars) {
  if($vars['type'] != 'static_page') {
    $vars['date'] = date('Y-m-d');
  }
}

You might want to change the parameters of date(). More information in the Drupal documentation.


Hide the email address when searching for users

I think there is no such an option to hide email addresses from drupal system. You can create your own search-results.tpl.php in your theme or use template_preprocess_search_results() in your template.php to alter the user names.


Do not let Drupal handle 404's on development environment

Newer versions of Drupal have an addition to settings.php so that it doesn't handle the 404 for certain assets:

$conf['404_fast_paths_exclude'] = '/\/(?:styles)\//';
$conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpeg|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i';
$conf['404_fast_html'] = '<title>404 Not Found</title>
Not Found

The requested URL "@path" was not found on this server.
';

There are comments in the file that explain these new options some more.

You can also edit the .htaccess to disable the ErrorDocument and then put some ErrorCond directives in to prevent missing files from being punted to index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} !files/foo/(.*)\.bar$
RewriteRule ^ index.php [L]


How to get html source code from body field in node type edit form?

The basic text format filters out all but a few HTML tags.  You want to select the Full HTML text format to keep your divs and classes.


With optimized js enabled, my javascript code not working

The reason maybe is your custom script loads first before the Jquery script.

Try this:

(function($) {
  $(function() {
    //your script here
  });
})(jQuery);

or

Drupal.behaviors.somethingHere = function (context) {
  //your script here
}


You need to be using Apache Solr 3.1 and have the edismax plugin enabled to allow for these boolean operator queries. You should see this in your Solr logs as 'an unknown query type' error. This should be an option in the ApacheSolr Drupal module since this patch but if not (or if you're running Apache Solr 1.4.x) you can check out this ticket on the solr forum for instructions on how to patch your solr and solrconfig.xml to allow for edismax queries.


How to disable a form button in DrupalGap after it is clicked?

Senario 1 or 2 would both be fine, the trick is to disable the button immediately before the ASYNC call begins. This can be easily accomplished with a little jQuery:

$('#my-submit-button').prop('disabled', true);

Then I'd recommend re-enabling it in the success and error handlers for the ASYNC call to Stripe:

$('#my-submit-button').prop('disabled', false);


Need to override single Drupal 8 plugin function

Method #1
You can simply create new plugin which extends class of target Core plugin.

File: modules/example/src/Plugin/EntityReferenceSelection/ExampleSelection.php

namespace Drupal\example\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Entity Reference Selection with distinguishing field.
 *
 * @EntityReferenceSelection(
 *   id = "example",
 *   label = @Translation("Example"),
 *   group = "example",
 * )
 */
class ExampleSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this->configuration['target_type'];

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = array();
    $entities = $this->entityManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();

      $translated_entity = $this->entityManager->getTranslationFromContext($entity);
      $label = $translated_entity->label();
      $distinguishing_field = $translated_entity->get('field_example')->get(0);
      if ($distinguishing_field) {
        $label .= ' [' . $distinguishing_field->getValue()['value'] . ']';
      }
      $options[$bundle][$entity_id] = Html::escape($label);
    }

    return $options;
  }

}

Having this done navigate to field settings page and enable your reference method.

Method #2
For select list widget you can install Entity Reference Views Select which allows to build selection options using Views fields.

Method #3
Content Browser module (not stable yet) offers more advanced way to select entities.

Method #4
You may globally override Entity::label() method for required entity type. So that the [title] - [other_distinguishing_field] pattern will be used everywhere including default entity reference selection plugin.


With current D8 status, what's the decision tree for creating a new content entity type versus creating a Content Type for the "Node" content entity?

Decision tree for choosing between creating a new Node-entity-type Content Type versus a new content entity type:

Are you a programmer, or do you have easy access to a programmer?

If no, then you are presently pretty-much limited to creating new Node-entity Content Types.  (There isn't a UI in core for creating new content entity types, and the Entity Construction Kit (ECK) contrib module currently only has an alpha release.)
If yes, then continue...

Do you know exactly which contrib modules you want to leverage for your data?

If no, then the safe bet is probably to just create a Node-entity Content Type.
If yes, do those modules already support the custom entity type(s) you're considering, or are you willing to help enhance them so they will or recreate the desired functionality in your module?

If no, then just creating a Node-entity-type Content Type may be best for you.
If yes, then continue...

Will the actual content data that is enabled by your module merely help group or annotate other content data?  (So that it will seldom be viewed on its own.)

If yes, then consider whether your module is like the existing entity types for taxonomy terms and comments.  If it is, then a new entity type may be a safe bet.
If no, then continue...

Can you clearly articulate why a new Node-entity-type Content Type will not work for you?

If no, then your safe bet is to probably just create a new Node-entity-type Content Type.
If yes, then continue...

Lastly, are you sure that you can't just extend the Node-entity-type and that you want to recreate all of its useful functionality like CRUD operations?

If yes, then go ahead and create a new custom entity type.
If no, or if you're not sure, then you probably want to engage some experts to help you decide.

Notes:

This decision tree does not consider performance or security.  I'm not sure if or when a new custom content entity type would perform better and be more or less secure than a Node-entity-type.
Even if this tree is a good answer, it will probably not remain one over time due to updates in Drupal core and contrib module releases.  StackExchange doesn't seem to accommodate how the "best" answer today may not be the best answer tomorrow.)


Pretty much $form_state->getValue('foo');.

See the docs page for getValue.


How to alter the Views field Format drop-down menu

If your content type is blog, for example, and it has a CCK image field, create a relationship from your blog content type to the image content type.

Create a new field in the View and select the field_image from the image content type, make
sure to select the relationship you created:

And select URL to file from the Format dropdown:


Cannot assign roles creating User through REST endpoint

For other people reaching this post, the answer to this is to use some kind of authentication on the REST endpoint, that only allows trusted users to create new users.

Otherwise anonymous users would be able to create admins and crash the site.

So this code is correct,

"roles": [
  "5",
  "6"
]

but the problem is that the user calling the endpoint has to have the administer permissions and administer users permission to be able to set roles to users.

That can be done by setting a role that has those permissions and also has permission to call the endpoint.

oAuth could be used to do that.


My custom preprocess function works as soon as the cache is cleared, then stops working

Drupal is looking to include the following file:

drupal_get_path('module', 'mymodule') . '/templates' . '/mymodule.theme.inc'

but, you say that you've put it in the main module folder, here:

drupal_get_path('module', 'mymodule') . '/mymodule.theme.inc'

So Drupal isn't going to include the file on subsequent calls to the theme function. So, you might want to move your include.

You can see this from how your hook_theme is processed in: _theme_process_registry


The variables for theme_table() are structured differently to a standard render array, so you need to format your array slightly differently:

$row = array(
  'title' => array(
    'data' => $name . ' ' . $surname,
    'class' => array('myClass')
  ),
  'date' => date('Y-m-d', $account->created),
  'name' => $name . ' ' . $surname,
);

The above produces:

      1970-01-01

The first and last column are only empty as my test environment doesn't have the same variables defined as in your code.


How to render Entityform submission (entity) without DOCTYPE and HEAD tags?

So in the end it was the Emogrifier class that kept adding the DOCTYPE and everything else.

It would have been good to know that it adds CSS inline but it also fixes/creates a whole new document. So it can't be used for e.g. fragments or in this case entities.


Passing arbitrary data into a node prior to preprocessing

Node's in D8 work differently to D7. in D7 node was a stdClass object - basically used in the same way an array was assign a value to a key ($node->value). In D8 Node's are proper objects and can't do the same key/value. Instead, how about creating a field on the node and assigning the value to the field, save the node and then view it?


How to implement challenges with prizes in a Drupal site?

Your question seems like a perfect usecase for the Goals module (disclosure: I'm its maintainer). It can be used in combination with the User Points module, though you'd use that combination by granting user points "after a goal is completed".
Read on for a possible configuration for your specific case.

Configure the goals

Define some goals, with a description (say) like so:

Challenge 1
Challenge 2
Challenge 3

For each goal you may optionally associated some image with it, which are typically used to visualize the goals completed by a user.

And after a goal is completed, you can (optionally) automatically grant a predefined amount of user points to the user who completed the goal.

Configure the tasks

To achieve goal "Challenge 1", define the Task(s) to be completed. E.g.:

Publish 1 (or some other amount of) articles.
Post 1 (or some other amount of) comments.

To achieve goal "Challenge 2", define the Task(s) to be completed. E.g. publish 10 articles and post 20 comments.
To achieve goal "Challenge 3", define the Task(s) to be completed. E.g. publish 25 articles and post 50 comments.

Advanced task configuration

A more advanced way to use (configure) Goals, is to configure tasks like so:

there could be multiple tasks to be completed for a single goal.
some tasks might have to be repeated multiple times.
some tasks might have to happen within a given timeframe.
some tasks may require some amount of time to expire in between any 2 similar tasks.

Track progress while performing tasks

To track the progress made by a single user to complete some task, you only have to write the appropriate rules, using the Rules module, to record relevant events happening in your site, which are related to the completion of the various tasks.

For the goals/tasks described above as an example, you'd only need 2 (extremely basic) rules, which would be triggered like so:

After publishing an article.
After posting a comment.

Note that these 2 rules can be re-used to measure progress on each of the 3 goals.

Moreover, the above challenges are pretty straight forward (basic) as examples of Challenges. But you can do this for virtually any entity for which you can think of a way to track them via the rules module.

Process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. And the user points related to completing that goal will be rewarded.

If you want, you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user.

More info

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for additional details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).


I'm assuming that you're using Drupal7.  I will provide some pointers but you'll have to look up the details on your own.

Sounds like you might want to create a new Content Type.
Views can generate a list of a specific Content Type (in your case, list only seminars).
Views typically links each item in the list to the actual node with the full info
The Webform module will allow you to create sign up forms but there's likely more that you'll have to do to tie everything together.


Rather than $variables['fieldclass'] use $variables['classes_array']

Based on the docs


Webform Tokens lets me access form meta-info but not user-submitted values (with Fill PDF)

The issue is that Fill PDF 7.x-1.9 doesn't work with Webform 4 due to a change in the structure of the $submission variable from Webform via webform_get_submission().  See this post for an explanation and an ad hoc fix.


These lines of code gets me out this error and i cannot understand it

The signature for SelectQuery::fields() is:

public SelectQuery::fields($table_alias, array $fields = array())

So you need:

$number_to_keep = db_select('variable', 'va')
  ->fields('va', array('value'))
  ->condition('va.name', 'dblog_row_limit', '=')
  ->execute();


Views 3 : Set header/footer/empty text for view via views_embed_view

First up, don't use views_embed_view(). It is a very simple function that doesn't allow for customisation.

Do something like this:

// Load the view.
$view = views_get_view('VIEW_NAME');
// Set the options for the header text.
// To get an idea of what options are available, set up a view with header text
// and then use the devel module to print out the view definition.
// For example, add a header text area field and print it with
// dpm($view->header['area']); after you have loaded it with views_get_view().
$header_options = array(
  'label' => t('Header text'), // Administrative label. Not really needed here.
  'content' => 'This is the header text content.', // Content of header text.
  'format' => 'filtered_html', // Format of header text.
  'empty' => 1, // Show even when there are no results. Set to zero otherwise.
);
// This adds a header handler for a text area. The table is views because it is not
// a database field. The field is area because it is a text area.
// The header_options are the settings.
$view->add_item('DISPLAY_NAME', 'header', 'views', 'area', $header_options);
// This is the preferred way to get the rendered view.
$output = $view->preview('DISPLAY_NAME');
// If you want you can check for results with this.
if (!empty($view->result)) {
  // Do something if there are rows.
}

You can do the same for footer handlers:

$view->add_item('DISPLAY_NAME', 'footer', 'views', 'area', $footer_options);

and empty text:

$view->add_item('DISPLAY_NAME', 'empty', 'views', 'area', $empty_options);

You can also change the field type if you don't want to use Global: Text area.

For more information see $view->add_item()


Turns out there is an error with the module but someone developed a patch for it.

Here;

https://www.drupal.org/project/heartbeat/issues/2102743


Filter by postal code as location within user defined radius

geofield should have what you're after.  It includes proximity handling and an exposable views filter.


How to implement and install Icomoon and Fontello icon packs in Drupal 7?

Ok, got it figured out.

Go to Fontello website.
Drag and drop Icons you need in the box on top.
Save file as Zipped, don't do any renaming or extracting.
Go to admin/config/media/icon/import
Give it a title and import the zipped file you just downloaded.

The icons will then show up on the drop down when adding them to articles or wherever.

Addtionally, the help files for Fontello are here:

https://github.com/fontello/fontello/wiki/Help


I want to send a confirmation mail on event of submit button in webform?

The webform module comes with an option to send e-mails after submission. Check the webform e-mail tab when you are editing a webform


I'm getting a 404 on a user/reset/%/%/% path

This was being caused by a third party custom module, funny enough not in hook_menu_alter.


It could be that your form_alter happens before the locale field is added. Make sure your module runs last.


Concatenate two fieds in an EntityQuery condition

I don't think it's possible this way.
I would rather split the $string in two parts, and check the two fields with each part.

$query->condition("FIELD_1)", $string_1);
$query->condition("FIELD_2)", $string_2);

You have many ways to separate the string in two.
Is this helping you ?


Asserting a failed login attempt on Simpletest

In case someone else wonders about this... It wasn't difficult, but I didn't realise at first that it can be done by copying part of the DrupalWebTestCase::drupalLogin() source code:

$edit = array(
  'name' => $user->name,
  'pass' => $user->pass_raw,
);
$this->drupalPost('user', $edit, t('Log in'));

And then asserting that the user could not log in:

// Assert that the user is not logged in
$this->assertNoLink(t('Log out'), 0, t('User not logged in.'), t('User login'));


Operations in find content page not working

Did you try selecting some files before (tick checkbox)?
Some filters only appears when contents are selected (in the Media tab for example in my website)


How to display entire comments in separate page

The Talk module shows the comments for a node in a tab added to the node page.

  The talk module removes comments from the node page and puts them on a separate tab. This style of commenting is very popular on Wiki sites (usually called the "discussion" page) and on news websites where the goal is to separate user generated content from editorial content.

  When installed this module will add a tab to the set of tabs at the top of a node view page like "View | Edit | Talk" and provides a link at the bottom of the node to go to the talk page and view comments.


The Node Limit module does exactly that:

  The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create.

Among its features are:

  Per-role node limits
  Per-user node limits
  Per-time interval node limits
  Any combination of the above


Try to change your "Date selection" in your second screenshot to "Text". If I remember correctly, you can now provide a text as paramaters.
There you can add things like
from: now and till: now +3 days


How to rearrange fields in user/%/edit page

use nod template as page--user--edit.tpl.php and you can able too rearrange the fields by its machine name like as we did for content types...

just try this..


To accomplish this you need to edit the body field before rendering. There are 2 ways of doing this.

1) Using the node template file
In case of an article the template file would be node--article.tpl.php. Here is some sample code to edit the body field and include an ad after 4 paragraphs. The node--article.tpl.php file can be edited to make the following change.Here is the quick reference to theme pages in drupal.

 <?php
       $array = explode("<p>", render($content['body']));
       $array_size = sizeof($array);
       if($array_size < 5 ){
         $array[array_size-1] = $array[array_size-1]. $ad;
       }else{
         $array[4] = $array[4]. $ad;
       }
       $content['body'] = implode("", $array);
       print render($content['body']);
    ?>

instead of rendering the body using <?php print render($content['body']); ?>

2) Using the hook_node_view.

This node gets invoked before the node gets rendered. You can include your logic to edit the body field based on your requirement in this hook. I am assuming you have some idea of implementing hooks in your custom module. Refer to this link for more details of this hook.


Entity reference autocomplete field node

First, to handle multi value fields you'll need this patch: https://www.drupal.org/node/2224803#comment-11477609

Second, depending on what Widget you have selected for your Entity Reference field, this does/can change what Services expects to be POST/PUT up to the server.

I personally always set the Widget as an Autocomplete, and then this JSON format is the correct one to use:

var node = {
  type: 'article',
  title: 'Hello world',
  language: 'und',
  field_foo: {
    und: [
      { target_id: '... (123)' }
    ]
  }
};

You can literally put anything you want in the position of the ..., the only thing that matters is the Entity ID is wrapped in the parenthesis.


Which tables and which data can I omit from backup?

You can omit the data from some tables. You cannot omit the actual table creation.

Tables for modules are created in one of two ways. Either when the module is first enable via hook_schema or when an update hook (hook_update_N) runs. Tables in hook_schema are only created when the module is first enabled.
After an update hook is run the system table is updated with the schema version so it's not run twice.

You can't expect modules (or core) to just recreate tables that they expect to exist but are missing on the fly. It's nothing to do with being robust - this is just how Drupal works. Also it would be very inefficient to check a table exists before running every query. You would be doubling the number of queries you have to run. This would be crazy!

If you have any missing tables you would need to disable, uninstall and then re-install the module to fix it.

This question has suggestions of which which tables contain data that can be excluded.


First of all you need to replace $ with jQuery and secondly you also need to put the width and coulmn properties inside double quotes. i.e,

drupal_add_js('
jQuery(document).ready(function () {
    if (jQuery.browser.msie && jQuery.browser.version < 10) {
            jQuery("li#megamenu-mlid-774 .megamenu-items, li#megamenu-mlid-842 .megamenu-items").columnize({
                "width": "420",
                "columns": "3"
            });
        }
  });', 'inline');


Using nested node content type template files

Assuming you want the structure to be something like this:

ie, render the template inside the the other template, and assuming you have named your templates properly, put them in your theme, and cleared the theme registry (or cleared all caches), you need to set the display settings appropriately.

In the Manage Display settings for Widget Set, find the Content Widget field, and adjust the settings:

Set the Label as you need
Set the Format to Rendered entity
The click the gear, and adjust the settings.  You can pick the view mode (full, teaser, etc), whether to show links or not, and potentially other settings that modules have defined.

Note that this does assume your node-to-node fields are using Entity References and not Node References.

Then you should get output to use nested templates.  Using Entity View Modes and Rabbit Hole also come in very handy when you do things like this on your site.


override default with the "taxonomy/term/%" views

or

function THEME_preprocess_page(&$vars) {
  if(isset($vars['page']['content']['system_main']['no_content'])) {
    unset($vars['page']['content']['system_main']['no_content']);
  }
}


How to preserve element type validation upon adding custom element validation?

You need add the definitions defined in the getInfo() method of that type explicitly yourself, there is currently no other way to do that.


block['content'] contail both string and form

drupal_get_form returns an array, so you can't concatenate it with a string.

Something like this will work, using a render array:

$block['content'] = [
  'preamble' => [
    '#markup' => '<strong>...</strong>',
  ],
  'form' => drupal_get_form('custom_request_price_form'),
];


Might be a bit late on this one, but there doesn't seem to be a posted solution online. You can remove the tax line using the below.

In your template.php file use the below, this should hide it from your order confirmation email as well. I haven't noticed any problems from this modification, but ymmv. The variation from the standard code is: $rows = array_splice($rows, 2);

function THEME_commerce_price_formatted_components($variables) {
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');

  // Build table rows out of the components.
  $rows = array();

  foreach ($variables['components'] as $name => $component) {
    $rows[] = array(
      'data' => array(
        array(
          'data' => $component['title'],
          'class' => array('component-title'),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total'),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }

  $rows = array_splice($rows, 2);

  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}


How do I get both published and unpublished records using entity query?

The propertyCondition allows three arguments. You could pass in an array containing the two values and as third parameter the operator 'IN':

->propertyCondition('status', array(0, 1), 'IN')

Note: As you have been asking for nodes, and nodes AFAIK only have the status 0 or 1, you could also just omit the status property condition entirely and would get all nodes.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->range(0, 1);


How to play the video using media module?

You can see see here the list of player modules that extend media module.
There is also basic version information about each module.

Start with jPlayer and see if it fits your needs.


Drupal 7 rewrite is removing get parameters from query string

It turns out that there was a bug in the latest release that in /modules/contrib/link/link.module that was causing the query strings to be stripped from the URL in the token. I replaced the code in this file with the code from the pre-upgrade version and it began behaving as expected again. This, of course, is not a resolution to the issue, but at least the source of the problem has been identified. For more info, see the original bug report.

I later found that there is a patch for this issue in the dev version (7.x-1.x-dev) of this module. Download this module and replace it in your install and you should be all set.


subtheme preprocess functions inheritance

EDIT : solution (can't answer myself before 8hours after posting)

Ok for those who're interested in the why :

It's a "side effect" of Twitter Bootstrap theme specific loader (_bootstrap_theme(), bootstrap_include ...)

To respect the correct order of hook processing, we have to keep the same filename as the main theme where hook is located in. (directories tree could change)

In my case, bootstrap_preprocess_region() was located in \sites\all\themes\bootstrap\theme\system\region.vars.php, so to overwrite it the mytheme_preprocess_region() should not be in my subtheme template.php file (=> breaking order of processing)

It should live in \sites\my-site.com\themes\mytheme\(opional folder)\(optional folder 2)\region.vars.php

Not explicitly written in TBS documentation I think ...

I hope this could help someone one day ! (:


How can I switch back and forth between globally installed Drush versions?

As you probably know newer Drush versions have to be installed locally. Go ahead with installing Drush 10 (Drush 9 is EOL) for certain sites. The globally installed Drush acts as Drush Launcher and will find local Drush installs.


How to create programmatically menu links with just created nodes during installation profile in aegir ?can't get nid!

You can add a menu item using this

$item = array(
        'menu_name' => 'menu-name',
        'link_title' => 'Link title',
        'link_path' => 'node/'. $nid,
      );
menu_link_save($item);
//don't forget to clear menu cache after saving menu item
menu_cache_clear_all();

Hope this will help

Updated Answer
As I looked into Drupal 7 standard profile installation file, that is standard.install (Line no 413), you can see "Home" link creation there.

// Create a Home link in the main menu.
  $item = array(
    'link_title' => st('Home'),
    'link_path' => '<front>',
    'menu_name' => 'main-menu',
  );
  menu_link_save($item);

  // Update the menu router information.
  menu_rebuild();


Get logged in user's username as twig variable

You would have to target a specific one. All twig templates is not possible because of caching. Many page elements don't get rebuilt on every request and they will display the wrong user.

And if you try to remove caching from all elements, your site would be very slow.

If you add this to a specific twig template, then you can adjust the cache context of this render element:

function MYTHEME_preprocess_HOOK(&$variables) {
  $variables['currentusername'] = \Drupal::currentUser()->getUsername();
  $variables['#cache']['contexts'][] = 'user';
}

Where HOOK is your template type.


Why are there so many settings.php files one in each folder or sub-directory?

Refer the multisite doc as Molot suggested. We don't know how your site(s) have set up, so you have to experiment it yourself.

  Q1: Why isn't there just one settings.php per sub-domain site?

There is. sub.example.com site's settings.php file is sites/sub.example.com/settings.php. The reason to have a whole folder is to make it possible for you to store files, modules, themes and libraries separately (sites/sub.example.com/modules will be only available to sub.example.com likewise.)

  Q2: What is the difference between /default/settings.php and
  /all/settings.php?

You should not have a settings.php file in sites/all folder. That folder is a special one that is used to store common files across all the sites, and the default modules/themes/libraries folder for the only site if it's not a multisite.

  Q3: And why are folders demo.[domain].org and [customer].[domain].org
  in the /sites/ folder? Perhaps they are just legacy folders left by
  the previous coder/hacker of the settings.php used in the those
  sub-domains.

If there are demo.example.com site, that site is probably using the settings.php inside to load the settings. You can however change this in the sites/sites.php file. Unless you override, demo.example.com site is using sites/demo.example.com/settings.php.


How can I exclude admin(uid=1) for "Views Argument PHP Validator code" which limit a view to a User’s uid value?

That is a basic PHP problem, it does not concern Drupal so much. You want to admit access to the admin user always, so you will want to exclude that user's user id of any checks. However, your logic is wrong. The correct version would be

global $user;
return ($user->uid == 1 || $user->uid == $argument);

Which firstly returns true if the user is the admin user and secondly returns true if the user id matches the argument.


Why is a content type's node twig template being used by taxonomy term?

A view can show content or fields. The taxonomy term view shows content and this means it renders each node in a node template. If you don't want that the template of the full node display is picked up by the view use different view modes, which you can append to the template name:

node--course--full.html twig
node--course--teaser.html.twig

teaser is the view mode the taxonomy term view uses by default. You can change this to a custom view mode if you want to style the nodes displayed here in a different way than in the front page view which uses teaser as well.


Editable Views should do what you are trying to accomplish. It won't allow you to drag the items up/down, but it will allow you to update multiple fields at once.

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

  Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.


You can request a rebuild in form submit and then add the message to the top of the form:

  public function buildForm(array $form, FormStateInterface $form_state) {

    if ($form_state->isRebuilding()) {
      $name = $form_state->getValue('name');
      $form['header'] = [
        '#type' => 'container',
        '#attributes' => ['class' => ['form-header-message', 'alert', 'alert-success']],
        'message' => [
          '#markup' => $this->t('Thank you for submitting this form, %name!', ['%name' => $name]),
        ],
      ];
    }

    $form['name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Name'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setRebuild();
  }


Calling drupal_goto(), you are avoiding the session is destroyed. The function that invokes hook_user_logout() (user_logout()) contains the following code.

  watchdog('user', 'Session closed for %name.', array('%name' => $user->name));
  module_invoke_all('user_logout', $user);

  // Destroy the current session, and reset $user to the anonymous user.
  session_destroy();

  drupal_goto();

drupal_goto() calls drupal_exit(), which means that with your Drupal's execution is interrupted before session_destroy() is called.

What you can do is changing the code to something similar to the following one.

function ucenter_user_logout($account) {
  user_cookie_save(array('ucenter.logoff' => '1'));
}

function ucenter_init() {
  // Check the value of the cookie Drupal_visitor_ucenter_logoff
  // and print the message if the user precedently logged off.
}


Taxonomy child terms list and product list view

Here's my tutorial video (I've published this step by step in many places): https://www.youtube.com/watch?v=y1jqu8JnLbU

STEP BY STEP

Create a Taxonomy Vocabulary here: admin/structure/taxonomy (And create a few terms)
Create a Taxonomy View here: admin/structure/views/add

  You want to make sure that you choose "taxonomy" entities.

Add a contextual filter for "Taxonomy term: Parent term"

  Make sure to select "Default Filter" and choose "Taxonomy term from url." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

Add a new page to this view, remove the contextual filter from this view and add a filter for "Taxonomy term: Parent term" and set it to "equal to" and leave the field there blank.
Save that view and create a new view here: admin/structure/views/add

  Make sure this view is a for "Content" of type "Product Display" (or whatever entity bundle has the field for your taxonomy terms).

Add a contextual filter for your taxonomy term, mine was called "Product Categories"

  Make sure this contextual filter displays "Contents of No Results." Also, specify a "Default validation criteria" for "Taxonomy term" and choose "Convert taxonomy name to ID" and select "Transform dashes in url..."

Add a "No results" item called a "View Area" and select "Page_1" from your first view (this is the second page we created)
Save this view and go back to the first view.
Add a "No results" item called a "View Area" and select the second view that we just made.
Make sure your title field in the Taxonomy View doesn't link to the taxonomy term, but it outputs the field as a link to "catalog/[name]" that way your catalog names are clickable :)
Profit!


If you take a look at the file_save_upload() call, you'll see what's happening with the py files.  It seems to be a It will occur with php|pl|py|cgi|asp|js files.

FROM: file_save_upload() http://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7

// Rename potentially executable files, to help prevent exploits (i.e. will
// rename filename.php.foo and filename.php to filename.php.foo.txt and
// filename.php.txt, respectively). Don't rename if 'allow_insecure_uploads'
// evaluates to TRUE.
if (!variable_get('allow_insecure_uploads', 0) && preg_match('/\.(php|pl|py|cgi|asp|js) (\.|$)/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
$file->filemime = 'text/plain';
$file->uri .= '.txt';
$file->filename .= '.txt';
// The .txt extension may not be in the allowed list of extensions. We have
// to add it here or else the file upload will fail.
if (!empty($extensions)) {
  $validators['file_validate_extensions'][0] .= ' txt';
  drupal_set_message(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $file->filename)));
}

}

If you wish to allow these uploads (without converting their extensions), you would set all_insecure_uploads to 1 (TRUE), but I doubt you do :)

KMT


They're added in template_preprocess_html:

$variables['html_attributes'] = new Attribute();

To alter them, you can implement hook_preprocess_html in your theme or module.


Commerce: retrieve coupon code used in order

If you're using 1.x version, an entity reference field is attached to the commerce order field upon installation (see function commerce_coupon_order_configuration()). This creates the field table commerce_coupon_order_reference.

To check coupons attached to an order, simply access the commerce_coupon_order_reference field, like:

if (!empty($order->commerce_coupon_order_reference)) {
  // Traverse the coupons referenced by this order.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  foreach ($order_wrapper->commerce_coupon_order_reference as $coupon_wrapper) {
    dpm($coupon_wrapper->value());
  }
}


What's the best practice for field API prefixes? (To prefix or not to prefix, that is the question)

I prefix my custom fields always with the name of my module, which, I think, is a good practice, so that I know which module provides this field. And also I think this is the same reason Drupal Field UI adds the field_ prefix since the fields are created by the Field module in this case.


Rate Module: Display the rating in the comment user added to the node

I achieved a similar thing with the Fivestar module. The trick is to let the users vote when they comment. You can find a whole description for the set-up at https://drupal.org/node/1308114. Here is an adapted version of the documentation:

  Setting up the content type

  Go to admin/config/content/fivestar and create a new tag, e.g. called Vote or Rating.
  Go to your content type and add a new Fivestar field, e.g. called "Rating".
  Select the widget type Stars (rated while viewing) and tag the Rating.
  Select the number of stars. Make sure it will be the same on both the content type and the comments.
  Go to your content type's display settings and click the settings button for the Fivestar field.
  Set Value to display as stars as Average Vote.

  Setting up the comments

  Go to the comment field settings for your content type.
  Use Add existing field and add the same Fivestar field you created for the content type.
  Widget: Stars (rated while editing).
  Select the number of stars, equal to the amount that's used in your content type.
  Select the voting tag you created earlier and set the voting target to Parent Node.
  Go to the comment display settings and click the settings button for the Fivestar field.
  Set Value to display as stars as User's Vote and change Text to display under the stars to User's vote.

I asked a question about how to display the average rating as stars before: How to display the average rating of a node as stars in a view?. Maybe that can help you too.


drupal 7 hidden views blocks when node references value is empty

You need to add a Filter Criteria which validates to "Is not empty (NOT NULL)" on the field which should not be empty.


How to get total number of rows on a block of a view

Use a views_view_ hook, i.e. views_view_unformatted,  views_view_list  etc... I tried this with a PHP count for my views block and it worked great.

My function is:

function MYTHEME_preprocess_views_view_unformatted(&$vars) {
  $num_rows = $vars["rows"];
  $count = count($num_rows);
  echo '
This view has ' . $count . ' rows

';
}

This yielded the number of rows in the view.

Printed, I see:


How the RTL css system works in drupal specially in omega theme?

The css file with the rtl at the end will be loaded whenever you have a RTL language added to your site. in Omega as the CSS files are generated by Scss you need to create a scss file with the rtl at the end of the file so at the time of compiling the scss you will have the rtl css files ready to use.
The RTL files will override the original files.


Check the setup text format: Filtered HTML, here

admin/config/content/formats/[your_format]

The settings will filter the desired output.
Or just choose Full HTML (if configured properly) ;)


Overwrite the title for a particular taxonomy page

It is easily done with the Taxonomy Title module.
It adds a "Term page heading" field for terms. Simply edit your term and you'll see.


Display Entity Reference field twice, with different display modes

How to display a reference field twice with the help of EVA:

Install EVA.
Add a new View.
Add a display "EVA".
Add the Entity Reference field to FIELDS and configure the Formatter to "Rendered entity" and set the view mode Display 2.
The EVA display includes the section ENTITY CONTENT SETTINGS, choose the entity type Content and bundle Type A.
In the ADVANCED section add a contextual filter for Content: ID.
Save the View.
Now the new field is visible in the field UI of the content type Type A and you can drag'n'drop it to the final position.


I've found a solution:

function beneficiaire_user_login($form, &$form_state){
  if($_SESSION['account']->temporaire){
    $_GET['destination'] = 'update-password';
  }else{
    $_GET['destination'] = 'order';
  }
}


How can I speed up the module registry approval proces on Drupal.org?

The process can be very slow unfortunately. There probably isn't a complete answer, but I can give a few hints.

Try to find users which test and report that it works (as detailed as possible), developers to review it and report that too. There are many ways to do that, for example for developers:

Ask in IRC (#drupal-contribute) (Remember to offer something in return, e.g. patch reviews). Do not ask multiple times and only when the channel is quiet.
Review/test applications of other users and ask for a review of yours in return.
If your module interacts with other modules, ask their maintainers to review the integration code. Again, you could help with the issue queue of these modules (review, write patches, answer support questions)

This has two advantages. a) It shows that your module works and users are interested in using it. b) It helps to keep it on top of the (very long) list of issues.

Also, try to make it as easy as possible to install and test your module. For example, if your module integrates with a third-party service/website, provide a test account for it or make it possible to register there for free (if it isn't anyway) and provide detailed installation instructions (for example in a README.txt or INSTALL.txt file).


User redirect after changing profile information

There were a bunch of issues with your example, but this should work:

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

  switch($form_id) {

    case 'user_profile_form':

      $form['#redirect']='user/' . arg(1);
      break;

    // any other forms here

  }

}

which will redirect to the user page of the user being edited after editing that user.  This way, if an admin is editing another user, it redirects to that user's page, not that of the logged in admin.


Form state redirect to node path plus fragment

Use the third argument of the setRedirect function:

  array $options: (optional) An associative array of additional options.
  See \Drupal\Core\Url for the available keys.

And if you check that doc:

  @param array $options   (optional) An associative array of additional
  URL options, with the   following elements:

  'query': An array of query key/value-pairs (without any URL-encoding)
  to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL.
  Do not include the leading '#' character.
  'absolute': Defaults to FALSE. Whether to force the output to be an
  absolute link (beginning with http:). Useful for links that will be
  displayed outside the site, such as in an RSS feed.
  'attributes': An associative array of HTML attributes that will be
  added to the anchor tag if you use the \Drupal\Core\Link class to make
  the link.
  'language': An optional language object used to look up the alias
  for the URL. If $options['language'] is omitted, it defaults to the
  current language for the language type LanguageInterface::TYPE_URL.
  'https': Whether this URL should point to a secure location. If not
  defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP.

In your case you should use just fragment:

$options = [
  'fragment'   => 'tag',
];

$form_state->setRedirect('entity.node.canonical',
  ['node' => 8],
  $options
);


Is there a maximum amount of data that a Drupal database can safely store?

The short answer is no. There is not reasonable way you can store "too much data".

If you read the Limitations entry on wikipedia about MySQL, you'll see that "maximum amount of data" doesn't come into the picture.

More specifically, MySQLs documentation says

  The effective maximum table size for MySQL databases is usually determined by operating system constraints on file sizes, not by MySQL internal limits.

Depending on what you do with the data, however, you can get performance problems if you store a lot of data, but that's not a Drupal specific problem.


Following solution works:

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 */
function YOURTHEME_preprocess_menu(&$variables){
  foreach($variables['items'] as &$link){
    $link['title'] = Markup::create($link['title']);
  }
}

Source: Allow html into menu item names - Solution for Drupal 8


hook_node_access($node, $op, $account) not working

You would need to check the access as the Admin role would have Bypass content access always.

hook_node_access

Also, try to check with the Reference.


mailsystem module does not appear in the selection field for HTML Mail module class

Below where you show in your screenshot, see the "New Class" field set.
Expand that

For the Class to use for the format() (link is external) method field select HTMLMailSystem

Class to use for the mail() (link is external) method select SmtpMailSystem

Save the form.

The new class will be available for use to set the Site Default.


Let the user change language with a select

This is what i did in the end:

php

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$type = 'language_url';
global $language ;
$lang_name = $language->language ;
$links = language_negotiation_get_switch_links($type, $path);
$languages =array();
$htmlSelect = "<select id='selezioneLingua'>";
foreach ($links->links as $id => $link) {
    $prefix = $link['language']->prefix;
    $selected = '';
    if ($lang_name == $prefix){
        fb('same');
        $selected = 'selected';
    }
    $htmlSelect .= "<option $selected value='$prefix'>$link[title]</option>";
    $href = ($link['href'] === '<front>') ? '' : '/'.$link['href'];
    $languages[$link['language']->prefix] = "?q=".$link['language']->prefix.$href;
}
$htmlSelect .= "</select>";
drupal_add_js(array ("languagepages" => $languages), 'setting')

javascript:

jQuery('#selezioneLingua').change(function(){
    var val = jQuery(this).val();
    var languages = Drupal.settings.languagepages;
    window.location.href = languages[val];
});


Show a term description when the search filter in a view is that term?

Create a template for the view.

Edit the view. Under "Advanced" find "Theme: Information". Click on it to find the names of the templates that are applied in your theme. I think "Display output" is what you want to use. It will show you the contents of the template.

In your custom theme, create a template with the same name as the template you copied. Paste in the contents of the template you copied.

Now you can use PHP to get the information you want (available variables are listed in the comments of the templates), manipulate it as needed, and add it to the $header or wherever you want it, without any PHP in the database.


Using forms API - sending submitted data as an XML attachment to an email address

Just implement the hook_form_alter or hook_form_FORM_ID_alter and add your custom submit handler.

See this article for an intro into hooking into forms:
http://websmiths.co/blog/very-introduction-drupals-hookformalter


You can use class="left" in your HTML, and .left {float:left;} in you CSS.


How Do I change existing theme to a new one without losing content?

Technically you won't loose any of your content since Drupal's theme layer is seperate from the content. Depending on how your previous theme is set up (templates, theme functions, etc) it can however happen, that the display of some of your content might not work / work differently in another theme.

A good starting point for learning more about Drupal's theme layer is the Theming Guide which is part of the Community Documentation at drupal.org. A more advanced view on theming can be found in the chapter 'Themes' of the book Drupal 7 – the Essentials which you can actually read online at drupal.org.


Improve performance by using drush functions instead of Drupal module functions

Queues are defined within Drupal modules, and you can use drush to run those queues:

drush @site queue-list
drush @site queue-run queue_name

Changing the interface to the import code (queue, batch api or a drush command) won't affect drastically the import time.

I'd review the import code to try and optimize it. For example by caching (in memory) any data you may be loading recurringly from the database.


Can visit the page but can't see the tab it should have

Drupal doesn't show tabs when there is just a tab defined or visible for the currently logged-in user (which includes the case users don't have the permission to see other defined tabs).
If you look at what Drupal does, for each node there is node/%node/view and node/%node/edit; when users don't have the permission to edit a node, they don't see any tab, in the node page.

See the following screenshot, taken from drupal.org at https://www.drupal.org/node/5, using an account with the permission to edit the node.

You see the View, Edit, Outline, and Revisions tabs.

Compare it with the screenshot taken using an anonymous user account, for the same page.

You don't see any tab, but the screenshot is for the View tab.  In fact, if you try accessing https://www.drupal.org/node/5/view as anonymous user, you would see the same as in the last screenshot.


how to export nodes and their referencing entities

My solution for this was to use the Migrate module. It is very powerful and you can create update classes for custom entities when one doesn't exist from the producer of the contrib module. I would highly recommend it.


How to make a complex grid layout with the Omega theme?

For something like this, I will simply use the Block Class module and for the blocks I'm placing inside a region, add a grid-X and alpha/omega appropriate classes as needed.

I've never found the reason (even in really advanced layouts/designs/grids) to do anything more than that...