Displaying a list of image thumbnails, with click-through

Creating a new Image content type is a good way to approach this.  Views can certainly display the content as a list or a gallery-- or some combination of both-- but you may want to think about how you want to display the content in the gallery.

Comments are handled by Drupal out-of-the-box so I don't think you have much to worry about with regard to them.

You do not need to use the Insert module if you're just going to be uploading an image file.  If you're only going to be adding 150 images once, I would just create the image nodes one-by-one.  If you anticipate having to add lots of images regularly, you should post a separate question asking for a solution to that.

Here are some resources to get you started.

First, there's a screencast about building a gallery in Views.  Although this is for Drupal 6, and a fair number of things have changed in Drupal 7, the basic principles are the same.

Second, there are some helper modules which can give you pop-up and gallery-type effects without much work.  Two of the more popular, well-supported ones are:

Lightbox2
Colorbox

Either can be used on its own or with Views.


dev-test-prod staging workflow for drupal with transport of database changes

Regarding #2, I would recommend using drush site aliases.  See also the sync_enable example in Drush, which demonstrates how you can get Drush to automatically adjust your database settings when you move your db from prod towards dev.  For moving configuration from dev to production, many folks use features; you might also want to look at ctools export bonus, which is built on much of the same technology.


Creating view using Index results in "plugin does not exist"

I now believe this is some type of caching issue, though I'm not sure why.  Originally I thought uninstalling a particular module fixed the issue, but the "plugin does not exist" error appeared the next day when creating a new view. Clearing the cache seems to clear the error, which is a good enough workaround for now until I have more time to dedicate to this.


Where do I find the vocabulary ID ($vid)?

Actually you can use:

$vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$vid = $vocab->vid;


How can I get the content type of a node given its node ID?

If the value returned from arg(2) is a node ID, you can load the node with node_load(). This will return a node object, which contains its content type.

$node = node_load(arg(2));
$content_type = $node->type;


Open an image in a new pop up window when form submit button is clicked in Drupal 7

You can give like this:

$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#attributes' => array(
            'onclick' => 'function_name()'),
        )
    );


You can try changing the settings data on the ajaxSend event.

$(document).ajaxSend(function(event, request, settings) {
  settings.url = '/views/ajax';
});


Attaching assets if the page contains a table

'#type' => 'table'

OK, so I tried it out in a Vanilla D8.6 with a custom module like yours and the Bartik theme enabled. I placed hook_element_info_alter in the custom module and checked what Kint ksm($info) would return me (matching the code from your question that would be ksm($types)). I visited the front page and I saw 'table' in the array so I thought there must be a table on that page somewhere and the library should get attached. But it didn't. Because there actually was no table.

Only after I added a custom block to the custom module, placed the block somewhere prominent and let it output some sample code from class Table:

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];
  $build['contacts'] = [
    '#type'    => 'table',
    '#caption' => $this
      ->t('Sample Table'),
    '#header'  => [
      $this
        ->t('Name'),
      $this
        ->t('Phone'),
    ],
  ];
  return $build;
}

And then the library suddenly got attached as documented. So, yeah, everything's fine. You just need to be sure you really have a '#type' => 'table' element on that page. That's all.

'#theme' => 'table'

As @4k4 asked in the comments to your question it seems likely you used '#theme' => 'table' to build your tables. Then attach the library directly like that (snipped copied from the Node core module):

$build['node_revisions_table'] = [
  '#theme' => 'table',
  '#rows' => $rows,
  '#header' => $header,
  '#attached' => [
    'library' => ['node/drupal.node.admin'],
  ],
  '#attributes' => ['class' => 'node-revision-table'],
];

Although in this case you could also make use of hook_preprocess_table to have that pattern applied to all tables you've built using '#theme' => 'table'.

/**
 * Implements hook_preprocess_HOOK().
 */
function my_assets_preprocess_table(&$variables) {
  $variables['#attached']['library'][] =  'my_assets/fancy';
}

<table>

OK, so after we finally found out you put a table as markup into the body field of your node, using CKEditor, here's what's needed to attach your library accordingly.

You can't check for '#type' => 'table' or '#theme' => 'table' at this point, as your table is just markup. So simply check for the existence of a <table> tag. Or even better, check for just <table, because who knows what else attributes can come after that. Pay attention for the two underscores in the function name, and replace body with the machine name of whatever field you need to preprocess.

/**
 * Implements template_preprocess_field__FIELD_NAME().
 */
function my_assets_preprocess_field__body(&$variables) {

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  $items = $variables['element']['#items'];

  $value = $items->first()->getValue()['value'];

  if (\strpos($value, '<table') !== FALSE) {
    $variables['#attached']['library'][] = 'my_assets/fancy';
  }
}


All hooks by default go in the .module file, so it should go in the .module file.

It's not clear what you mean by "run my module", as modules aren't 'run', so I can't really give any more info.


How to scp one file to remote using drush?

I've found the following workaround useful:

cat my_rsa | drush @remote ssh "cat > ~/.ssh/my_rsa"

It'll send content of the file directly via ssh into the file.


You can use these two modules:

Title

  Do as follow:
  In content type field management, use replace button to turn title core into a text field; set up the field to be in a full html text format;
  In content type display management, show new title field;
  In file node.tpl do not print the core $title;

HTML Title

  It let you insert some sort of BBcode into the title. I've never used it and I don't know if there is a BBtag for


Programmatically get field values of fields added to custom entity

The column for an entity reference field is target_id, so you should just need to replace the getter with:

public function getProjectId() {
    return $this->get('project_id')->target_id;
}


If you want to reduce the content indexed by search engines use your robots.txt file to instruct them to ignore certain paths or sets of paths.

Many Drupal projects use Path, Pathauto and one of redirect modules to automatically assign aliases to links. Usually, the path pattern is set to automatically replace node/[nid] with something like content/[title]. Globalredirect or Redirect modules permanently automatically redirect from the default Drupal query to the alias, so there is nothing else you have to do (no need to edit Robots.txt unless you want to exclude some of them).

Path aliases can be generated automatically for existing content so it will work for your case and also in the future.


Form with manged_file filed is not submitted?

I found the reason of this problem finally.
It was as a result of jQuery code mistakes.

in form submission, I tried to disable submit button immediately after clicking.
I had to change the coding because set button disable causes this problem.


I ended up using contextual filter instead of filters. I added:

Content: Created date

Provide default value - php code

return date("d", strtotime("-1 day"));


1. First of all, The step you are showing, at that step you can easily change the machine-name, See in following image, where I have created the block 'Main Page Content' and it is not allowing me to go ahead, before changing the block machine-name. Hence, you can easily change the machine-name here. Hence there is no problem in editing the machine-name.

Secondly, if system is saying, you can not use capital letter, then simply you can't as system designed in that way.

2. Main Page Content Why you want to give your block name Main Page Content title, Block with same name with machine-name theme_content has already been provided by the default Drupal 8. So, why you wan to create the another block with same title and same kind of machine-name. That block(Main Page Content) is used for displaying the main content which is not supposed to be changed. If you want just create the other custom block and place it in CONTENT region.

3. Once the machine-name is stored in the database, practically you can't change that. please read the accepted answer of this Question How do I change the machine name of a field once it's been created.

4. Till which step you can edit machine-name: After creating the block and before final saving, you can see the edit link in the following image. So at that time you can change the machine-name. And before placing it in the region. Once you places block and it gets enabled, after that you can not change the machine-name.


Add a role to a user during MailChimp subscription

Try using rules you can add a condition and put action to it.
condition -> when to activate your rule: when a person subscribes
action-> add user role.
Hope this solves your problem


Drupal 8 requires PHP 5.5.9. If you are using PHP 5.2.9, it doesn't recognize as valid a line like use Drupal\Core\DrupalKernel; since namespaces were introduced in PHP 5.3.

If you were already running a stable release of Drupal 8 before, check you didn't change in someway the PHP version used from your site.


Webform multiple files with descriptions

You can allow node submission for users. Create a content type, go to permissions tab and allow content type to be submitted by particular user role. Under content type go to manage fields and create an image field by allowing multiple images to be uploaded. Now use Form block module to display node form on front end for users. This will be easy for you as well as you can get the submitted content easily in views to display them as per your requirement.


You could use hook_preprocess_page() in a module:

function MYMODULE_preprocess_page(&$variables) {
  if (arg(1) == 'add' && arg(2) == 'add-student') {
    $types = node_type_get_types();
    $name = $types['add_student']->name;
    drupal_set_title("Add $name");
  }
}

I'd suggest setting your content type's display name to "Student" rather than "Add Student." You should just need to put the machine name of your content type in place of 'add-student' and 'add_student'


What is the best way/api to load a node by node content type and a field value?

In both D6 and D7, you can use Views. Explaning all of Views is out of scope for this answer, but you can either add two, "Filters" one on content type, and one on field value. This however will require reconfiguring the View if you want to change the score, or type. If you add the same filters as "Contextual Filters", or "Arguments", depending on your Views version, the values can be pulled from the URL. This will allow completely different listings with a single view.

Two URL examples for using contextual filters:

example.com/results/easy_assignment/50
example.com/results/hard_assignment/75

In D7 you have entities, and could in code do:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'assignment')
->propertyCondition('status', 1)
->fieldCondition('field_assignment_score', 'value', 65, '=');
$result = $query->execute();


theme_image() by default looks like this:

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

so, if you are storing the images in this field in an identifiable place, eg, you can look at $variables['path'] and figure out they are the ones you want to always look for on a specific host, you should be able to do something like this in your theme:

function MOTOTHEME_image($variables) {
  $attributes = $variables['attributes'];

  if (dirname($variables['path'])==WHEREIKEEPTHISFIELDSIMAGES) { // on d7 this might be a uri so you might need to get fancier than dirname() :)
    $attributes['src'] = // http://.....
  } else {
    $attributes['src'] = file_create_url($variables['path']);
  }

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}


This is the way I would approach this. I would create the two views using a block display. And place the two blocks display on the page created. Then you can create the custom page file and theme it. You can add the blocks using the default blocks page (admin/structure/block), or the context module.

In case you do not know how to create a block display, on your views UI page,


State of form element based on global config

You can unset a form element using this code :

var x = variable_get("VariableName");
if(x confirmed some condition)
{
  unset($form[$ELEMENT_YOU_DESIRE_TO_HIDE]);
}


How can I pull slideshow filenames from the database using jQuery?

Here's another option - how about create a view to generate JSON for the image paths and then pull that into your JS?

The module "Views Datasource" can output your view as JSON.  You would need to create a view that pulls the images from the content type you are using and make sure that the image is rendered as a URL (rather than the actual image tag).

From there you could update your JS to pull the JSON from the view output.  Create a loop that sets a variable with the JSON data (as a comma separated list) and use that variable within your backstretch function.

I can't provide any code examples at this time, but hopefully that can get you started down a path.  Here is a stackoverflow article that provides examples on how to convert JSON to CSV and store that in a variable:

https://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable


What would the main use of this? If a content is kept as unpublished it is similar to saving the draft. It will not be visible to anyone else except the author and admin and any one else you have given permission to view the same. So this in itself is a good option. The save as draft module does the same thing it creates a button to uncheck or check the publish unpublish checkbox.

If you are looking for a workflow kind of feature then workflow module would be a better option. where you can define different workflow status and give different users permission to access the node in each workflow state.


Custom theme function with drupal render

What I wanted to do is to get the html through a function and not a template. So actually there is no need to set the variables, just the 'render element' did the trick.

function custom_module_theme() {
  return array(
    'custom_module_link' => array(
      'render element' => 'element',
    ),
  );
}


How to prepopulate a term reference field with multiple values on a new form?

Answering my own question:
1) First aspect is to feed the data correctly to the term reference field. The magic formula I found is:

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);

where $bidule is a the string of taxonomy term (not its taxonomy id).

2) If there are multiple elements in the field_ad_tags, then I had to create a loop to place them all one after the other in a string. It was important to have the exact wording of each taxonomy term for the field to recognise which tag it is and to separate them with a comma. Here is my final code:

$bidule = '';
$i=0;
foreach ($node->field_ad_tags['und'] as $truc => $value) {
        drupal_set_message('<pre>$truc '. print_r($value, TRUE) .'</pre>');
        $term = taxonomy_term_load($node->field_ad_tags['und'][$i]['tid']);
        $name = $term->name;
        $bidule= $bidule.','.$name;
        $i++;
}
$bidule=substr($bidule, 1); // Remove the first character ','

$form['field_revactivities'][LANGUAGE_NONE]['#default_value'] = array($bidule);


How to check Commerce product type of current line item in Rules?

If the data about a product are not available when processing a "line item", you can make them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Here is a blueprint of what you need to do:

Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "Some details about this product"), e.g. by also using either of these available tokens that seem to be what you're interested in:

[product-fetched:type] - The machine name of the product type.
[product-fetched:type-name] - The human readable name of the product type.

Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".

PS: I assume this question is about D7.


Answered at https://www.drupal.org/node/2829462 - as mradcliffe says, this is a YAML syntax error.


I have overcome by using the Migrate CSV plugin, now i can able to import large body content.


Display the results of a form submit on the same page just under the form

As suggested in the comment the SQl query were made on the hook_form and the hook_form_submit contains only the $form_state['rebuild'] = TRUE;. Detailed code is as follows:

function form_example_form($form, &$form_state) {

//your form fields or items

$form['submit_button'] = array(
 '#type' => 'submit',
 '#prefix' => '
',
 '#suffix' => '
',
 '#value' => t('Find my store'),
 '#attributes' => array('class' => array('btn btn-primary')),
);

/*-----Query database code Start--------*/

if(isset($form_state['values']['item-name'])){
  //get the values to variable
}

if(isset($zip_code)){

//setup the sql query

if(isset($sql3)){
  $result = db_query($sql3);
}
$records = $result->fetchAll();
$tot_records = count($records);
}

if(isset($tot_records)){
 if($tot_records>0){

  $form['result_table'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#markup' => '
Store Name	Address	City	State
',
  );

  $i=0; $j=0;
  foreach ($records as $record) {

    $record_in_array = json_decode(json_encode($records[$i]), true); //Convert object to array

    $form[$j]['result_table1']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $form[$j]['result_table2']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name1'],
    );
    $form[$j]['result_table3']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name2'],
    );
    $form[$j]['result_table4']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name3'],
    );
    $form[$j]['result_table5']= array(
      '#type' => 'markup',
      '#prefix' => '',
      '#suffix' => '	',
      '#markup' => $record_in_array['sql column name4'],
    );

    $form[$j]['result_table6']= array(
      '#type' => 'markup',
      '#markup' => '
',
    );

    $i++;
    $j++;
  }

  $form['result_table7']= array(
    '#type' => 'markup',
    '#suffix' => '
',
  );

  }
 }

/*-----End Query database code--------*/

return $form;

 }

 function form_example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
 }

Hope this helps!


How to disallow users to edit their content after it was submitted for review?

You can look to the workflow module to implement a suitable workflow and permissions.


How to make Drupal Commerce tokens available in the Commerce Message module?

Even though your question is about the "Commerce Message" module, at its core your question relates to the Message module. And since you are using the Rules module, you can make the missing tokens (= the commerce standard tokens, as in your question ...) available by using the Replacement patterns for each message type.

So the answer to your question is "Whatever token you're missing, just make it available via Rules, by creating a replacement token for them". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.

These Replacement tokens are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".


Replace date by text in date_popup default value (or in-field label)

Try using the placeholder html5 attribute by removing the #default_value from the array.

So, take out....

'#default_value' => $date,

and replace with

'#attributes' => array('placeholder' => t('Please select date')),

or, as you already have attribute, add it to that


How to customize order confirmation e-mail

Order receipt emails are powered by Twig templates, just like regular pages. This helps us avoid the inflexibility of tokens and their lack of conditional support ("Only show the Shipping information heading if the token has data"), which were big problems for D7 sites.

You can override the commerce-order-receipt.twig.html template in your theme to customize it.

See https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/order/templates/commerce-order-receipt.html.twig


How to show Comment Count in node template?

Use this code in your theme's YOUR_THEME.theme file:

function YOUR_THEME_preprocess_node(&$variables) {
  // Note: you'll probably want this only for certain content types.
  if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['comment_count'] = $variables['node']->get('YOUR_COMMENT_FIELD')->comment_count;
  }
}

And then you can use it in your node.html.twig file like so:

{{ comment_count }}


How can I make a node template that works on any url I specify?

Probably best to add a template suggestion rule to hook_preprocess_node, to control which templates are looked for.

e.g, in template.php

/**
 * Implements hook_preprocess_node
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'article') {
    // Regex replace anything not alphanumeric with underscore _ in node title
    $title = preg_replace('/[^a-z0-9]/', '_', drupal_strtolower($variables['node']->title));
    $vars['theme_hook_suggestions'][] = 'node__'. $title; // Use title in template suggestion
  }

}

Then you could use a template like

node--my-node-title.tpl.php


This is the fix for the issue.

The code taken from duplicated issue in https://stackoverflow.com/questions/36359917/docker-gd-module-for-php-7

Please take this with heaps of grain and salt, and modify the script accordingly.

# Install GD
RUN apt-get install -y libfreetype6-dev libjpeg62-turbo-dev libpng12-dev
RUN docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/
RUN docker-php-ext-install gd

What is actually happens is your GD library is installed BUT without JPEG library configured. Your Drupal will be chill saying GD installed but there is hidden requirement that JPEG need to be exist too.

The line 179 in GDToolkit.php:

$function = 'imagecreatefrom' . image_type_to_extension($this->getType(), FALSE);

Causes the function imagecreateformjpeg fails to be executed.

Hope it helps someone that confused, cant generate thumbnail with limited knowledge of the errors.

:)


I discover that the reason is because of the localhost. Once life the form is submitting by the FormSubmit handler.


How do I count the number of unique visitors to Pages

You can not with only a Drupal instance, it's an architecture issue. But you can use Matomo (former Piwik) for such needs.

If it is a simple scenario, you could get along with setting your own visit-cookie - but you need to program a module for this. And the result will be fuzzy cause of numerous caching steps.


Hook_form_alter for changing field labels doesn't work of user registration page

Simple Solution just change ['0']['#title'] by [0]['value']['#title'].

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function MYMODULE_form_alter(&$form, Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    if ($form_id == 'user_register_form') {
        $form['field_user_first_name']['widget'][0]['value']['#title'] = 'First Name';
        $form['field_user_last_name']['widget'][0]['value']['#title'] = 'Last Name';
        $form['field_user_phone_number']['widget'][0]['value']['#title'] = 'Phone Number';
        $form['field_user_country_of_residence']['widget'][0]['value']['#title'] = 'Country (of residence)';
    }
}

This solution a little bit complicated.
After i test your code, i did some search, i found this Post say

  It is apparent that we modify any form in drupal by implementing hook_form_alter(). But there are cases when even the hook_form_alter() cannot offer a solution in altering the form fields.

I tried to use hook_element_info_alter as it suggested to alter fields.
In your case Here is the code bellow.

/**
* Implements hook_element_info_alter().
*/
function MYMODULE_element_info_alter(&$type) {
  if (isset($type['textfield'])) {
    $type['textfield']['#process'][] = 'MYMODULE_process_textfield';
  }
}

/**
* Process Callback Function
*
* Callback to process the User fields.
*/
function MYMODULE_process_textfield($element) {
  //- get the current route name
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name == 'user.register' && isset($element['#array_parents'][0])) {
    switch ($element['#array_parents'][0]) {
      case 'field_user_first_name':
        $element['#title'] = 'New first name label';
        break;
      case 'field_user_last_name':
        $element['#title'] = 'New last name label';
        break;
      case 'field_user_phone_number':
        $element['#title'] = 'New phone numbe label';
        break;
      case 'field_user_country_of_residence':
        $element['#title'] = 'New country of residence label';
        break;
    }
  }
  return $element;
}

Note : all the four fields should be of type textfield Text (plain), otherwise you should add another process to other type, see the example in the article for password_confirm type.


How to get GD2 generate PNG8 when resizing PNG8 images

GD2 indeed doesn't check what palette size is the source image. From GDToolkit.php:

// Always save PNG images with full transparency.
if ($this->getType() == IMAGETYPE_PNG) {
  imagealphablending($this->getResource(), FALSE);
  imagesavealpha($this->getResource(), TRUE);
}

The only way I could hack PNG8 in there was:

// Always save PNG images with full transparency.
if ($this->getType() == IMAGETYPE_PNG) {
  imagealphablending($this->getResource(), FALSE);
  imagesavealpha($this->getResource(), TRUE);
  imagetruecolortopalette($this->getResource(), TRUE, 256); // ← hardcoded 256 hack for PNG8
}

I couldn't find a way of determining the palette size of the source image. So by leaving that hack of mine in there the risk is that PNG24 source images will be saved in the styles/ directory as PNG8 files.


how to add newsletter subscription during registration?

you can achieve this either by using Mailchimp Module

                          OR(by custom coding)

You can alter your registration form using hook_form_alter. Now in your form you can add add two new elements that is :-

A checkbox saying- Signup to receive alerts.
A text field to capture email address.

Now you can override your form on submission and pass the email captured above to mailchimp function that adds users to email lists via ajax call.

Hope this helps!!!


Link to nodes in WYSIWYG Editor and Domain Access

See the LinkIt project.

Its flexible API should let you hook into the node listing logic it uses to inject SQL to group node listing by Domain. You should be able to make a plugin with it ... I see no existing solution off-hand (I've used LinkIt and DomainAccess, but not had users linking around sub-domains from the WYSIWYG. My domains were very separate from one another).


Both of the modules mentioned (Taxonomy display and TVI) that make Taxonomy term pages easier to configure rely on Views, so you do need to have the Views sorted out before you can assign different Views to different Vocabularies. These modules don't replace the "Views magic".

If you don't use these modules that override how term pages are displayed the "Taxonomy term" Views that comes out-of-box handles all of the terms equally. BTW "Taxonomy term" Views is of the content type (not the taxonomy term type, the name can be confusing a bit).

But the "Taxonomy term" Views can be changed to handle different Vocabularies differently. This change can be made in the Contextual filter in the validation settings. Then you can clone that page, give it a different path, and adjust the contextual filter validation to a different Vocabulary.

Both of your cases can be handled with the modified "Taxonomy term" views. Using the "Summary" option in the contextual filter for the Taxonomy reference field will list the terms present in the views results. When you click through those links you see the content listed. Although your "No results behavior" solution also works.

You can get the Parent info into your path through another Contextual filter (Taxonomy Name), that you can get after adding the Relationship for the parent term in your Views.

It's all in the Contextual filters and perhaps some Relationships to create your cases. There are a lot of answers here relating to those so you can search and learn from them.

It is also mentioned in the comments you can use the theme templates to override how Term pages are displayed, when you're not using the Views to build those pages, but you'll probably still use Views to build blocks to put in those templates, unless you know SQL and can create better queries manually.


Display members of Organic Groups that are members of a given Organic Group in Views

What you can do is add a relationship to the View for the User entity (current user). From there, you have the ability to create filters based on the OG group(s) that the user belongs to.


How to limit access to vocabulary term by role?

Have you tried taxonomy_access_fix? It allows you to manage permission for each vocabulary for each role.


How to create a unit test for a class which uses a trait?

Following on Bedir's answer, here is an example.
I have a test that is using the class DurationService. DurationService uses the StringTranslationTrait as follows:
class DurationService implements DurationServiceInterface {
  use StringTranslationTrait;
  ...

To test this, I am doing the following (note, using a class that extends UnitTestCase):
$duration_service = new DurationService();
$duration_service->setStringTranslation($this->getStringTranslationStub());

This calls StringTranslationTrait::setStringTranslation() passing it the response from UnitTestCase::getStringTranslationStub().


Templating. Check if entity is comment or node?

Assuming this is for Drupal 7, there isn't an official way to do this, unfortunately. See core issue: https://www.drupal.org/node/1042822

One possible workaround is to check if the entity has some known fields that you are aware of. This obviously wouldn't be a generalized solution - but might work for you.


Change Field Order of Content Type in the database

Yes, I saw this too. The language form element was added by locale module in code. If you want to change the weight of this element you can create your hook HOOK_form_node_form_alter() and add #weight for $form['language'].


How to add library to Paragraph bundle using hook_preprocess_theme?

You have to do like this instead:

$variables['#attached']['library'][] = 'my_theme/my-library-name';

So you attach the library directly to $variables instead.


How to make view source code in single line

A couple modules you might find interesting.

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

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


admin only can log from a certain country

I would use the Smart IP module (https://www.drupal.org/project/smart_ip), you can add an extra validation on the login form that checks the country (https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_validate/7).

You should check if the username exists on validation, when it exists you can check it's role and when it's the administrator role you make sure only users with the IP of your selected country can log in as admins.

There might be easier ways.


How do I get the administrator to automatically flag?

FlagServiceInterface::flag takes an $account argument:

The account of the user flagging the entity. If not given, the current user is used.

So for example:
$flag_id = 'moderate_node';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
$account = \Drupal\user\Entity\User::load(1);
$flag_service->flag($flag, $node, $account);


How to remove the top, bottom, left... region when theming a node in Drupal 6

I think You need to create specific page.tpl.php for your content and don't include these regions in the template. You name them page--YOUR_CONTENT_TYPE_MACHINE_NAME.tpl.php according to this thread. You can also try this module


Adding content to Paragraph Date Field Drupal 8

Use the global constant DATETIME_DATETIME_STORAGE_FORMAT to format the date:

// If the time is in a different timezone then adjust it to UTC before you save it
$date->setTimezone(new \DateTimezone(DATETIME_STORAGE_TIMEZONE));

$paragraph = Paragraph::create([
  ...
  'field_date' => [
    'value' => $date->format(DATETIME_DATETIME_STORAGE_FORMAT),
  ],
]);

Edit

For Drupal >= 8.5: Global constants in datetime.module are deprecated and DateTimeItemInterface has been introduced.


My guess is you're experiencing a common issue with product permissions due to a relationship you've added from the line item to the referenced product. Open your View's advanced settings fieldset, and in the Query settings menu disable SQL rewriting. This will bypass the normal entity access check to see if a customer has the permission to directly view the related product data, which is fine for this View since we know the products in the cart will always come from line items the customer has created through Add to Cart forms.

See also: https://drupal.org/node/1276450


How do exposed views filters make their queries URL safe?

Use the url() function to encode your URLs.

url("what is going on around here, anyway?");

this will return the string '/what%20is%20going%20on%20around%20here%2C%20anyway%3F'

You could also use this to get the full, absolute URL.

url("what is going on around here, anyway?", array('absolute' => TRUE));

You may also be interested in the l() function if you need html output.


How to use drush download file plugin (drush_dlf) project page has no information

If you would like to install the Drush extension drush_dlf, run:

drush dl drush_dlf

If the module you download is a Drush extension (has a .drush.inc file but no .module file), then Drush will put it in $HOME/.drush, where it will be findable by Drush.

If the module you download has a .module file, then Drush will put it in the appropriate modules directory (DOCROOT/modules for Drupal 8, or DOCROOT/sites/all/modules for Drupal 7). In this instance, the command will only be available for that one site.

To stipulate where the downloaded extension should go, you can add --destination=$HOME/.drush (or some other location). Use caution when doing this with any extension that has a .module file, though, as some of these are designed such that they only work when their module is available and enabled.

Finally, note that Drush caches the location of all of the available Drush extensions.  If you add a new extension, you must run drush cc drush before your new command will be available.  Drush does this automatically if you use drush dl to install the extension, but you must do it manually if you copy the files into $HOME/.drush yourself.

Finally, with regard to Drush Download File, the behavior it purports to provide could also be implemented with a simple shell script that simply called drush dl repeatedly, as Drush dl will already place the files where they belong.  Using drush make or composer is generally preferable, but just using drush dl directly is an option if you don't want to do that.


Custom entity to load another custom reference entity fields

You might want to take a look at Entity metadata wrappers. They are not really efficient as they load even more data, but they simplify the working with entity properties and fields and also resolve nested entities (so you would be able to do something like $car->field_car_type->field_length->value()).

But under the hood (a car joke :D), it still performs an entity_load to get the values. It is less code for you though.

To answer your question:

Drupal makes the assumption a field is always attached to an entity, it would be very difficult to properly load some fields without actually loading the entity (I suppose that is what you are after). The function which loads field values and attaches those fields to entities (field_attach_load) already required loaded entities as input. (This function is often called during entity_load). You could attempt to replicate its behaviour without loading the entities, but you will probably run into a lot of issues.
The same applies for fetching a single field's value; field_get_items() and field_view_value() also expect a loaded entity. So my advise would be to just load the entity, possibly using entity metadata wrappers as they make your life easier.


I'm having a problem getting Context to work properly

I had the same problem with the "blocks" section.

In the blocks section, you need to select the block(s) you want to add in a template region from the right panel where there is a list of all the blocks. Then click the + sign of the corresponding region.

As for the condition problem, that is weird have you tried in different browser?


How can you prevent a Webform from going to a confirmation modal if remote post handler fails in a service response?

I believe it is too late to halt the Webform with validation errors once it is past the validation phase ie. in postSave(). If you are expecting validation errors on user input however, then you could move the service call to WebformHandlerBase::validateForm() and then save the service response in the $form_state object if you need it.
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    parent::validateForm($form, $form_state, $webform_submission);

    try {
      $response = $this->doServiceRequest()
    }
    catch (\Exception $e) {
      $form_state->setErrorByName('foo', $e->getMessage());
      return;
    }

    // Save service response output.
    $webform_submission->setData($response->getData() + $webform_submission->getData());
  }

Note: This probably goes against the design of the RemotePostWebformHandler, but I think it could work..., or you could directly extend WebformHandlerBase instead.


How to assign a user a role during registration using Rules and Profile 2?

If "...the role is not assigned to the user..." (as in your question), it must be that your Rules Action is not performed. And if that's the case, then that must be because your Rules Condition is not satisfied (true).

And the reason why your Rules Condition is not true, is pretty sure because you should add another Rules Condition Entity has field (related to your additional field in the Rules Condition you already have). And make sure to add that Entity has field condition BEFORE the Rules Condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


New site appearing in folder structure after first hit on homepage?

It would be good if you ask HostGator support guys to assist you through your problem. Got to Support and create a support ticket.


Loading a block should be in theme context, because block visibility configured by theme, here is an example to how load system_breadcrumb_block block in your active theme.

   use Drupal\block\Entity\Block;
    // Get block ids.
        // This will return block ids by theme like the following
        /*  [
              "bartik_breadcrumbs" => "bartik_breadcrumbs"
              "seven_breadcrumbs" => "seven_breadcrumbs"
            ]
        */
        $ids = \Drupal::entityQuery('block')
          ->condition('plugin', 'system_breadcrumb_block')
          ->execute();
        // Get the active theme name.
        $active_theme_name = \Drupal::service('theme.manager')
          ->getActiveTheme()
          ->getName();
        $my_block_id = '';
        foreach ($ids as $id) {
          // Check the if the id start with theme name.
          if (strpos($id, $active_theme_name) === 0) {
            $my_block_id = $id;
          }
        }
        // Load Block.
        $block = Block::load($my_block_id);
        // Get the block visibility array
        // Something like
        //    [
        //      "user_role" => [
        //        "id"    => "user_role",
        //        "roles" => [
        //          "administrator" => "administrator",
        //        ],
        //      ],
        //    ]
        $visibility = $block->getVisibility();
        $currentUser = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        /**
         * TODO: Do your visibility check
         */
        // Example to check if the user has the access by role
        $has_access = FALSE;
        if ($visibility['user_role']['roles']){
          foreach ($visibility['user_role']['roles'] as $role => $name){
            if ($currentUser->hasRole($role)){
              $has_access = TRUE;
            }
          }
        }
        dpm($has_access);


Good question (+1) but be aware that this is a known issue about the OG Menu module.

There are a few issues related to it, and issue 2348821 contains a great summary of these (related) issues. It also includes some patches (the patch in #9 seems to be the recommended one to consider).

The issue is sill in status "needs review", so maybe you want to consider participating in that review? I.e. check if that patch works for you, and update the issue with your review results?


What is the correct way to cache blocks by language?

You should use the languages context, don't use tags here.

Like this: '#cache' => ['contexts' => ['languages:language_interface']],

You'll find more here: https://www.drupal.org/developing/api/8/cache/contexts


Allow all OG members to view/edit all content

Organic groups controls (Organic Groups Global Permissions) are different from your site permission, roles etc. To allow authenticated users the required permission, configure the organic groups global permission:

Navigate to: Configuration -> Organic Groups Global Permissions (drupal/admin/config/group/permissions), here you will find the controls over who can view and edit nodes and fields on your group pages.

Few reference for the organic groups permission:
http://vimeo.com/32398425
http://vimeo.com/32398425
https://drupal.org/node/2014929
https://drupal.org/node/2014793


How to query all content type and add as checkbox for custom form?

This was inspired from @leymannx comments.

I changed the '#type' to checkboxes.

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
 $types = \Drupal::entityTypeManager()
   ->getStorage('node_type')
   ->loadMultiple();

 foreach($types as $type) {
   $content_types[$type->id()] = $type->label();
 }

 // Need help setting this up so that the options are content types.
 $form['enabled_content_types'] = [
   '#type' => 'checkboxes',
   '#title' => 'Enabled Content Types',
   '#description' => 'Run preprocess for all enabled content types only',
   '#options' => $content_types,
 ],
}


Allow user to edit commerce line item at checkout

Yep it seems my proposed solution should do the trick.

I somehow didn't previously see the Commerce Cart Form Checkout Pane module, which does pretty much exactly what I was asking for.

I also used the Commerce Line Item Cart Form module to add line item fields to the form.

[EDIT]
Turns out that those two modules I mentioned don't seem to play nice together so I'm just going to create a custom checkout pane with a custom form that updates the line item in it's submit function.


Remove that $comment->save(); Because you are already in the save process and you will trigger it over and over again with this.


How to use 'session' to check path history of user

if you just want to track user visiting there are some modules ready for that like user visits .

or if you want to do something and need to write a module for that then hook_node_view will fire when user is viewing a node . you can implement it like below :

function YOURMODULENAME_node_view($node, $view_mode, $langcode)
{
   global $user; //user data is here
}

now you can do what you want with user.


use facetapi or faceted_search module i think it helpful..


I have solved the problem this way.
(1) I created a View to show desired user information.
(2) Then, I added a 'Contextual filter' to point to the user being viewed. (with the options "User ID > Provide default value > Type: User ID from route context")
(3) Then, I selected 'REWRITE RESULTS' and "Override the output of this field with custom text". As a result replacement tokens become available for user fields. I used that for formatting the Information according to the requirement.
Then, I placed this View block at the desired place.


View to display nodes with a random term

I would set up an argument (D6) / contextual filter (D7) to filter the view results based upon a taxonomy term, and then for the argument/filter value, select the PHP option for providing the default, and in there randomly return one of your taxonomy terms.  Without actually testing the code, I would imagine using array_rand() would make this rather trivial, eg:

$terms=array('foo','bar','baz');
return $terms[array_rand($terms)];


Include external JS/CSS libraries in a module?

Quoting this blog post

Core API changes in Drupal 8
The drupal_add_js() and drupal_add_css() functions for manual inclusions of JS/CSS files have been removed in favour of library definitions that properly declare their dependencies. As a result of this, all modules and also themes have to declare their libraries in order to include JS and/or CSS files. During the development of D8 the way of declaring a library evolved from a renamed info hook (hook_library_info()) to finally using YAML (like in many other places in D8) by describing the libraries in *.libraries.yml files. The info hook finally was removed fully. See the change record for more information. The new hook_library_info_alter() hook is of course still there.
Another big change is the usage of Composer for dependency management, like many other modern frameworks do. Although Composer is primarily for PHP libraries, it can be used for JS libraries too. Using Composer not only spares you manually downloading the library from Github, etc and afterwards manually extracting and uploading the files to your server, but also eliminates the error source of placing the files into the right directory structure. (Note: Composer integration is not fully finished yet, see: https://www.drupal.org/node/2372815)


How to see the filenames imported by the Feeds module?

Imported files are stored in default/files/feeds by default I think so you could test on that first.

Feeds does create a watchdog event but it doesn't persist.

If you attach feeds to a node then you have several advantages. You can re run the import. And more interestingly you can access the node via Views and probably Rules. With those two you could build something with a Rules trigger event on the node save or Feeds import that would check for an existing node with a matching file.

If you can't get that working then post back and I'll try to make an example.


Cant display error message in custome form!

Hope this will help you.

In Drupal 7, just add this line in your custom template file

<?php if ($messages): print $messages; endif; ?>


Theming Print PDF module output when used on non-content page (views)

The .tpl file for a View with machine name "myview" would be views-view--myview--page.tpl.php. Following that convention and what the print module reports, I would try creating a .tpl called print.views-view--myview--page.tpl.php. Include <?php print $content; ?> in this file, clear Drupal's cache, visit the View's print page, and see if it registers.

Edit: Try and throw something like this in your theme's template.php file:

function mythemename_preprocess_node(&$vars) {
  // Something to make sure they're on your View.
  if (arg(0) == 'my_view' && arg(1) == 'print') {
    // Add a new template suggestion...
    $vars['theme_hook_suggestion'] = 'print__view_page'; // and then make a print--view-page.tpl.php file.
  }
}


Yes it should be that easy, Drupal doesn't tend to mind what protocol it's served under. I say "should" because who knows what contrib/custom modules you have that might be doing who knows what, but in my experience contrib tends to be pretty good and you can sanity check the custom modules before implementing anyway.

You'll probably want to un-comment the http -> https redirect in .htaccess (or implement similar in the vhost if you're using something other than Apache), that way any errant insecure requests will be upgraded before they hit Drupal.

A useful check is to crawl a test version of the secure site (e.g. with Integrity on a Mac) and look for requests for insecure resources. If you see any, you can check the referring URLs to find out where the insecure request comes from (link, iframe, script tag, etc), and use that as a jumping point to find out which module/sub-system is responsible.


Difference between hook_node_view() and template_preprocess_node() with seeing messages

It is the execution order. hook_node_view() acts on the node object as it is being assembled. When template_preprocess_node() is called, the node is ready to be rendered. For instance you may use template_preprocess_node() to change the date format.


Adding a loading indicator to form submission module

AFAIK there are no OOTB features in Drupal yet but perhaps you can implement ProgressButtonStyles by Codrops. See https://github.com/codrops/ProgressButtonStyles for more info...


How to attach a library to a page controller that returns a plain Symfony response?

After rendering of $build the attachments have bubbled up to $build['#attached'] and you can add them to a response, which implements AttachmentsInterface, for example an HtmlResponse:

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new HtmlResponse();
$response->setContent($html);
$response->setAttachments($build['#attached']);
return $response;

To place the libraries on the page you have to enclose the page in an html render element

$build = [
  '#type' => 'html',
  'page' => [
     // content with attached libraries
  ],
];

or implement the placeholders where the attachment will end up in a custom template, see template_preprocess_html().


What is the use of "Add view from template"?

Modules give you some templates to work with instead of having to figure out the dirty details yourself.

For example:

You have the image module installed, so they give you a gallery template to work with. of course you're not obligated to use it but it's there.

If you download the Calendar module it will give you a bunch of templates as well.

There are several modules that give you templates to work with. And if you write your own custom modules, you to have access to create templates for users to use if you wish to.


Show block menu links only on certain pages

Without any additional information about the links inside your menu, it seems the easiest way to structure this is to create 3 separate menus, even if some of the links inside them are repeated.

What sort of links are those? Maybe you can use Views to create a Block that reacts to the page it's on to filter out the relevant links.


Duplicate Entry for Video Embed Field which not allow to save node

field_sql_storage_field_storage_write() function exposed by Drupal helps to update desired single field only. Calling this will not invoke any hooks.


image style (imagecache) images are not being created

The problem was fixed when I changed the theme to another one, and back, as per @MPD suggestion.


Change default Taxonomy value on form via form alter in D7

It'll be something more along the lines of:

$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = $taxTermId;

If the field is a multi-select you would wrap the default value in an array, but there's no need to set a key for it:

$form['field_mytax_reference'][LANGUAGE_NONE][0]['#default_value'] = array($taxTermId);

Have a look at Why is hook_form_alter() so messy? for a bit more info.


CKEditor Link a content with rule as a hypelink with title and url to a custom field

You don't want to use PHP Filter. That's for embedding PHP code into a Drupal content field and is not what you want (unless you're willing to give your content creators access to PHP code that could potentially break the site).

You want to implement 2 things to provide your custom functionality in a Drupal module:

Provide a custom plugin to CKEditor: You'll need to build your own CKEditor plugin which will do the work of building your custom markup (e.g. internal URL, title, mapped field, uid, etc.) to embed into CKEditor, You'll need a custom module to define it via hook_ckeditor_plugin() in D7 (or a CKEditor plugin in D8), then enable it in the Drupal CKEditor module settings.
Provide a custom input filter: After your CKEditor button provides the markup for your custom link, you'll need a custom input filter so you can process the CKEditor markup for display that depends on your requirements. This can be defined in D7 with hook_filter_info() (or a filter plugin in D8). Once this input filter is enabled for your text format, it should be able to post process the information (e.g. internal URL, title, mapped field, uid, etc.) that CKEditor plugin embedded in its markup so you can render it accordingly.


How to show/hide a link based on a permission?

By default, Drupal will hide all menu items that the user doesn't have access to, so the easiest thing to do, it to require the selected access for the page that the menu item is linking to.


The error message occurs because the command must be drush.phar and prefaced by the php command. In the same folder as Drush Launcher, you'd have to run php drush.phar to get it to work. Elsewhere, you'd have to run php /path/to/drush.phar (which can be just as, if not more, annoying that vendor/bin/drush).

To get it to work, create a folder called drush.bat in the same folder as drush.phar and include the following two lines of code:

@echo off
php %~dp0\drush.phar %*

This file is executed by the command drush since it is in your PATH and will then execute the proper php command passing the correct parameters. You'll then be able to run drush from anywhere on your computer.


How to hide a field group fieldset programmatically in drupal 8?

The field group module is no longer storing grouped fields as a fieldset in Drupal 8. It's storing metadata on each group in an array called #fieldgroups which is used in a pre-render function.
The logic of the module doesn't render the fieldset if all its children elements aren't visible. Hence, you can hide all the children elements to have the same effect. For example:
foreach ($form['#fieldgroups']['group_p_payment']->children as $form_element_id) {
  $form[$form_element_id]['#access'] = FALSE;
}

The logic will have to change if you have nested groups, but the approach will remain the same.
Note that the above code can go in a form alter, but you should ensure that your form alter runs after Field Group does its work.
Here is complete working code, for a module named example in the example.module file:
/**
 * Implements hook_module_implements_alter().
 */
function example_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter' && isset($implementations['example'])) {
    $hook_implementation = $implementations['example'];
    unset($implementations['example']);
    $implementations['example'] = $hook_implementation;
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
 */
function example_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach ($form['#fieldgroups']['group_b_payment']->children as $form_element_id) {
    $form[$form_element_id]['#access'] = FALSE;
  }
}


How do I verify a block can be shown in the current page?

With the help of the answer on this question, Here is a helper function to check block visibility in case someone needs it:

/**
 * Helper function to remove blocks from list who can not show in the current path:
 * based on , pages, user, roles ..
 * @see: block_block_list_alter().
 * @return mixed
 */
function _check_block_list_visibility_on_current_path(&$blocks) {
  global $user;

  // Build an array of roles for each block.
  $block_roles = array();

  $result = db_query('SELECT module, delta, rid FROM {block_role}');

  foreach ($result as $record) {
    $block_roles[$record->module][$record->delta][] = $record->rid;
  }

  foreach ($blocks as $key => $block) {

    // If a block has no roles associated, it is displayed for every role.
    // For blocks with roles associated, if none of the user's roles matches
    // the settings from this block, remove it from the block list.
    if (isset($block_roles[$block->module][$block->delta]) && !array_intersect($block_roles[$block->module][$block->delta], array_keys($user->roles))) {
      // No match.
      unset($blocks[$key]);
      continue;
    }

    // Use the user's block visibility setting, if necessary.
    if ($block->custom != BLOCK_CUSTOM_FIXED) {
      if ($user->uid && isset($user->data['block'][$block->module][$block->delta])) {
        $enabled = $user->data['block'][$block->module][$block->delta];
      }
      else {
        $enabled = ($block->custom == BLOCK_CUSTOM_ENABLED);
      }
    }
    else {
      $enabled = TRUE;
    }

    // Limited visibility blocks must list at least one page.
    if ($block->visibility == BLOCK_VISIBILITY_LISTED && empty($block->pages)) {
      $enabled = FALSE;
    }

    if (!$enabled) {
      unset($blocks[$key]);
      continue;
    }

    // Match path if necessary.
    if ($block->pages) {
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($block->pages);
      if ($block->visibility < BLOCK_VISIBILITY_PHP) {
        // Convert the Drupal path to lowercase.
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
        // Compare the lowercase internal and lowercase path alias (if any).
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }
        // When $block->visibility has a value of 0
        // (BLOCK_VISIBILITY_NOTLISTED), the block is displayed on all pages
        // except those listed in $block->pages. When set to 1
        // (BLOCK_VISIBILITY_LISTED), it is displayed only on those pages
        // listed in $block->pages.
        $page_match = !($block->visibility xor $page_match);
      }
      elseif (module_exists('php')) {
        $page_match = php_eval($block->pages);
      }
      else {
        $page_match = FALSE;
      }
    }
    else {
      $page_match = TRUE;
    }

    if (!$page_match) {
      unset($blocks[$key]);
    }
  }
}

Thank you No Sssweat for pointing me to right direction.


hook_feeds_processor_targets_alter - how to set a value not in the feeds source?

I managed to get the answer to this question.

In MYMODULE_import_filename() we can get the data we want to import, in my case is just a simple text: 'file.csv'.

The simple way to do it is like this:

function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['my_feed'] = array(
    'name' => t('field_filename'),
    'description' => t('This field has the csv file name.'),
    'callback' => 'mymodule_import_filename',
    'real_target' => 'field_filename',
  );
}

function MYMODULE_import_filename($source, $entity, $target, $value, $mapping) {
    $my_filename ='file.csv';
    $wrapper = entity_metadata_wrapper('node', $entity);
    $wrapper->field_filename->set($my_filename);
}


Problem with HOOK_preprocess_breadcrump (Caching?)

Change the cache context from 'url.path' to 'url'

function xxx_preprocess_breadcrumb(&$variables) {
    ...
    $variables['breadcrumb'] = array(
      array(
        'text' => 'some text',
        'url' => "/someurl"
      )
    );
    ...
    $variables['#cache']['contexts'][] = 'url';
}

I ran into the same problem with Drupal 8.2.4


Check out the Popup module, which may be useful.


Circumventing Drupal's Cache for New Content

403 "Access Denied" on a cache miss seems odd to me. One thing to try is http://drupal.org/project/adbc as it makes the Dupal cache operate like one expects.


How do I automatically load a bunch of JS/CSS from sites/all/libraries without hook_library?

Assuming you are on Drupal 7, drupal_add_library() will do just that for you. From the function's API page:

  Adds multiple JavaScript or CSS files at the same time.

  A library defines a set of JavaScript and/or CSS files, optionally
  using settings, and optionally requiring another library. For example,
  a library can be a jQuery plugin, a JavaScript framework, or a CSS
  framework. This function allows modules to load a library
  defined/shipped by itself or a depending module, without having to add
  all files of the library separately. Each library is only loaded once.

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_library/7

Note that you first need to define and register the library with hook_library().

http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_library/7


Domain access domain menu show default values

I found a workaround. I just rebuild the options array with the domains the user has admin access to.
Here is my code:

// Alter the edit menu item form

if($form_id == 'menu_edit_item'){
    $form['domain_menu_access']['manage']['#collapsed'] = false;
    $domains = array();
    if($user->uid > 1){

  // We don't need to hide any menu items on other domains so we don't show this option.
  $form['domain_menu_access']['manage']['domain_menu_access_hide']['#access'] = false;

  // Loop the user object for all the domains current user is connected to
  foreach($user->domain_user as $domain){
    // Get the domain data
    $domains[] = domain_lookup($domain);

    // First unset all the options of the form element so we can rebuild it with our own values
    unset($form['domain_menu_access']['manage']['domain_menu_access_show']['#options']);
    //Rebuild the #options array
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#options']['d'.$domain] = $domains[0]['sitename'];

    // Set the default value(s)
    $form['domain_menu_access']['manage']['domain_menu_access_show']['#default_value'] = array('d'.$domain);
  }
}

}


Is there a easier way to disable and enable module for module development?

For quick disabling and re-enabling of modules, try drush dre module1, module2.

This is a Devel command, so you need to have that installed, and enabled.
You just need to be sure you put them in the right order according to their relative dependencies; should module1 be dependent on module2, it wouldn't work.


Is there a way to add bulk operation options to the admin/content list's 'Update Options'?

Bulk operations provided by that module only make sense in the context of a view, so you won't see them on a non-view page like the standard admin content page.

You can install the Administration Views module to replace that page with a View, and then you should see the options you're expecting. Most (all?), of the core actions from the original page should be available. To add more, you can edit the View and change the available actions in the VBO field.


add product with special price to cart drupal7

You need to use a rule that acts on the "Calculating the sales price of an item" and then set the price using that rule. Here is an example: https://drupalcommerce.org/user-guide/sell-price-calculation


Are entity IDs assigned per entity or across the board?

Each entity type has it's own ID sequence. For example a user may have the uid of 1 while a node may also have an nid of 1. Similarly a taxonomy term may have a tid of 1. In all those cases the "entity_id" is 1.

Regarding the serial module, as it provides a field via the Field API, presumably that field could be attached to any entity bundle.

In regards to linking your entities, you could probably use the entityreference module to create reference links between your entities.


"Node: Created day" mismatched, not reflecting the actual created day

Actually had this bug, but with views 2 on drupal 6, and instead of going forward a day, our view was going backward a day.

Have you tried updating to --dev to see if the issue still exists? I know a lot of patches have been committed since that alpha was released.


How do I add JavaScript specific for a view?

You could use the template_preprocess_views_view() hook to do this:

function THEME_preprocess_views_view(&$vars) {
  $view = &$vars['view'];
  // Make sure it's the correct view
  if ($view->name == 'your-view-name') {
    // add needed javascript
    drupal_add_js(drupal_get_path('theme', 'your-theme') . '/your-js.js');
    // add needed stylesheet
    drupal_add_css(drupal_get_path('theme', 'your-theme') . '/your-css.css');
  }
}

Note that you could also check the specific display of the view using:

if ($view->name == 'your-view-name' && $view->current_display == 'your-display-id') {
  // include javascript & css here
}

You should be able to check for a custom css class like this:

if ($view->name == 'your-view-name' && $view->display[$view->current_display]->display_options['css_class'] == 'your-css-class') {
   // include javascript & css here
}


Views Data Export: Export to XLS with column labels?

If your spreadsheet is missing the field labels as column headers, chances are the "label" setting is disabled on each field (probably because, you have another display in the view with the labels turned off).

For each field in the Fields section,

Click the field name to open the settings option.
If necessary, be sure to choose For "This views_data_export (override)" from the top of the modal.
Enable the checkbox to Create a label and set the column heading/field label for the spreadsheet.
Click the Apply (this display) button at the bottom of the modal to save the settings for that field.

Save the view, clear your caches, and test the export again.

If the labels are set, the next course of action to check include:

Checking for any template files either in the theme or a custom module that could be overriding the settings.

Within the view, you can click the Information link next to Theme at  the bottom of the Advanced section (far right of views edit screen). It will list template filenames that could override the view,  and render existing templates in bold.
Should you find a template outside of the Views Data Export module's folder, you can temporarily remove it and test to see if it resolves the export issue.

Checking to make sure you are running the most up-to-date version of the module.


profile2_load_by_user Trying to get property of non-object

You are assuming there is a profile for all users and your admin user seems to not have one. Add a check if there is a profile for the current logged in user:

function odbornik_fields_form_profile2_edit_main_form_alter(&$form, &$form_state){
global $user;
$profile = profile2_load_by_user($user->uid, 'main');
if($profile) {
  $checkbox = $profile->field_testcheckbox['und'][0]['value'];
    if ($checkbox == 0) {
       $form['profile_main']['field_info'][LANGUAGE_NONE][0]['#type'] = 'hidden';
     }
  }
}


Based on the help for this command I'd say it is not possible:

$ drush help field-clone
Clone a field and all its instances.

Examples:
 field-clone tags labels                   Copy 'tags' field into a new field 'labels' field which has same
                                           instances.
 open `field-clone tags labels`            Clone field and then open field edit forms for refinement.

Arguments:
 source_field_name                         Name of field that will be cloned
 target_field_name                         Name of new, cloned field.

Edit: This GitHub issue can confirm it.

But you can always go to Manage Fields, edit the new field and change its name.


Cron task with Elysia cron module run only manually?

As you said "the cron works only when I run it manually in the admin section (Elysia cron configuration), but I need it to be runing every some specific periode !", it tells your codes are working fine.

By default Drupal cron runs when site is accessed and it evaluates when was the last time cron ran, so if the prescribed time is passed cron will run again, but for that site needs to be accessed, so you have a task which is supposed to run at fix period, you can not wait for Drupal site to be accessed by some one, instead you need to set a crontab on your server which means your server will ping your cron.php at the scheduled time.

Check How to setup cron tab on Linux based system or as an alternate option you can use drush while setting up cron tab (see: cron.html).


Is there a module that will let me set up site-wide notifications like Stack Overflow's orange one?

Check out the list of modules for Displaying Status Messages — some of these might provide a good starting point.


Commerce, different price based on quantity

You can set a Promotion based on Product's quantity if that's what you're looking for. Just give a go to commerce_promotion module (included in Commerce 2.x core) and enable set conditions as on the picture below.


How to make a custom translatable string?

Clear caches. Then, go to http://example.com/admin/config/regional/translate/i18n_string and hit "Refresh strings" button. This should do it.

Also, t() is known to cause problems if used on variables, not strings directly. But most of these problems affect tools that tries to extract strings into .po files, so there is a fair chance it will work for you. But think twice if you really need a variable there.

If it happens to you that your string aren't recognized by panel, you can use one more method. Write your own .po file. Structure is as follows:

white-space
#  translator-comments
#. extracted-comments
#: reference...
#, flag...
#| msgid previous-untranslated-string
msgid untranslated_string
msgstr translated_string

Repeat this (in one file) for all strings. Create one file per language you want to translate to. Then go to http://example.com/admin/config/regional/translate/import and import your files. From now on, strings will be available for translation in interface.


Retain Guzzle Session During Batch Operations

Between two batch runs, the data is saved in the database serialized. Before the second batch run, the data is taken from the database and unserialized. __PHP_Incomplete_Class Object tell us that, at the moment the data is unserializes, no GuzzleHttp\Cookie\CookieJarInterface class is available, and objects of that class cannot be unserialized.
To retain a Guzzle session between batch runs, you can save the data as  array.
$context['results']['jar'] = $jar->toArray();

To get back the data, you can then use the following code.
$jar = CookieJar::fromArray($context['results']['jar'], 'domain.com');

If you save an object in $context, as in your case now, it would be available through all iterations at one batch run, but at the next run, an error is thrown.
If you still prefer to keep objects during iterations instead of arrays, to avoid errors you should check if $context['results']['jar'] is an instance of GuzzleHttp\Cookie\CookieJarInterface.


Add body class to both Node add and Node Edit Page

Did you try :

function MYTHEME_preprocess_html(&$variables) {
  if ((arg(0)=='node' && arg(2)=='edit') || (arg(0) == 'node') && (arg(1) == 'add')) {
    $variables['classes_array'][] = 'node-edit-page';
  }
}


Most maintainable way to make page with one top half and alternative bottom halves selected by tabs?

Looks like you need to look at some of the typical "page layout" modules, such as these ones (excerpts from their project pages):

Display Suite.

... allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

Panels.

... allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Not sure if Display Suite will be sufficient for all your needs, but Panels will pretty sure be helpfull. Possibly also with 'mini-panels' added to that.
Be prepared however to invest some time in learning about these amazing modules. A great resource for learning about Panels is the (free) video training about Learn Page manager. Panels uses 'Page manager', which is one of the sub-modules of Chaos tool suite (ctools)).


Setting a field on an entity form to be required

It is really annoying... I struggled with that several times as well. The important key is places deeper in the array. Take a look on

$form['field_ref_download']['widget'][0]['target_id']['#required']


How to access fields from a goal when creating a node with Rules?

Have a look at this rule (in Rules export format), which is an example of how to get this to work:

{ "rules_show_a_message_after_goal_completion" : {
    "LABEL" : "Show a message after goal completion",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "goals", "rules" ],
    "ON" : { "goal_awarded" : [] },
    "IF" : [ { "goals_goal_condition" : { "goal_id" : "2" } } ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "goal", "id" : "2" },
          "PROVIDE" : { "entity_fetched" : { "goal_fetched" : "Fetched goal" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about the \u0022[goal-fetched:ftitle\u0022 goal which you just completed:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Description\u003C\/strong\u003E = [goal-fetched:field-goal-description]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Category\u003C\/strong\u003E = [goal-fetched:field-goal-category]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Level\u003C\/strong\u003E = [goal-fetched:field-goal-level]\u003Cbr \/\u003E" } }
    ]
  }
}

Some details about this rule:

Rules Event: "A goal is completed by a user", as in your question.
Rules Condition: "The goal completed by a user", a Rules Condition provided by the Goals module (disclosure: I'm its maintainer). In my case, I used the goal with goal id = "2" (replace with the goal id that matches your case).
Rules Actions:

"Fetch entity by id", whereas the entity is a goal, and the id of it is (also) "2" (replace with the goal id that matches your case).
"Show a message on the site", which is just to demo / test some of the field values related to that goal (adapt the machine names of those fields to match your field names).

So by adding the Rules Condition "The goal completed by a user", and by also adding the Rules Action to "Fetch entity by id", in any subsequent Rules Action you should have access to all fields of the goal (with the goal id that matches your case).


Adding jQuery UI selectmenu() to Drupal form

I think the 'Drupal' way would be to implement hook_library() to add the new element to the system:

function MYMODULE_library() {
  $libraries['ui.selectmenu'] = array(
    'title' => 'jQuery UI: Selectmenu',
    'website' => 'http://filamentgroup.com/lab/jquery_ui_selectmenu_an_aria_accessible_plugin_for_styling_a_html_select/',
    'version' => '1.8.7',
    'js' => array(
      drupal_get_path('module', 'MYMODULE') . '/jquery.ui.selectmenu.min.js' => array(),
    ),
    'dependencies' => array(
      array('system', 'ui.widget')
    ),
  );

  return $libraries;
}

And then add it to your pages using drupal_add_library():

drupal_add_library('MYMODULE', 'ui.selectmenu');

Doing it this way ensures that all the necessary core UI files are included in the page automatically, and allows you to add the widget with a single line of code any time you want to.


This is probably not Drupal's fault. Check the default file permissions on your server!


How can I specify background color and image for a block or node?

You can do it with this module:
https://www.drupal.org/project/bg_image_formatter

Just upload image as background field and set the class in the field settings for which element you want to display image as bgd.
It works with Views as well. So, for example, you can use Views conditional module and create a block and test if bdg field is empty and then create different styles with bgd color in that case.


Use hook_form_FORM_ID_alter() as shown below:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULENAME_form_contact_site_form_alter(&$form, &$form_state) {
    $form['subject']['#title'] = t('New Title');
}

Update #1

For Page Title use drupal_set_title() as shown below:

drupal_set_title('kontakt'); // Add this line in above function MODULENAME_form_contact_site_form_alter


How to use in a view an argument like gids[0]=

Try Views Arguments Extras that lets you set URL params (gid[0], in this case) as arguments.
You can also "push" arguments to the View at the User-Reference field's settings page. You just need to return the URL param to the View.
You must configure the View accordingly.

return $_GET['gid[0]'];


How change Drupal Context with a button?

Context Flag

This module provides integration between the Context and Flag
(3.0+ only for the moment, if there is interest in it support for 2.0
may be added later) modules.
When enabled it creates new Context conditions which can be triggered
based on the value of one or more Flags applied to nodes, currently
active users, or user profile pages.


To override container variables you have to enable this line in sites/default/settings.php (is enabled by default)

$settings['container_yamls'][] = __DIR__ . '/services.yml';

and then copy sites/default/default.services.yml to sites/default/services.yml.

Now you can configure the variables in services.yml.


After an intensive debug session I discovered the block is actually created when you place blocks and select the menu you have just created through the Block UI. That didn't fit with my requirements to place the block programatically so I took a look at the structure of an existing menu block and replicated that.
$this->block = $this->entityTypeManager->getStorage('block')->create(
    [
      'id' => $this->getBid($form_state->getValue('language')),
      'region' => 'header',
      'plugin' => 'system_menu_block:' . $this->menu->id(),
      'settings' => [
        'id' => 'system_menu_block:' . $this->menu->id(),
        'label' => $this->menu->label(),
        'provider' => 'system',
        'level' => 1,
        'depth' => 0,
        'expand_all_items' => FALSE,
      ],
      'theme' => 'mytheme_base_theme',
      'visibility' => [
        'language' => [
          'id' => 'language',
          'langcodes' => [
            $form_state->getValue('language') => $form_state->getValue('language'),
          ],
          'negate' => FALSE,
          'context_mapping' => [
            'language' => '@language.current_language_context:language_interface',
          ],
        ],
      ],
      'weight' => 100,
    ]
  );
  // Save the block.
  $this->block->save();

This achieved the result I was looking for. So far so good. I can now create menus and place them immediately after the menu is created.


Multi-site setup outside public_html and add on domains

By the definition of multi-site: you use one Drupal installation (core) to host several sites. But according to your problem, you want a separate instance of Drupal installation and hence it's considered a "multi-site".

You need edit your virtual host file and point http://assitertselvh.no to the specific folder you're hosting to:

Please use the following guide to edit your virtual host.

http://drupal.org/node/111238


Change the heading User Accounts in user Registration Page

"User account" is the title that an anonymous user see for the "Create new account," "Log in," and "Request new password" pages. Replacing "User account" with "Registration" using $conf['locale_custom_strings_en'] would cause the string to be replaced in every place where "User account" is used, which is not correct.

The solution is to replace the title callback used for user with another title callback. Create a custom module, or add the following code to the custom module you are already using.

function mymodule_menu_alter(&$items) {
  if (isset($items['user'])) {
    $items['user']['title callback'] = 'mymodule_user_title';
  }
}

function mymodule_user_title() {
  if (!user_is_logged_in()) {
    switch (current_path()) {
      case 'user':
      case 'user/login':
        return t('Log in');
      case 'user/register':
        return t('Create new account');
      case 'user/password':
        return t('Request new password');
      default:
        return t('User account');
    }
  }
  else {
    return t('My account');
  }
}

The code I used for mymodule_user_title() is exactly the same code used by Drupal 8 in its user_menu_title().

Other solutions, such as using the String Overrides module don't work too, as they replace the string independently from the context, which is important in this case. Users who are in the page for requesting a new password should not read "Register" as title because they are not registering.


Problems primary links translate drupal 6

I flush all the caches and the problem dont exist!


Why does node_add_body_field() lock down 'body' field instances to the 'node' entity type?

I would expect it is for historical reasons and is a place to migrate data from the old Drupal 6 body field.

Since the old Drupal 6 body field was just for nodes it seems in some ways logical that they would then also restrict this to just nodes so it is as it was in Drupal 6.

A couple of quick (not so thorough) greps didn't turn up any code that looks like it would cause you trouble using it for other entities but I could have missed something.

I would not think that this would cause you much trouble in future but I'm not sure of that.

A possible downside though is that it is in some ways like hacking core.
If someone else inherits your site they may find it unusual that your site behaves differently than usual.

Personally sometimes I remove the drupal core body field and add my own field_body and use that throughout the site.


Placing the comment form on a separate page

Drupal has this built in, the link you are after is comment/reply/[nid].


File upload functionality on node display page

I am able to do it by creating custom module.

    function upload_course_form($form_id) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['course_materials'] = array(
            '#type' => 'file',
            '#title' => t('Course Materials:'),
            '#size' => 60,
            );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#weight' => 10
    );
    return $form;
}

  function upload_course_form_validate($form, &$form_state){
  $field = 'course_materials';
  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array('file_validate_extensions' => array('pdf xls html doc txt docx'));
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}

function upload_course_form_submit(&$form, &$form_state){
print_r($form_state['storage']['file']); //see the upload file details
//and add the code to save the node.

}


Supplying current URL to "Path override" in Panels with Views pane

Although this doesn't answer why exactly the term id is being attached (hoping someone might shed light on that), the simple solution thanks to @Letharion was to use the hook_form_views_exposed_form_alter:

function hook_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if($view->name == 'exhibitions' && $view->current_display == 'panel_pane_3') {
    $form['#action'] = $view->override_path;
  }
}


Where is the CCK autocomplete widget field php configuration code stored?


Fresh installation on the same server where another core version was installed gives error

After you install Drupal, automatically Drupal set sites/default to 555 and settings/default/settings.php to 444 , So it means they haven't deleted .

my suggestion is to change the permission for them, them delete settings.php (and make sure you delete it correctly ), and when you got insure of deleting everything Setup Drupal 7.56 again.


Is it possible to use standard tokens in a views field?

If you want to display the date the node was posted or created when showing fields, you don't need to use a token. Simply add the field Content: Post date to the fields of the view.

If you want to include this date in a Global: Custom text field in your View, be sure to have the field Content: Post date above the Global: Custom text field. The replacement pattern for the post date will appear by clicking on Replacement Patterns inside the custom text field (usually named [created]). You can also select Exclude from display in the post date field if you don't want it to show.

EDIT:
Re-read your question, and I guess you are using Token Filter to insert tokens like [node:created] in a Long text field in your node, right? If this is the case, I'm afraid Views will not do a token replacement when rendering the field. There may be a way to modify the Views formatter to do this, but that's beyond my skills. See this post for a similar situation - you are able to use token replacements in your Views Header or Footer custom text, but not in a Field.


As long as a default value isn't provided in the route definition, every route placeholder is required. Defining the route as follow is sufficient.
my.search.results:
  path: '/search/{text}'
  defaults:
    _controller: '\Drupal\my\Controller\SearchController::results'
    _title: 'Search Results'
  requirements:
    _permission: 'access content

See, for example, the definition of the dblog.event route in the dblog.routing.yml file.
dblog.event:
  path: '/admin/reports/dblog/event/{event_id}'
  defaults:
    _controller: '\Drupal\dblog\Controller\DbLogController::eventDetails'
    _title: 'Details'
  requirements:
    _permission: 'access site reports'

The controller associated to that route, DbLogController::eventDetails(), doesn't check the value of $event_id is an empty string, simply because it won't get an empty string for that parameter.
public function eventDetails($event_id) {
  $dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', [
    ':id' => $event_id,
  ])
    ->fetchObject();
  if (empty($dblog)) {
    throw new NotFoundHttpException();
  }
  // …
}


Check out the API Docs on Drupal.org.  There you will be able to find the description on how to use the functions as well as the actual code of the function.  For your use, here is theme_table().  The actual function is in "includes/theme.inc, line 1631" as stated in the theme_table() documentation page.


Custom Entity is only showing via admin theme

As 4k4 said in the comments, the route is being generated using the link template in the entity annotations. Changing these link templates should be how you set the path to any custom entity page. For future content entities, drupal console will use the base path specified in this step:
Enter the base-path for the content entity routes [/admin/structure]


I think best practice would probably be to use field_view_field():

$view = field_view_field('node', $node, 'field_image');
print render($view);

That will render the field as if it was attached to an entity view, and as such will provide the default image if none is available.


Change date format "Authored on" for views with replacement pattern

In Drupal 8, fields use the normal field formatters.  In your list of Fields in the View, click on Content: Authored on (Authored on).  You can change the Formatter to what you want (same choices as Manage Display on the content type configuration).  You can then configure other options, like the format.

If you already are using {{ created }} in the template, and you need it in a different format for a replacement pattern / token, then add Content: Authored on (Authored on) again to the list of Fields, but exclude it from display.  Reorder things, so this appears before the field you need it as a token.  Configure it as above.  Then, where you need the token, you should have {{ created_1 }}, which is the duplicate you just made.


Interfacing Data back and forth: JSapp  Drupal

Once your step one runs, you've actually created a unique order with a unique line item that references a product.
The ID in #2 should probably just be your line-item id.

I would consider creating a rule on the event "After adding a product to cart" and a custom action (this is an answer where I provided the code to make a custom action) that takes a line item id (something the rule will easily have access to) and sends that to the three.js app.

You really just want to add the custom data to the line item (which is unique to each line item on the order). In fact, using Customizable Products you can easily create a bundle specifically for adding as many fields as you would need to track your data (and display/hide it in views or display modes).

To do this, I would create a menu item that somehow recieves the full json object. Perhaps this blog article will help? Regardless, once you have your data, you will want to update the line item with your data and the best way to do this is with entity meta data wrappers if you are using fields to store the data.

<?php

$line_item_id = 1;
$line_item = commerce_line_item_load($line_item_id);
$line_item_wrapper = entity_metadata("commerce_line_item",$line_item);
dpm($line_item_wrapper->getPropertyInfo());

// ... mess with fields

$line_item_wrapper->save();

?>

If you are using the fields on a line item to store your data, the cart will already be up-to-date because it simply references all the line items.


There is no way to add unique alt text using views, unless... you use:
Editable Fields

This module allows CCK fields to be edited on a node's display (e.g.
at node/123), not just on the node edit pages (e.g. node/123/edit). It
also works within views etc. Anywhere a 'formatter' can be selected,
you can select editable (or click to edit).

Video tutorial/demo
You would have to enable the alt in your content type, then you should be able to edit it in your view.

I have more than 150 content. So i am asking for alternative

I take it you're looking for an easy & quick way so you don't have to edit 150 nodes one by one.
Another method
would be to find the alt field in your database and export the table as .csv file.
Then edit it using excel, and add your alt text here, save.
Import back in and clear the Drupal cache.


User can input multiple terms, results can tagged as some or all of those terms, but not other terms

So if I understand this correctly, you only want the nodes that have all the checked values (and not a subset). So if I checked only blue, only node 4 will be returned and not 1 and 3?

I think you'd be best of to write a custom filter, based on the 'is one of' filter. With that you can select nodes that have the terms attached and than drill down the filter.


Where can I alter the path of the anchor around a views items title?

@No Sssweat interesting proposal. Yes, if an external path field is
  populated we link this node to that path in the view. – dibs

For example: I created a field called external url

In you view add field path then external url and then title

They need to be in this specific order for it to work

Then for path:

For external url:

For Title:


Fatal error: Cannot redeclare MYTHEME_preprocess_page()

You have the function lm_sr4_preprocess_page() declared twice; once in template.php (line 11) and once in preprocess/page.preprocess.inc (line 10).

You need to merge those two functions together, you can only declare a function once in PHP.


get drupal base path in views rewrite result

You can do this in the theme layer by overwriting the template and calling base_path(). If you are displaying Fields, you can overwrite the template for the field you want to rewrite.


How to access personal contact form in search

Okay. I was under a deadline so I came up with an annoying but functioning solution.

1) I added the Search by page module (https://www.drupal.org/project/search_by_page) and enabled it.
2) I made a new search environment by going to admin/config/search/search_by_page.
3) In the new search environment, I enabled all the content types I wanted the module to pull.
4) How I got it to pull users' contact pages was:
5) Go to the enironment I made and clicked 'edit'
6) On the top right of the page are two tabs: 'General settings' and 'paths'
7) I clicked on 'paths'and then clicked 'add new path'
8) I opened a new browser window and navigated to the 'People' tab. I clicked on a user and selected their 'Contact' tab, and copied the path (in my case, user/number/contact
9) I went back to the 'add new path' tab and pasted that info in the 'page to index' section
10) I entered a page title (Contact Mr. Smith) and saved. Clicked on 'add new path' for next user.
11) Repeated steps 7-11 for all 50 users.
12) Re-indexed site by running cron. Voila, contact pages come up in search results.

This was a cumbersome, time-consuming way of doing this, and I'm sure there's a better solution. However, if you're pressed for time like I was, I hope this helps someone.


Theming a node teaser to use its content types's custom tpl.php

You can add template files in your template.php & then add files for them. In your case write something like this in your template.php -

function THEME_preprocess_node(&$vars) { //Replace THEME with your theme name.
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
  }
}

After that, your TPL file for teaser would be in the format of node--[type]--teaser.tpl.php. Don't forget to clear your cache after you do this..