Exported menu blocks to a feature module via FE block they are not created - Why?

You need to select also, in the feature, under strongarm, the "menu_block_ids" variable. Also make sure that the dependency to strongarm is selected. Sometimes it shows the select box but it is left unchecked.

With that the menu block should appear in the blocks page.

It will not appear in the context->edit->menu block though, and I think that is an issue. I am doing more tests before I really open it though.

----alternatively

Don't do it with fe features or strongarm, instead, just use menu block export module (go there admin/config/user-interface/menu-block/export) and proceed, just put any name and click export.

Copy the resulting code in your feature.module (make sure you put the proper name). Something like this:

function feature_name_menu_block_blocks() {
// The array key is the block delta used by menu block.
  return array(
    '23' => array( // feel free to change this to the real id of your menu block
      'parent'      => 'menu-api-menu:0',  //the module might not encapsulate string, be careful
      'title_link'  => 0,
      'admin_title' => 'title',
      'level'       => 1,
      'follow'      => '0',
      'depth'       => 0,
      'expanded'    => 1,
      'sort'        => 0,
    ),
  );
}

Just copy the menu block you want to export, you dont have to copy all of them.


Facet API and Entity Reference Autocomplete

If you are using the Search API Solr with the Facet API, you can create a search index view and use the Facetapi Multiselect along with Chosen to allow your users to select the city via a user friendly drop down box (chosen not only supports typing the search term, but it also allows fuzzy matching). Even if the content type city is not indexed in Apache solr, you can create a relationship in your search view and make the city available to FacetAPI system. You can even expose the city as a filter (if you do not want to mess with facets at all) to your users with a views' relationship.


Adding process function in address field

I have fixed the issue using following code.

$info['address']['#process'][]  = 'Drupal\custom_feature\Element\CustomFeature::customprocessAddress';

Naming convention was also issue.


I think creating a service REST API to be consumed by the client sites is the cleanest solution.

This has been implemented in Drupal 7 with sharedblocks but there no Drupal 8 port at this time.

Studying this module would give you a solid foundation on how to accomplish your task in Drupal 8.

Based on the same concept there is also distributed_blocks module but again does not seem to have a Drupal 8 port.


Feeds import by http always imports even after deleting the source

I solved my problem changing FeedsHTTPFetcher to FeedsFileFetcher in my module and changing the importers to file also. In this case, each import gets the file even if there's already one with the same name.


This is not a trivial question and you're actually asking multiple things :)

As mentioned by BetaRide, a technical, auto-generated key has the advantage that it is much simpler to maintain. The primary key defines how the data is stored and if you have a simple key then update/insert/delete should be a bit faster. What's better in general is a hard question to answer, you could make some comparisons (test both approaches, write 1 million rows and then compare update/delete/query speed)

For the indexes, you do most certainly not need a separate key per column. Some hints:

Only a single index can be used for a single query. Unless you will have queries which only have a condition on e.g. the id, that index is useless.
Indexes on multiple columns are read from left to right. E.g. a index on A,B,C can also be used for a query with conditions on A and B but not for one on B and C.
The more indexes you have, the slower are updates.

Same here, I recommend to fill your table with data and then use EXPLAIN to see how your queries are executed and which index they use. Then you can start to optimize things.


You can use Views Cache to make better performance.

Click on Caching in right side of view edit page


How to use another theme's template file

Since it's always bad practice to hack core, you would have to do it with a custom module. This would be done with either template suggestion overrides or with template suggestions in a preprocess hook such as template_preprocess_node or template_preprocess_page.

Unfortunately this is not enough when you place the template file (tpl) anywhere but the theme's templates/ folder. Your custom module's template folder is not known by default so you will have to notify Drupal about. To do this, you will need to use hook_theme_registry_alter. Here below is an example from one of my projects in Drupal 7 (and it's live and works).

/**
 * Implements hook_theme_registry_alter()
 */
function CUSTOM_MODULE_theme_registry_alter(&$theme_registry) {
  // The Templates path in your custom module you want to add...
  $mod_path = drupal_get_path('module', 'CUSTOM_MODULE') . '/includes/templates';

  // ... or the Templates path in your custom theme.
  // If you use your already existing custom theme's path, make sure you remember that this
  // function exists when you alter or disable the custom theme.
  $mod_path = drupal_get_path('theme', 'CUSTOM_THEME') . '/templates';

  $theme_registry_copy = $theme_registry;
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);
  $hooks = array('node');
  foreach ($hooks as $h) {
    _CUSTOM_MODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}

/**
 * Helper function for re-ordering arrays (needed by theme_registry_alter)
*/
function _CUSTOM_MODULE_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    array_unshift($a, $first_element, $element);
  }
}

I've seen people advocate (or at least suggest) the use of theme_hook() instead, but I actually find the theme registry way a lot easier to handle. Especially when you add more templates at a later stage during the development process.


Custom redirect on custom page for admin user

Implement hook_user_login():

function MY_MODULE_user_login(&$edit, $account) {
  if(/* CONDITION, e.g.: $account->uid == 1 */) {
    $edit['redirect'] = 'admin/content';
  }
}


How do I implement hook_page_alter() in a module?

Try using hook_page_build(&$page). hook_page_alter(&$page), which is called directly after it, is meant for themers to use after all the modules are finished with their business.

I just implemented function MODULE_page_alter(&$page), and it worked in the module as expected.
Did you clear the cache so the module is registered?


I ran into a similar problem recently.  The issue is that internally the "Raw value from URL" doesn't get its data from the URL, it gets its data from the unaliased url.  So if you have a node with an alias like mysite.com/foo/bar, you would expect 'bar' to be the argument passed with a path component of 2.

However since foo/bar is actually node/123, internally it becomes node/123, and '123' is what gets passed to the view.

I have opened a ticket in the views issue queue (http://drupal.org/node/1658352). Hopefully it will see some light with a proper fix, as I dont believe that the expected behavior is to retrieve the unaliased path.


Eliminate Views Entity Reference Duplicates. I have some titles the same on purpose

You can use hook_views_pre_render to get at the results array before it is output to the screen.

e.g.

function my_module_views_pre_render($view) {
  if ($view->name == 'the machine name of the view') {
    foreach ($view->result as $result) {
      // do some kind of comparison and de-duplification
    }
  }
}


Thanks a lot. I did go down the Views PHP route initially, but it struck me as a bit un-Drupally, and even Views PHP says to use handlers where possible.

In the end I used hook_views_data and did:

function mymodule_views_views_data() {
  $data['views']['current_path'] = array(
    'title' => t('Current Path'),
    'help' => t('Provide current path.'),
    'field' => array(
      'handler' => 'concept2_views_handler_field_current_path',
    ),
  );
  return $data;
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function mymodule_views_views_handlers() {
  return array(
    'info' => array(
      'path' => drupal_get_path('module', 'mymodule') . '/handlers',
    ),
    'handlers' => array(
      // The name of my handler
      'mymodule_views_handler_field_current_path' => array(
        // The name of the handler we are extending.
        'parent' => 'views_handler_field',
      ),
    ),
  );
}

With a handler file like:

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 */
class mymodule_views_handler_field_current_path extends views_handler_field {
  function query() {
    // do nothing -- to override the parent query.
  }

  function option_definition() {
    $options = parent::option_definition();

    // Override the alter text option to always alter the text.
    $options['alter']['contains']['alter_text'] = array('default' => TRUE, 'bool' => TRUE);
    $options['hide_alter_empty'] = array('default' => FALSE, 'bool' => TRUE);
    return $options;
  }

  function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    unset($form['help']);
  }

  function render($values) {
    // Return the text, so the code never thinks the value is empty.
    return drupal_get_path_alias();
  }
}


Do you know of the nice menus module?  Nice menus will allow you to make dropdown menus without writing any code on your own.  You can also find instructions for customizing the Nice menus CSS here.

Nice menus has almost 60,000 installs as of this writing, indicating that it is likely to be supported well into the future compared to modules that aren't so popular.


Create node upon form submit rendered by block plugin

You are right, the blockSubmit() method is used when you configure the block. The config form is in blockForm(), not in build().

If you put form elements in build() they get rendered like any other render element, but they are not part of the form api and can't be submitted.

If you want to build a form, use a form class. Then you can put the form class in build() by using the formBuilder():

public function build() {

  $content = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\MyForm');

  return $content;
}

Better solution:

Instead of building your own form use the entity form for nodes, which you can place in a block with this module: https://www.drupal.org/project/entityform_block


The problem is upper/lowercase in your module name.

To be able to run update functions, your module must consist of lowercase characters only. Unlike all other hooks, those are detected through regexes and the way it's implemented isn't compatible with mixed case.


use xmlrpc to authenticate and create a node via services module 3.x and drupal 7

Note: this is valid after SERVICES 3.5 (lower version are deprecated, anyway)

// USER LOGIN
$authenticate = xmlrpc($settings['server'], Array('user.login' => array($settings['user'] , $settings['password']),));

// CREATE HEADERS
$options['headers']['Cookie'] = $authenticate['session_name'] . '=' . $authenticate['sessid'];

// GET TOKEN
$token = xmlrpc(url($this->endpoint, array('absolute' => TRUE)), array('user.token' => array()), $this->headers);

//INSERT TOKEN INTO HEADERS
$options['headers']['X-CSRF-Token'] = $token['token'];

At this point you should be authenticated and could create nodes at will.


Funny how those tutorials did not mention Drupal behaviors, which will trigger once the page is loaded. This is a good tutorial on them (Drupal 7, but same principles apply).

Basically all you should do is call your callback function from a behavior to get the same effect as jQuery's document ready callbacks.

Drupal.behaviors.myModule = {
  attach: function (context, settings) {
    // Call callback here.
  }
};

And while you are at it, I recommend reading up on behaviors as they help to streamline your javascripts and keeps them in closed scopes.


Adding a line item to an order from a module

You need to add the line item to the order itself. You can do this pretty easily with the entity wrapper:

$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;
$order_wrapper->save();


How can I make Apache Solr Autocomplete work in search Views?

Have you tried to search in google? before asking. Have you tried to do anything?
 I noticed you're constantly asking questions to which the answer can be found by spending a little time searching.
Try to do something by yourself before asking. thanks.

ApacheSolr Autocomplete module - This module should solve your problem.


i think you need to increase your max_allowed_packet in your my.cnf/my.ini in mysql,
maybe the problem is with packet size.


In say a validation function, to see both the $form structure and what the user has entered, use a devel debug statement like:

dpm(array('$form' => $form, '$form_state' => $form_state), "Validation debug");

The $form_state['values'] array will contain the raw user entries you can then access and validate.


Well, that's obvious mister - filter criteria has nothing to do with results sorting. On your first screenshot, see "SORT CRITERIA" in the left bottom? you can setup sorting there by adding content field or fields to be sorted by.


Basically:

$messages is where your system messages are put via drupal_set_message()
$help is created from http://api.drupal.org/api/drupal/modules%21help%21help.api.php/function/hook_help/7
and I have never used the mission statement stuff but apparently that's what the highlighted region is used for now and is described in greater detail in http://drupal.org/update/themes/6/7 which has a lot of information on the d6 -> d7 theme changes.


How to filter a node view on a paragraph field

Adding Relationships often causes duplicate rows in the results.

You can "remove" the duplicates using the Aggregation in Views (enable it under Advanced).

Then adjust the Aggregation settings for some Fields, specifically the Group column option. You may need to change it from Value to Entity ID or vice versa. The exact combination of settings depends on your particular case, I haven't tried it with Paragraphs.

When duplicates are introduced through Taxonomy reference field that is using a Relationship then all those Taxonomy fields need to have the Entity ID and not the Value.

If the field is a direct Entity Reference field and isn't using a Relatinship then again it needs to be Entity ID instead of, in this case, target_id.

Be careful with Sort criteria when using Aggregation, some of them can mess up the Aggregation. It's best to remove all Sort criteria while adjusting the Aggreation, then when you have it working add them and test that everything is still working as expected.

Some modules offer more advanced Aggregation settings, try looking into that if you need to, for example: Views Aggregator Plus,


It is easily achievable with drupal_add_css in a hook_preprocess_views_view.

An example of it can be found in the last comment here.


Set default title by content type in Panelizer

If you're using a custom module already and you want to 'set' the title prior to saving the node then you can use hook_node_presave().

To avoid contributor confusion when creating the node you can also do a form_alter and set the #access of the title field to false.  This will hide the field from the contributor.


Have you checked the User Visits Advanced, and the User Visits modules?

The User Visits Advanced module is a module that depends from the User Visits module. It is extremely useful for social networking sites that wish to provide their users with statistics about the number of time a user's profile page is being viewed, and by which users.


date_popup element not working when the form is rendered with ajax

The problem is that you are not using any of AJAX helpers provided by Drupal. When you are using Form API AJAX, for example, all behaviors are re-initialised and functionalities like calendar added to new elements.

If you are not using Drupal-provided AJAX functionality, you need to manually call all behaviors with a proper context after your request is finished and DOM tree updated, probably by calling

Drupal.attachBehaviors(element)

on added DOM element.


Error is raised when I try to redirect webform submission to external webpage with query string

I think there's an easier way to achieve what you want.

In you webform go to "Settings > Form" then you'll see near the bottom "Custom settings" with a dropdown for "method". There you can change it to "GET (Custom)" then enter the url for your third party site.

If you needed the get variable names to be something specific you might need to remake your fields with the right key to match your get variable names you need.

But that should do the trick and it will take care or encoding any special characters for you


For custom forms
The preferred way is to call hook_form_validate for hook_form but you can use $form['#validate'][] = 'custom_validate_function' to call validate function

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

$form = array();

// write your custom fields here..........
return $form;

}

function hook_form_validate($form, &$form_state) {
 $short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');
    }

}

For built in forms by creating content type

function hook_form_alter($form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form_state['#validate'][] = 'form_1_validate';
    $form_state['#submit'][] = 'form_1_submit';
  }
}

function form_1_validate($form, &$form_state) {

$short_field_name = $form_state['values']['long_field_name']['und'][0]['value'];
    if (empty($short_field_name) || $short_field_name == '') {
        form_set_error('long_field_name','That field cannot be empty!');

}
}

function form_1_submit($form, &$form_state) {

//To get the user selected or user submitted values you should look into code below
$field_name_values = $form_state['values']['field_name'];

}


Depending on which one you are using (filter or full html) You need to go to

/admin/config/content/formats/filtered_html

OR

/admin/config/content/formats/full_html

Then under Limit Allowed html Tags add <form> <input> into the list.

If that does not do it, try unchecking the correct faulty and chopped off html box.

Edit:

If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.


Import from feed using a selector only if it has a given XML attribute

I figured this out with the help of an XPATH cheatsheet that shows how selectors I might have written to target HTML would transfer to XPATH values.

To only pull <category domain="keywords"> items, I can use category[@domain="keywords"] as my selector. The other set of <category> items don't have a domain attribute, so I pulled them separately using the selector category[not(@domain)].


How can I use jCarousel with swipe event in drupal for touch screen?

You can use

Swipe event
jQuery.event.swipe

On swipe you can trigger left and right navigation event.

Reference:

Swipe


How to limit number of points that user can add through Geofield widget to Openlayers maps?

In the settings of the GeoField you'd like to limit the entry for, set Storage Options to 'Store each simple feature as a separate field.'
Then in Location field settings, you can set the limit to one.

Number 1 is important, as it will make sure that clicking on the map a second time, moves the point around, instead of creating new points.


To retrieve a Student node (in OO-lingo that would a Student instance), use node_load(). If you want to retrieve all Student nodes, you have to loop over the result of a database query like this

$results = db_query(db_rewrite_sql("SELECT nid FROM {node} WHERE type = 'student'"));
while($nid = db_result($results)) {
  $node = node_load($nid);
  // Do something with $node
}

If you have a lot of Student nodes, it's probably not a good idea to process all of them in a single run. If you really need to process all of them, you should use the Batch API.


How can I index only active user accounts in a user index?

It turns out that Search API has a built-in filter for excluding unpublished nodes, but not users.

So here's a patch.


Remove drupal message "field is required" from webform validation

You can remove it using CSS in that particular page !

Check for specific div's the page body is using and set the div.error to display:none;

OR

Override theme_status_messages to exclude or alter the status messages.

In your case,

function your_theme_status_messages($variables) {
  $display = $variables['display'];
  $output = '';

  $status_heading = array(
    'status' => t('Status message'),
    'error' => t('Error message'),
    'warning' => t('Warning message'),
  );
  foreach (drupal_get_messages($display) as $type => $messages) {
    $output .= "
\n";
    if (!empty($status_heading[$type])) {
      $output .= '
' . $status_heading[$type] . "
\n";
    }
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        if (strpos($a,'required') === false) {  // Check for any other conditions here
          $output .= '
' . $message . "
\n";
        }
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }
  return $output;
}


Addressing the (correct) conclusions you've come to in the comments...

Yes, you'll see some repetition in Drupal 6/7. Drupal 8 uses Symfony routes so things get better, but it's not stable yet.

For your specific case you don't have to have 3 separate menu items (although for the sake of clarity it might make sense). You can define a single list page like so

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

  $items['products/list'] = array(
    'type' => MENU_CALLBACK,
    'title' => 'Enjoy shopping',
    'page callback' => 'html_list_products',
    'access arguments' => array('access products')
  );

  return $items;
}

And define your page callback like so

function html_list_products($arg1 = NULL, $arg2 = NULL) {
  if ($arg1 && arg2) {
    // Both args were provided.
  }
  elseif ($arg1) {
    // Just the first arg was provided.
  }
  else {
    // No args were provided.
  }
}

Drupal will always pass along the remaining slash-separated parts of the request URL to the callback function, so with the above method if you visit /products/list/1/2, $arg1 and $arg2 will be populated respectively. Similarly if you visit /products/list/1 just $arg1 will be populated, and for /products/list, neither will be.


Make either of 2 fields required but not both?

Check this thread and Conditional fields module.

If you're using D7 - the principle is the same as in the thread I linked. Basically you need to attach the name of your processing function to the validation array and there perform the checks.


SimplePie library is required for Feeds SimplePie Parser

You can pull a compiled version of the parse from http://simplepie.org/downloads/simplepie_1.3.1.compiled.php. Rename this file simplepie.compiled.php and copy it in the  directory sites/all/libraries/simplepie/; the module should stop reporting the error.


I think you shouldn't create user this way, as it's bypassing all the controls made by drupal.

You can retrieve registration form this way:

drupal_get_form('user_register_form');

And print it like this:

print(drupal_render(drupal_get_form('user_register_form')));


How to add multiple conditions on a single field in views?

So far as there is no support for nested groups in Drupal 7, we shoud do it slight differently.

Join general filters (Published and Node type) in first AND group. May be we also should to add there "State IS NOT NULL" condition to exclude content with empty State field.

In second group we should place State = 'active' OR test = 'false'. This group - OR group.  In the Views admin interface in would be somthing like this:


Please have a look at the Drupal core themes no longer extend Classy change record.

  Bartik, Claro, Seven, and Umami are part of the product rather than
  the API and therefore it is not officially supported to extend them.
  These themes can change as part of a minor release and cause
  regressions to any themes extending them.

Means: No it's not recommended to extend Bartik. Extend Classy or Stable instead.


Is there a way to safely downgrade modules after installing a version that has a database update?

I think the answer is that "it depends".

If the hook_update_N just added indexes, then you should be safe.  If it added or changed columns, then you could have the instance were particular parts of the module work but others will fail (eg, parts that save to the database).  Or, worse, you could start getting inconsistent data in the database for the custom tables.  You should also see an error about the database on the status report.

I would look at the module in question, search for the hook_update_N definitions and see what changed.  It may be documented in the changelog, but I don't always trust that everything was logged.  Then make a judgement call about what to do.


Why are my prices showing up as unformatted (minor units) in a view on a search index?

To start, if it's a Views view, check you field formatter within the view admin page.  You could also hook into it somehow (I'm not entirely sure how, possibly alter the query), to divide the price by 100, but only for formatting.


How to inject text into the beginning of a textfield?

Do your fields have a different field name per language? For example, maybe they follow some sort of convention like field_description_en, field_description_cn, field_description_de?

If so, then perhaps you can use hook_form_alter and add your own submit handler into the form like so :

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'mytype_node_form') {
    $form['#submit'][] = 'my_custom_submit_handler_function';
  }
}

Then create a function my_custom_submit_handler_function($form, &$form_state). Inside the function you'll need to loop through $form_state['values'] like so and just append your language strings before the values:

function my_custom_submit_handler_function($form, &$form_state) {
  foreach($form_state['values'] as $field_name => &$value) { // <-- forgot the & here... oops
    switch($field_name) {
      case 'description_en':
        $value = '=en='.$value;
        break;
      case 'description_cn':
        $value = '=cn='.$value;
        break;
      case 'description_de':
        $value = '=de='.$value;
        break;
    }
  }
}

There's probably better ways to do it though.

Update

@drupalina I forgot to put the ampersand on the submit handler function which would have updated $form_state. Here's your code with a working version:

<?php

function language_markers_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'property_for_sale_node_form' || $form_id == 'property_to_rent_node_form') {
    // You can remove the texts here too. Below is just an example.
    // Path inside $form may not be correct, so
    // do a var_dump($form) or dpm($form, 'form'); to check the array
    // To use dpm() you need to install "devel" module and enable it.
    #dpm($form, 'form');

    // Trim =fr= string from left side of the #value
    $form['field_description_fr']['#value'] = ltrim($form['field_description_fr']['#value'], '=fr=');
    // You might need to set the #default_value too
    $form['field_description_fr']['#default_value'] = ltrim($form['field_description_fr']['#default_value'], '=fr=');

    // Do this for each language...
    // $form['field_description_de']['#value'] = .......

    $form['#submit'][] = 'language_markers_submit_handler_function';
  }
}

function language_markers_submit_handler_function($form, &$form_state) {
  // Note the ampersand before $value below, which allows the
  // modifications on $value to persist into $form_state
  foreach($form_state['values'] as $field_name => &$value) {
    switch($field_name) {
      case 'field_description_fr':
        $value = '=fr= '.$value;
        break;
      case 'field_description_nl':
        $value = '=nl= '.$value;
        break;
      case 'field_description_en':
        $value = '=en= '.$value;
        break;
    }
  }
}

In my opinion, this would quickly turn very unmaintainable as you get more and more fields & languages combinations. So if you are planning to have more than these description fields, I would suggest to use more general ways to find these fields and automatically remove/add the language strings. For example, using hook_field_attach_presave


Yes, it has, just add --ordered-dump parameter to the sql-dump command, e.g.

drush sql-dump --ordered-dump

Tested under Drush 8.x.


When an anonymous user hits '/user/login' route, how can I trigger an event?

I agree with @Berdir, it shouldn't be a problem if the internal page cache stores a response for each query string.

But the issue here is probably that TrustedRedirectResponse is a cacheable response. When you use such a cacheable response you  have to add the correct cache metadata for the content of the response, here a context for the query arg:

  if ($event->getRequest()->getRequestUri() == '/user/login' && $account->isAnonymous() && $event->getRequest()->query->get('loginFailed') == FALSE) {

    $response = new TrustedRedirectResponse($url . '/StartPage.aspx?Site=' . $site_key . '&URL_success=' . $base_url . '/user/netforum/{token}&URL_failed=' . $base_url . '/user/login?loginFailed=true');

    $cache_metadata = new CacheableMetadata();
    $cache_metadata->setCacheContexts(['url.query_args:loginFailed']);
    // or set max-age = 0 instead
    // $cache_metadata->setCacheMaxAge(0);
    $response->addCacheableDependency($cache_metadata);

    $event->setResponse($response);

    }
  }

Then the dynamic page cache will vary by this context. Or add max-age = 0 to disable the dynamic page cache, because caching won't help here much, this is already cached for anonymous users.


Ended up using a taxonomy term reference with a tag widget.


How to make product views display also show up for Anonymous users in Drupal Commerce?

Inspired by what's written in some of the comments to issue nr 1276450, such as in comment nr 158 of it:

  edit your View: > "Advanced" > "Query settings" : check "Disable Query Rewriting"

For sure worth trying to see if it helps in your case. If it does, it'll be way better then the permission you granted as described in your question I think.


How can I implement a required disclaimer page?

I'm assuming that once someone "Agrees" to your terms, you do not want them to have to agree on subsequent visits?

I'd like to recommend a forced registration. You can restrict the contents of your website to authenticated users only. To do this - go to admin/people/permissions and uncheck all permissions for anonymous users.

If you do not want to mess with site permissions, you can check out a great module:
https://www.drupal.org/project/anonymous_login
Anonymous Login will redirect anonymous users to the login page whenever they reach any admin-specified page paths.

Then I would customize your user registration process accordingly. Make it as lightweight as you want. I would check out the Site Disclaimer module to add your site terms functionality:
https://www.drupal.org/project/site_disclaimer

Also - if you're looking for a quick way to make the login/registration pages nicer - check out the "Better Login" module.

Depending on your version of Drupal - check out the "Agreement" module.
The Agreement module allows the administrator to present a text-based agreement (think "Terms of Service") that users of a particular role must accept before they are allowed to access the site.

Let me know if you would like more clarification. I hope this helps put you in the right direction, but you didn't provide much background info for me to help. (i.e what have you done so far, etc).

-Wrench


What is the difference between template_preprocess_search_result() and template_preprocess_search_results()?

template_preprocess_search_result is to process variables for search-result.tpl.php which will render output for each of the search result independently.

template_preprocess_search_results is to process variables for search-results.tpl.php which will render output after each of the search result is already rendered through search-result.tpl.php

For example, if there are 4 search results. for each of the results search-result.tpl.php will be used. and at the end search-results.tpl.php will be used. Ending up using search-result.tpl.php for 4 times for each of the results and search-results.tpl.php only once at the end.

Hope that is clear.


Present users with form to create new node

You could redirect the user upon login to the create form. A good module for this (and a lot of other stuff) is: logintoboggan


Git is a source code management (SCM) system.  There are many different source code management systems out there and Git fall into the category of a distributed version control system (DVCS).  It takes a "peer-to-peer" approach to version control as opposed to a "Client-Server" approach like version control systems like Subversion (SVN).

Yes we can use GIT with drupal.

To setup a GIT repository in drupal project please visit below link.

Git Setup


With theme hook suggestions:

function MYMODULE_preprocess_page(&$vars) {
  if (some_contextual_condition()) {
    $vars['theme_hook_suggestions'][] = 'page__about_us_gallery';
  }
}

The above will correspond to a template file in your theme named page--about-us-gallery.tpl.php


A disabled module has a schema version of -1, how can I enable the module and then run DB updates using hook_update_N?

Disabling a module should not set the schema_version to -1. -1 means SCHEMA_UNINSTALLED. As the constant says, it means this module has never been installed.

A module that has not been installed before is not supposed to run updates. hook_schema() is supposed to contain the current state of a module's schema. So this behavior is correct, and you should not mess around with the schema version manually.

If disabling (not uninstalling) a module really does set the schema_version to -1, then that's where things go wrong. But Drupal core isn't doing this, see module_disable().

Also, note that Drupal executes updates for all installed modules, no matter if they're enabled or not.


This is an open issue which is worked on here:

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


This is a known issue for drush in Windows, along with several others regarding sql operations and rsync. The best solution I know so far is described in:

https://drupal.org/node/1393672


I don't know if it's the best way to do it, but if I was in this situation I will do that way:
hook_form_alter => use a sql query to get the last node id of his last post, then node_load() and in form_alter copy the data you got from node_load() into the new node.

This solution should work if you already have a value in at least one of the previous one.

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
    //get your form id of the admin activity page
    drupal_set_message($form_id); //or echo $form_id; it should be activity_node_form
    if($form_id == 'activity_node_form'){
        $form['#submit'][] = 'YOURMODULENAME_submit';
    }

}

function YOURMODULENAME_submit(&$form, &$form_state){
    if(isset($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
        if(empty($form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'])){
           $lastNode =  YOURMODULENAME_query();

           $node = node_load($lastNode['entity_id']);
           if(isset($node->field_activitiy[LANGUAGE_NONE][0]['value'])){
                $form_state['values']['field_activitiy'][LANGUAGE_NONE][0]['value'] = $node->field_activitiy[LANGUAGE_NONE][0]['value'];
           }
        }
    }
}

function YOURMODULENAME_query(){
    global $user;

    $query = db_select('node', 'n');
    $query->join('field_data_field_activity', 'a', 'n.nid = a.entity_id');
    $query->condition('n.uid',$user->uid,'=');
    $query->fields('a', array('entity_id'));
    $query->orderBy('a.entity_id', 'DESC');
    $query->range(0,1);
    $result = $query->execute()->fetchAssoc();
    return $result;
}

Tell me if you got an error.
PS:once you got the form_is remove the line

drupal_set_message($form_id);


Search API for searching in existing Solr Core

The Solr core's schema must have a field "index_id" and the value must be the same as the machine name of the Drupal index (in order for that (Drupal) index to find it). Moreover, the (Drupal) server has to use "Any Schema" and the (Drupal) index must be read-only.

Note that under "View" it still says "0/0 Indexed", however the search works.

There is a datasource.md in the search_api_solr module's folder which was helpful. I found it helpful to use search_api_devel as it shows the queries to Solr.


Override html.twig.html within custom module

You can completely take over the printed page if your return value is an extension of Symfony's Response class.

Here your return value is a render array so Drupal assumes it is to be rendered in a normal HTML page.

This complex looking diagram shows the flow of request to response:  You can read more about the diagram here: https://www.drupal.org/developing/api/8/render/pipeline

The first takeaway on that docs page is

  Routes whose controllers return a Response object bypass the pipeline below. They rely directly on the Symfony render pipeline.

In other words, most of the complexity of that diagram covers the case where the return value of a controller is NOT a Response object. Returning a Response object cuts out what Drupal normally does to wrap the render array in the html.html.twig file.

There are a lot of examples in core of direct returning of a response object. Here is one:

public function testFeed($use_last_modified, $use_etag, Request $request) {
  $response = new Response();

  $last_modified = strtotime('Sun, 19 Nov 1978 05:00:00 GMT');
  $etag = Crypt::hashBase64($last_modified);

  $if_modified_since = strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE'));
  $if_none_match = stripslashes($request->server->get('HTTP_IF_NONE_MATCH'));

  // Send appropriate response. We respond with a 304 not modified on either
  // etag or on last modified.
  if ($use_last_modified) {
    $response->headers->set('Last-Modified', gmdate(DateTimePlus::RFC7231, $last_modified));
  }
  if ($use_etag) {
    $response->headers->set('ETag', $etag);
  }
  // Return 304 not modified if either last modified or etag match.
  if ($last_modified == $if_modified_since || $etag == $if_none_match) {
    $response->setStatusCode(304);
    return $response;
  }

  // The following headers force validation of cache.
  $response->headers->set('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
  $response->headers->set('Cache-Control', 'must-revalidate');
  $response->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');

  // Read actual feed from file.
  $file_name = drupal_get_path('module', 'aggregator_test') . '/aggregator_test_rss091.xml';
  $handle = fopen($file_name, 'r');
  $feed = fread($handle, filesize($file_name));
  fclose($handle);

  $response->setContent($feed);
  return $response;
}


Can I pass file name as a parameter to menus page arguments?

Example

function mymodule_menu() {
  $items = array();
  $items['custom/delete/%/%'] = array(
    'title' => "Delete Files"
    'page callback' => 'delete_public_files',
    'page arguments' => array(2, 3),
    'access arguments' => array('administer custom settings'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

Please use integer in the array of page arguments to specify the value in url. The url is split in this format: 0/1/2/3


How ajax open a link of node in custom region?

I don't have much time to write the example code for you at this moment, please try to digest the steps below. Let me know if you find some points which you don't understand.

Duplicate a new ajax endpoint (e.g. ajax/node/%node) fornode/%nodeinhook_menu`.
Alter the menu item 'node/%node' with custom page callback.
In the custom page callback, load front page content.
Load a custom JS file in the page callback.
In block admin, move a empty block to the desire region.
In the custom JS file, use l_ajax() to load the content ajax/node/%node to the target DIV.


In your Views UI, at the right, expand "Advanced". Simply add a relationship of User: Author and then create a filter using field User:current and make sure you use setting logged on user


module to customization product in drupal commerce

You are looking for Commerce Customizable Products

  Drupal Commerce allows you to sell customizable products that require
  customer input when added to the cart. Use cases for this
  functionality include:

Business cards that require contact information and a logo upload.
Event registrations that require attendee information.
Donations the allow the customer to specify a donation amount.

and especially for t-shirt design it is possible only through third party tools, we can integrate but it is not free, they have drupal support with their tool http://www.online-product-designer.com/online-advance-tshirt-design-tool.php and http://harboarts.com/shirtdesigner/


User picture not removed when deleting user in Drupal 7

if you really like to delete user profile picture on user delete event use this code in hook_user_delete($account).

// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);

hope works for you


How can I change the items order in a pulldown list of filter in views?

I guess you could probably change the roles order in People>Permissions>Roles (simple drag and drop) and the Views filter will use it by default.


What's the fastest method/implementation for an Ajax callback?

I define a custom page callback for my hook_menu() item which prints my json/js.

That is what Drupal 6 offered. The Drupal 7 AJAX framework can do a little more than that. Yes it bootstraps Drupal, but it also gives a lot of features for free. In short you can use ajax_deliver() as a page delivery method, and send commands to the browser.

  ... Ajax may be enabled by adding classes to buttons and links. By adding the 'use-ajax' class to a link, the link will be loaded via an Ajax call. When using this method, the href of the link can contain '/nojs/' as part of the path. When the Ajax framework makes the request, it will convert this to '/ajax/'. The server is then able to easily tell if this request was made through an actual Ajax request or in a degraded state, and respond appropriately.

However if you want to sidestep the framework for performance reasons then there is nothing to stop you calling php files in your module directly from javascript. You will get no Drupal goodness but you also will have complete control over the page.


Is the redirect from /user/logout to /user/login?destination=/

No, the normal behavior is to redirect to the frontpage. You probably have a module installed which issues a second redirect when the logged out user doesn't have access to the frontpage.

  How is the user logout process supposed to work?

This is the core controller as example:

UserController::logout

  /**
   * Logs the current user out.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirection to home page.
   */
  public function logout() {
    user_logout();
    return $this->redirect('<front>');
  }

So you only need to call user_logout() in custom code to implement your own logout.


how can I have a body with more than 64 Kb of data in it?

The reason of the problem is a regular expression that causes PCRE to reach the limit set for pcre.backtrack_limit or pcre.recursion_limit.
There was an issue report on drupal.org about truncated body content; the length of the text that is possible to enter before it gets truncated depends from the characters used (English text can be longer than a text containing all Unicode characters), and from the values set for pcre.backtrack_limit and pcre.recursion_limit.
The issue report I am speaking of is Document possible preg memory issues. Gerhard Killesreiter's comment is the following one:

This issue [the body content being truncated] is due to the limits of the perl regular expressions that we use to validate that you posted valid UTF8.
If you increase the limits in your settings.php file you will see the text.

ini_set('pcre.backtrack_limit', 200000);
ini_set('pcre.recursion_limit', 200000);

You will need to experiment which values work for you.

node_schema() defines the body field of the node_revisions table as "big text". This means that with MySQL the maximum length of a node body is 4 GB, and with PostgreSQL there isn't (theoretically) any limit; in both the cases, the limit is not the 64KB you are observing.
The default.settings.php file contains the following comment:
/**
 * If you encounter a situation where users post a large amount of text, and
 * the result is stripped out upon viewing but can still be edited, Drupal's
 * output filter may not have sufficient memory to process it.  If you
 * experience this issue, you may wish to uncomment the following two lines
 * and increase the limits of these variables.  For more information, see
 * http://php.net/manual/en/pcre.configuration.php.
 */
# ini_set('pcre.backtrack_limit', 200000);
# ini_set('pcre.recursion_limit', 200000);


How to aggregate field results to a chart?

This kind of questions show up quite often. And each time I try to get them resolved with this very first attempt (if it is related to a Views display):

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

In my experience, 90% of the issues turn out to be related to errors in the creation of the table that contains the data to be charted.

If this question is about creating a chart using the Views integration, then refer to the appropriate Community documentation resources with more details about how to do so:

For the Chart module: Create charts using Views
For the Charts module: Steps to create charts using the views UI.

Disclosure: I'm a (co-)maintainer of both Chart and Charts, and co-author of the documentation resources mentioned.


[Updated] You will need to have the Token and Entity Token modules enabled. Then you'll print custom date format with the following token

[entity-fetched:field-event-date:value:custom:d-M-Y]

the token should produce the date in the format

09-Jan-2016

refer to PHP Manual for custom date formats.


CSRF validation failed issue on custom services!

You can check workflow steps

First Time for login

POST /services/session/token to retrieve CSRF Token POST
myendpoint/system/connect with X-CSRF-Token header IF not Logged In
Try Log in /myendpoint/user/login Log in Success and keep
session_name=sessionid in Cookie Varible

Future Launches

POST /services/session/token to retrieve CSRF Token
POST myendpoint/system/connect with X-CSRF-Token header along with previousely saved session_name=sessionid as Cookie Header

Don't request for new CSRF token use the returned one for previous request.
You will find it in a key named token in the result returned.
Just request a new csrfCSRF token for the first time only.

Here is an example of a user profile request:

{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}


How to unlink the teaser title from the original content?

On the view you are using, simply click  on the title field, and uncheck link field to original piece of content


The Drupal 8 version of Mime Mail doesn't seems to integrate with the
Rules module.

This question and the follow-up comment seem to imply that Rules integration with Mime Mail is NEEDED in order to send HTML email with Rules. That's not true. Drupal core doesn't support HTML email, so you need an add-on module like Mime Mail if you want to send HTML email. But if you have Mime Mail installed, then you can send HTML email from ANY source, INCLUDING Rules. If you follow the Mime Mail Quick Start documentation you will get this working in just minutes.
There is also a complete example at https://www.drupal.org/docs/8/modules/d8-rules-essentials/examples/email-examples/sending-html-email showing how to send HTML email from Rules using Mime Mail.
Mime Mail integration with Rules allows Rules to use the ADDITIONAL features provided by Mime Mail which are not part of Drupal core or part of other email modules.  But this additional integration is not needed unless you want to use those Mime Mail features. For example, the ability to add attachments, or to specify a plaintext email body that is different from the HTML body. Those are Mime Mail specific features.
Mime Mail is not completely ported to D8 yet but there is a patch that ports the Rules support at https://www.drupal.org/project/mimemail/issues/2928965 If you need these additional features I suggest you contribute to that issue.


I have a block that I need to show in two regions.

One solution is to use MultiBlock. Another would be to use Panels which would also have value if you wanted to have different layouts for the gender specific pages.


How to display the node title in different region 2 using theme method in drupal 7

You're looking for the $title variable.

<?php print $title; ?>

Here is a list of all of the variables that are available to you in a theme file (for a page).


How do I find the role id from an og group role name?

Found a helpful solution using a db query https://www.hashbangcode.com/article/load-drupal-organic-group-role-name

$roleid = db_query("SELECT rid, name FROM og_role WHERE gid = :gid and name = :name ORDER BY rid",array(':gid' => 14, 'name' => 'student'))->fetchAssoc();

Let me know in case there is any other or better solution, thanks!


Get the image file src (url)

$fid = 1;//The file ID
$file = \Drupal\file\Entity\File::load($fid);
$path = $file->getFileUri();

OR

$path = 'public://images/image.jpg';
$url = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($file->getFileUri());


How to add text over Slideshow/carousel?

First of all you are using views + views slideshow for the slideshow, correct??
And you are using a slideshow content type.

No => use views + views slideshow to show your slideshow contents as a slideshow. You can find instructions in its documentation and many videos to help you out(google knows best!! :))

Yes =>

in views : should show fields and not content
so you will have 2(or more per your need) fields : image and text(custom text area or say your title)
Using css you can position your text.

Hope it helps....keep posting your problems in comments...the community will always help you out.


Drupal Module for arranging Nodes of special type into a table||chart

I'm really glad that I found a good and comfortable solution for my problem.

There are two modules available: Views Table Group, Views Merge Rows

At the beginning, I had some problems with the settings. After a few tryings I got along with these:  check "Use values of this field as a filter" instead of "Use the first value of this field"

Note: I've just seen the merged rows logged out! So you had to change the visibility/accessibility settings or just log out to check the table.

My result:


How to calculate field values in Views Calc?

Edit: Sorry, I overread "Views Calc" before I wrote my answer. But maybe it helps you nevertheless.

Views maybe isn't the right place to add your custom code to. You might consider writing a very small custom module. Let Views then maybe display full nodes. And in your custom module you might hook into hook_node_view(), grab your node's fields, do the calculation and finally add the result as a new field to the the node's content, which then will get rendered automatically:

function MY_MODULE_node_view($node) {
    dpm($node); // start with that

    $time = $node->field_time[LANGUAGE_NONE][0]['value'];
    $distance = $node->field_distance[LANGUAGE_NONE][0]['value'];

    // do your calculations
    // ...

    $speed = $result;

    $node->content['speed'] = array(
        '#prefix' => '
',
        '#markup' => $speed,
        '#suffix' => '
'
    );
}

When developing your custom module you might find the Devel module quite helpful. After activating it you can easily check out what's inside a variable and then double click the displayed results for a deeper insight. So you might start by calling dpm($node) right inside hook_node_view().


Unable to print menu links using menu_navigation_links

The normal way to print that menu would be:

<?php print theme('links', array('links' => $menu), 'attributes' => array('class'=> array('links', 'site-menu')) ));?>

or similar.

If you want to do something different for individual items then in template.php you could implement:

function THEME_preprocess_menu_link(&$variables) {
    // if certain menu item, do something different
}


Creating the custom url aliases for nodes?

You can use the Path Auto module for this purpose. It has many patterns options for each content type.

You can generate alises pattern for child articles and parent article separately.
I have added a screenshot that how it looks in the back end.

If it does not fulfill your requirement then we can customize the urls on saving with hook_url_inbound_alter() function in our custom module.


User profile view - 2 x variants or view panes with args?

You can either use two variants or different view panes on the same variant.  It is just an organizational choice.

If you use two variants, use Selection rules to distinguish them.  For example, on one of my sites, I have two variants for the user profile, depending on whether the logged in user is viewing his/her own profile or another user's profile.  I distinguish between these two variants using a Selection  rule of logged in user != user being viewed.

Alternately, within the same variant, you can use multiple content panes (created in Views).  You can choose which of these are shown by clicking in the upper right corner of the respective pane (within the Panels UI) and adding Visibility rules.  Why would you use this approach?  If you only have a few panes.  In my case, I used two variants instead because I had about twenty different view panes on the user profiles, and it was simpler to set two Selection rules then 20 Visibility rules.

So in short, my recommendation is: Use different variants with selection rules when you have lots of different items.  Use a single variant with visibility rules when you only have a few items.


How should I read values from multi-field's subfield?

field_get_items() is the only function provided by core to help with this.

The Entity module provides the EntityMetadataWrapper class, though, which makes these things a bit more palatable. E.g.

$node_wrapper = entity_metadata_wrapper('node', $node);
try {
  foreach ($node->field_my_field as $item) {
    $val = $item->value->value();
  }
}
catch (\EntityMetadataWrapperException $e) {
  // Recover...
}

That's about the simplest example there is, it would be worth reading the docs to find out how else you can use it.


How to delete Content Type created through features

Open the content type (for example: article) for editing which should bring you to a URL:

  admin/structure/types/manage/article

You can then append "/delete" into the URL like so:

  admin/structure/types/manage/article/delete

Which should open a form that will let you delete the content type. I don't know if this lets you delete ones that are coming from an active features package, but it definitely does help you delete obsolete content types from inactive features packages. So be careful

FYI, if you do this for multiple content types, don't open all the delete forms in multiple tabs and try to be clever by deleting several types at once. Bad things will happen :-p Make a backup and delete one content type at a time.


How to customize CKEditor format configuration

To remove entries from "Format" selection list of ckeditor just follow in the drupal admin menu :

Configuration >> Content authoring >> Ckeditor

Edit the concerned profile(s) and within the Cleanup and Output section change the "Font formats" list, removing the tags you don't want.

Save and clear your caches.


You can use the element parameter:

  An optional integer to distinguish between multiple pagers on one page.

e.g.

First call:

$output .= theme('pager', array('tags' => array(), 'element' => 0));

Second call:

$output .= theme('pager', array('tags' => array(), 'element' => 1));


How to copy/clone menu of a node when clone with Entity Clone module?

Issue #2839833 has a proposal to add entity clone plugin to node entity to handle this special case.

Alternatively, we could use the event. Luckily Entity Clone module dispatches an event before & after clone for the other modules to act. Here is the code for menu copy:

  // mymodule.services.yml

 mymodule.entity_clone.subscriber:
    class: Drupal\mymodule\EventSubscriber\EntityCloneSubscriber
    tags:
      - { name: 'event_subscriber' }

Subscribe to the post clone event:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_clone\Event\EntityCloneEvent;
use Drupal\entity_clone\Event\EntityCloneEvents;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\node\NodeInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Crates menu item after node clone.
 */
class EntityCloneSubscriber implements EventSubscriberInterface {

  /**
   * Entity post clone handler.
   *
   * @param \Drupal\entity_clone\Event\EntityCloneEvent $event
   *   An event object.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function onPostClone(EntityCloneEvent $event) {
    $entity = $event->getEntity();

    // Act only on node clone.
    if (!($entity instanceof  NodeInterface)) {
      return;
    }
    $cloned_entity = $event->getClonedEntity();
    $values = menu_ui_get_menu_link_defaults($entity);

    // Copy menu item, if available.
    if (!empty($values['entity_id'])) {
      $this->cloneNodeMenuLinkContent($cloned_entity, $values);
    }
  }

  /**
   * Clones menu link content associated with the node.
   *
   * @param \Drupal\Core\Entity\EntityInterface $cloned_entity
   *   Cloned node.
   * @param array $values
   *   An array of menu link content values.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function cloneNodeMenuLinkContent(EntityInterface $cloned_entity, array $values) {
    $menu_item = MenuLinkContent::load($values['entity_id']);
    $menu_name = $values['menu_name'];

    // Create new menu link content with original value.
    $cloned_menu_item = MenuLinkContent::create([
      'link' => ['uri' => 'entity:node/' . $cloned_entity->id()],
      'langcode' => $cloned_entity->language()->getId(),
    ]);
    $cloned_menu_item->enabled->value = $menu_item->isEnabled() ? 1 : 0;
    $cloned_menu_item->title->value = trim($cloned_entity->getTitle());
    $cloned_menu_item->description->value = trim($values['description']);
    $cloned_menu_item->menu_name->value = $menu_name;
    $cloned_menu_item->parent->value = $values['parent'];
    $cloned_menu_item->weight->value = isset($values['weight']) ? $values['weight'] : 0;
    $cloned_menu_item->save();
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[EntityCloneEvents::POST_CLONE][] = ['onPostClone', 200];
    return $events;
  }

}


Displaying all sub-menu items even when not "expanded"

The jQuery Menu module gives you that functionality.


What is the difference between a page and a node?

node.tpl.php

  Default theme implementation to display a node.

page.tpl.php

  Default theme implementation to display a single Drupal page.

see image for more detail.


How can I control block visibility with code?

A working code snippet how to use hook_block_access(). Here I retrieve the condition from a field of the current node:
use Drupal\block\Entity\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_block_access().
 */
function MYMODULE_block_access(Block $block, $operation, AccountInterface $account) {

  if ($operation === 'view' && $block->getPluginId() === 'MYBLOCK') {

    $node = \Drupal::routeMatch()->getParameter('node');

    $hero_image_exists = FALSE;

    if ($node instanceof NodeInterface) {
      if ($node->hasField('field_hero_image')) {
        if (!$node->get('field_hero_image')->isEmpty()) {
          $hero_image_exists = TRUE;
        }
      }
    }

    return AccessResult::forbiddenIf($hero_image_exists === FALSE)->addCacheableDependency($block);
  }

  return AccessResult::neutral();
}

Thanks @Insasse for sharing the following gem in the comments. For programmatically created custom blocks you can control visibility directly from inside the block class via blockAccess():

class MyBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->t('This is a simple block!'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access content');
  }

}

Source: How to Programmatically Create a Block in Drupal 8


How do I get the fields of form attached with a content type as token?

If I understand your question correctly you want send email after state field changes by Rule:

You should:

Create a new rule that will react to the After updating existing content event
Use the following condition:
Data comparison: node:field-your-field(maybe field-state) and node-unchanged:field-your-field
Select Negate: FALSE
Create the action
Send the email


Custom VBO action to print selected nodes

In your hook_action_info() implementation, you should set 'aggregate' to TRUE. For example:

function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_your_custom_print_action' => array(
      'type' => 'node',
      'label' => t('Print nodes'),
      'aggregate' => TRUE,
    ),
  );
}


Use the next code:

$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));
file_put_contents('myfile.txt', $menu_html);

Source: Programmatically load a menu.

EDIT
If you want to make it downloadable you can add next code to your page or submit callback:

// Get menu tree.
$tree = menu_tree_all_data('main-menu');
$menu_html = render(menu_tree_output($tree));

// Download menu txt file.
$filename = "menu.txt";
drupal_add_http_header('Content-Type', 'text/plain; charset=utf-8');
drupal_add_http_header('Content-Disposition', 'attachment; filename="' . $filename . '"');
drupal_send_headers();
echo $menu_html;
drupal_exit();


Drupal core code creates files only when a user uploads a file. With third-party modules, files could be created in other cases. For example, if you are using Apache Solr Search Integration some files could be created; if you are using a module that implements an alternative caching system, some files could be created as well.
sess_write() saves the session ID in the "{sessions}" table, together the value of $user->cache, the IP address used by the user to connect, and the current timestamp.

db_query("UPDATE {sessions} SET uid = %d, cache = %d, hostname = '%s', session = '%s', timestamp = %d WHERE sid = '%s'", $user->uid, isset($user->cache) ? $user->cache : '', ip_address(), $value, time(), $key);
if (db_affected_rows()) {
  // Last access time is updated no more frequently than once every 180 seconds.
  // This reduces contention in the users table.
  if ($user->uid && time() - $user->access > variable_get('session_write_interval', 180)) {
    db_query("UPDATE {users} SET access = %d WHERE uid = %d", time(), $user->uid);
  }
}


You will get the best speed performance using PHP 7.x. I've been running a few Drupal sites on PHP 7 with no issues, and definite performance improvements over PHP 5.x.

MySQL 5.5 or 5.6 is good.


add field in admin>content that show if entity is translated

You can install the Admin Views module and override the view on /admin/content by adding a field that shows if the node has been translated or not.


Views Rss - How to set pager options / items to display via URL argument

/**
 * Implements hook_views_query_alter.
 *
 * If we have an rss feed view we need to set pager settings from url.
 * If no pager number specified in the url do nothing and use view pager   settings.
 * Otherwise get the items_per_page options from the first argument in the url.
 */

function rss_feed_length_views_query_alter(&$view, &$query) {

  $rss_views = array(
    'rss',
  );

  if (in_array($view->name, $rss_views)) {
    $limit = arg(1);
    if ($limit !== NULL) {
      $view->set_items_per_page($limit);
    }
  }
}

SUGGESTED IMPROVEMENT:

  "i'd have used GET parameters rather than path elements - since it's not a different resource, rather it's an option"

I'll accept as an answer anything that implements the suggested improvement.  :)


How do I show the form for adding a node as block?

Try node_add():

$content = node_add($type);

or:

$content = drupal_get_form($type . '_node_form', $node);

Also, please keep in mind that node_load() changed in D7. You should use it like this:

node_load($nid);


Event does not trigger each time I load a page

This look like it is the module "Internal Page Cache", which caches pages for anonymous users. This cache runs before any event as middleware.

In your case there is no need for this module and you can uninstall it.

If there is other code that does interfere you should be able to control this with a priority you set on the event subscriber.


How to change user id from incremental integer to random hash?

Just aliasing the path (as suggested by m1n0) will not be enough, as  users allowed to see the user profile will still be able to connect a user name and profile to a numeric user ID by entering an URL ending with user/ID (where ID is an integer, e.g. 1 for user #1). This will let anyone permitted to view user profiles to view the user name and profile associated with user/ID.

As pointed out by Jimajamma, totally replacing the numeric user ID with a random hash is a major undertaking, since just doing it will break a lot of stuff hard coded in Drupal.  No module exists that will do this for you.  If you want to do this, you'll have to start from scratch.

What you need to do to avoid numeric user IDs from being associated with specific user names and profiles is to prevent non-privileged users from ever seeing the user profile.

Navigate to  Administration » People » Permission and make sure that non-privileged user does not have the permission "View user profile".

After doing this, if a non-privileged user typed in an URL ending with user/1 (or anURL with any other numeric user ID) a 403 status code (Permission denied) will be returned.  Also user names that appear in bylines, etc. will no longer be linked to a profile when viewed by a  non-privileged user.


Show the cart icon only if it exists and it isn't empty

Don't know any module that does this but it is simple to do in your theme

Add this to your THEMENAME.theme

function THEMENAME_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'commerce_cart') {
    if ($variables['content']['#count'] == 0) {
      $variables['attributes']['class'][] = 'visually-hidden';
    }
  }
}


How do you load extra javascript files required for wysiwyg api plugin on node/edit pages?

With drupal_add_js:

function yourmodule_preprocess_page(&$vars)
{
  $node = $vars['node'];
  if($node->type == 'yournodetype' AND arg(2) == 'edit')
  {
    drupal_add_js([...]);
  }
}


Here is the javascript I ended up using to load a views block using AJAX and pass in a contextual filter from the href value of given link on page.

function getInfo(args) {

  $.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
      view_name: 'agent_lookup',
      view_display_id: 'agent_lookup_block', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#ajax-target').html(viewHtml);
        //Drupal.attachBehaviors(); //check if you need this.
      }

    },
        error: function(data) {
         alert('An error occured!');
        }
  });
}

$('.ajax_button').once().click(function(e){
    e.preventDefault();
    var the_id = $(this).attr('href');
    noSlashes = the_id.replace(/\//g,'');
    getInfo(noSlashes);
});


PDOException: SQLSTATE[HY000] [2002] No such file or directory in lock_may_be_available() (line 167

lock_may_be_available() is the first call that Drupal makes, in order to try a connection with the database. Then, the first idea seems that is not unable connect to your database so your mysql isn't running well or better, your Drupal can't connect to your MySQL server. Ok.

The next step is think'bout the reasons:

1- In some cases, it's just due to use "localhost" instead of 127.0.0.1 in your settings.php or local.settings.php file. Review this in the database config block:

$databases['default']['default'] = [
  'database' => 'db_name',
  'username' => 'db_user',
  'password' => 'db_password',
  'host' => '127.0.0.1',
  'driver' => 'mysql',
  'port' => 3306,
  'prefix' => "",
 ];

In some cases using Containers (Docker, DDEV, etc) may be necessary change as: 'host' => 'localhost', to 'host' => 'mariadb',.

2- Maybe the MySQL daemon is crashing. Stop the daemon and restart it. You can use:       /etc/init.d/mysqld restart
or:  service mysqld restart // service mysql restart.

3- If you're using some special kind of configuration as multisite, multidomain, etc, then get some of log info from your system, using: tail -f /var/log/mysql/error.log


How to attach image from a list of predefined images?

These are general guidelines as I made something like this but for D6.
I would create a logotype variable in template_preprocess_node and then loop on you dropdown variable. For each value selected I would add an <img src='path/to/logo1.png' alt='Logo 1' /> to your logotypes variables.
Then just display the variable in you node template.


How to attach a library to a specific content type?

You can check content type and add libraries like this:

function fluffiness_preprocess_node(&$variables) {
  $node = $variables['node'];
  //check content type
  if ($node->getType() == 'article') {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
  }
}


How to pull a record from Salesforce and immediately push the node ID back to Salesforce

Here's how I did it...

Since content is set to push (immediately) on update, I added a hook_entity_insert() that responded not to the content insert but the "salesforce_mapped_object" entity.

This ensures that not only was the node/user created but a mapping was created.

/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'salesforce_mapped_object') {
    $entity_info = $entity->get('drupal_entity')->first()->getValue();
    $type = $entity_info['target_type'];
    $id = $entity_info['target_id'];
    switch ($type) {
      case 'node':
        $node = \Drupal\node\Entity\Node::load($id);
        $node->save();
        break;
      case 'user':
        $user = \Drupal\user\Entity\User::load($id);
        $user->save();
        break;
    }
  }
}

Thanks to @leymannx in the above comment for the guidance.


Problem with anonymous Flag and webform_select_ options_info() only visible to logged in users

So, after some frustration and headbanging, I was led to the answer by someone on #drupal-support IRC. The solution was in fact related to the SQL rewriting. The view was editable through the UI. There under the advanced section, I selected 'diasable sql rewriting.' This ultimately solved the problem.


Display users webform submission as readonly?

I have done an identical task, unfortunately this one of those unique use cases. Here is a snipped in my hook_form_alter

Basically, assuming there is no page element (not multi page):

if ($cutoff_time > $current_time) {

  $form['elements']['field_name']['#disabled'] = TRUE;

  $messenger = \Drupal::messenger();
  $messenger->addMessage(t('Time has expired, you can no longer change the value'), $messenger::TYPE_WARNING);

}

Otherwise (multipage):

$form['elements']['page_name']['field_name']['#disabled'] = TRUE;


How to make Views sorting case-sensitive?

What you're want to do is a sort by a character's byte value. MySQL has a function for this, BINARY(), which you could use in your ORDER BY criteria (e.g. ORDER by BINARY(title)).

Drupal Views doesn't have any default sorting handlers that use this function, so the only way to do it in views is by creating your own custom sort handler.


How to make the image hover between the 2 uploaded image?

Display both images independently with something like this:

<div class="portfolio_area_left">
    <?php print theme('image_style', array('path' => $imageone, 'style_name' => 'image_800x600', 'attributes'=>array('alt'=>$title))) ?>
    <?php print theme('image_style', array('path' => $two, 'style_name' => 'image_800x600', 'attributes'=>array('alt'=>$title))) ?>
</div>

Then use jQuery for the hover/fade: http://jsfiddle.net/adeneo/xTw44/


Drupal Commerce: discount for line items based on user's values?

I don't think the line item will be exposed to the PHP block, and I doubt there'll be anything in scope to get a reference back to it.

You might need to create your own Rules action. It's pretty simple, and you can copy most of what you need from commerce_line_item_unit_price_subtract(), which does have access to the line item entity.

hook_rules_action_info() would be a good place to start.


Making a block's content's all show in one row

This appears to be a stylesheet issue. Everything should 'float:left'. If this has already been done, then your first block is too wide and is forcing the other blocks to displace down.

Experiment with maxwidh on your first block to leave room for the other two.


How do I put a div around table with class = table-responsive?

CKEditor generates the table on its own. You can see this, if you switch to source. So the changes in twig will have no effekt, because the theme layer doesn't touch the source code that is coming out of the ckeditor. Only the filter layer is checking the source. More for security reasons. But it would be possible to change the table here, if you want to do it in drupal. Or you can modify the configuration of ckeditor itself.


How to disable front page view programmatically?

Views are entities, so:

Load the View:

$view_id = 'content'; // Replace with the ID of the view you wish to disable.
$view = \Drupal::entityTypeManager()->getStorage('view')->load($view_id);

Update the status:

$view->setStatus(FALSE);

And save it:

$view->save();

Or all in one go:

\Drupal::entityTypeManager()->getStorage('view')
  ->load($view_id)
  ->setStatus(FALSE)
  ->save();


How to show "New" if the node author is registered within 4 weeks.

What if you edit Vikas code with:

$node_author = user_load($node->uid);
$author_created_time = $node_author->created;


In Drupal Commerce how can you turn product select box options into images?

ok seems that this module does the trick:

https://drupal.org/project/commerce_fancy_attributes

  This module provides a "Rendered term" attribute mode, that shows the
  rendered term instead of a radio button (degrades to a normal radio
  button when JS is off) on the add to cart form.

  Example usage: 0) Enable this module. 1) Create a Color vocabulary,
  add a text field called "Color" that will hold hex values. Go to the
  "Manage Display" screen of that vocabulary, click the tab called "Add
  to Cart form - Attribute", enable only the color field (with the label
  hidden, and using the "Color" formatter). 2) Create several terms with
  matching hex colors (Black: #000000, White: #ffffff, etc). 3) Add a
  Color taxonomy_term_reference field to a product type. 4) When you add
  the color field on the product type, tick the checkbox "Enable this
  field to function as an attribute field on Add to Cart forms." and
  select "rendered term" as option of the "Attribute selection widget".

  The Add To Cart form will now show the colors. Of course, imagefields
  can be used instead of "textfields holding hex values" rendered as
  images.


Updating other modules schema when creating custom module

You should make use of the hook_schema_alter to update entity schema of existing schema's.

function YOURMODULE_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['users']['fields']['timezone_id'] = array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'Per-user timezone configuration.',
  );
}


Module Views automatically replace underscores in css classname to hyphens?

It's by design... Views module is cleaning class in views_plugin_style.inc..

  /**
   * Return the token replaced row class for the specified row.
   */
  function get_row_class($row_index) {
    if ($this->uses_row_class()) {
      $class = $this->options['row_class'];
      if ($this->uses_fields() && $this->view->field) {
        $class = strip_tags($this->tokenize_value($class, $row_index));
      }

      $classes = explode(' ', $class);
      foreach ($classes as &$class) {
        $class = drupal_clean_css_identifier($class);
      }
      return implode(' ', $classes);
    }
  }

Below statement is converting _ (Underscore) to - (hyphens)

$class = drupal_clean_css_identifier($class);

If you see documentation of drupal_clean_css_identifier by default filters replaces _ with -.


Fatal error: Unsupported operand types in form.inc

Duplicate of this question:

Db_Query Fatal error: Unsupported operand types

It turns out that I was setting my page callback to a drupal_get_form with no form present.

I changed my hook_menu to:

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

  $items['admin/structure/module'] = array(
    'title' => 'description of module',
    'description' => 'Configure settings for module',
    'page callback' => 'MY_MODULE_admin_menu',
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

And it worked fine.


Views to display events with single date events and events with date range

Since I was completely unable to make myself understood when asking the question, I thought maybe the solution could clear things up. In the views view I filter  event dates like specified in the question. I then used the hook_views_query_alter to add an or group condition like so:

function MYMODULE_views_query_alter (&$view, &$query) {
  if ($view->name != 'events') { return; }

  global $language;
  $lang = $language->language;

  $start_date = isset ($_GET['field_from_date_value']['value']['date']) ? $_GET['field_from_date_value']['value']['date'] : date('Y-m-d');
  $end_date   = isset ($_GET['field_from_date_value2']['value']['date']) ? $_GET['field_from_date_value2']['value']['date'] : date('Y-m-d');

  $query->group_operator = 'OR';

  $status_condition = array (
    'field' => 'node.status',
    'value' => 1,
    'operator' => '='
  );

  $node_type_condition = array (
    'field' => 'node.type',
    'value' => array ('event'),
    'operator' => 'in'
  );

  $language_condition = array (
    'field' => 'node.language',
    'value' => array ($lang),
    'operator' => 'in'
  );

  $date_condition_value = array (
    'field' => "DATE_FORMAT(field_data_field_from_date.field_from_date_value, '%Y-%m-%d') >= :field_data_field_from_date_field_from_date_value",
    'value' => array (':field_data_field_from_date_field_from_date_value' => $start_date),
    'operator' => 'formula'
  );

  $date_condition_value2 = array (
    'field' => "DATE_FORMAT(field_data_field_from_date.field_from_date_value2, '%Y-%m-%d') <= :field_data_field_from_date_field_from_date_value2",
    'value' => array (':field_data_field_from_date_field_from_date_value2' => $end_date),
    'operator' => 'formula'
  );

  $condition_type = 'AND';

  $query->where[10]['conditions'] = array (
    $status_condition,
    $node_type_condition,
    $language_condition,
    $date_condition_value,
    $date_condition_value2
  );

  $query->where[10]['type'] = $condition_type;

}


a hacky solution in html.tpl.php could be like this:

$node = node_load(arg(1));
echo $node->nid;

You'll want to check for the existence of $node and such to avoid errors.

You could also create your own node template: node--123.tpl.php

You could also use the HOOK_preprocess_page() function to check for the node ID.


In hook_user_login is there a way to know if this is the first time the user has logged in?

Check for $account's access property. It is a timestemp the user logged in previously.

It should be other than a valid time stamp in case to be a first time login.

function MODULE_user_login(&$edit, $account){
debug($account->access);
}


Hide other user comments, but not to admins

Hidden comment

  Optional field to let users know the reason why a comment is hidden.
  Disallow edit/reply/delete on hidden comments
  Optional permission to allow user to hide personal comments (comments on their own nodes). This permission can not unhidden
  comment.

if you want to do custom edit your node.tpl file add following code:

    global $user
    login_uid = //get user id of commnet
    if ($user->uid == login_uid){
      print render($content['comments']['comment_form']);
     }


How to render ctools_custom_content_type_edit_form with ctools_modal_form_wrapper()

Look at if ($settings['custom_type'] == 'fixed') condition in ctools_custom_content_type_edit_form(). Problem in it I think. Also, look at ctools_custom_content_type_get_conf() and do all needed to this function return $settings['custom_type'] equal to 'fixed'.
Maybe this will fix problem, change this value before ctools_modal_form_wrapper() like this: $form_state['subtype']['name'] = 'custom';


Alias not working for a non default language

By default url alias created manually or by Pathauto works only for the language of the node.

But you could make it work for all languages ina few simple steps:

go to the page "admin/config/search/path",
find required url alias and click "edit"
select "All languages" in "Language" field and save

That's all, now this url alias will be active despite of what language has the user.

If manual change is not an option, you can:

try to use "neutral_paths" module (though it is in a sandbox mode)
create simple module that wil do the same

Module forces url aliases to be language neutral, it works both for pathtauto and manual path aliases:

<?php
/**
 * Implements hook_path_insert().
 */
function MYMODULE_path_insert($path) {
    _MYMODULE_path_language_fix($path['pid']);
}
/**
 * Implements hook_path_update().
 */
function MYMODULE_path_update($path) {
    _MYMODULE_path_language_fix($path['pid']);
}
/**
 * Fixing a given path id.
 */
function _MYMODULE_path_language_fix($pid) {
    db_update('url_alias')
        ->fields(array('language' => LANGUAGE_NONE))
        ->condition('pid', $pid)
        ->execute();
}
?>

If you already have lot of existing content with not correct languhae for aliases, then run this code

<?php
function _neutral_paths_set_all_to_neutral($type) {
    $num_updated = db_update('url_alias')
        ->fields(array('language' => LANGUAGE_NONE))
        ->condition('language', LANGUAGE_NONE, '!=')
        ->condition('source', $type . '/%', 'LIKE')
        ->execute();
    if ($num_updated > 0) {
        drupal_set_message(t('@num aliases were reset to language neutral', array('@num' => $num_updated)));
    }
    else {
        drupal_set_message(t('No aliases were updated.') . $type);
    }
}
_neutral_paths_set_all_to_neutral('node');
?>


Adding a CDN asset to drupal theme via info file

You can add it in the theme template.php file.

function YOURTHEME_preprocess_html(&$vars) {

      // Load font
      drupal_add_css('//fonts.googleapis.com/css?family=Lato:300,400,700,900', array(
        'type' => 'external'
      ));

}

Tip: Dont set a protocol to load external resources from Google


How to display a page of a taxonomy term differently from the default view?

Maybe you should check Taxonomy Views Integrator

  The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice


I would recommend that you avoid multisite, and clone the code into a separate codebase -- then copy the database. This is much easier to manage for simple use cases, and would entirely avoid your problem above, as you would only have one copy of each module present in your code base, so Drupal would not be able to load any of them twice.

I am not sure exactly how your situation above came to be, but the database from the original site contains references to all of the paths of all of the enabled modules; somehow, Drupal is trying to bootstrap both the old cached paths, and also the new paths for the same module in its new location.  If you want to continue with a multisite setup, it is likely that a registry rebuild would clear this up.


How to do recurring subscriptions with credit card and Drupal 7

Been doing a bunch of research, and it seems there are two main contenders for my scenario: http://www.fastspring.com and http://www.moneyscripts.net/drupal-membership-suite

I like the second one because it is pure drupal. But I like fastspring because it's very easy to use and pricing seems to be moderate. They also offer a great range of payment methods and they are PCI-DSS certified.

I'll do some more research and let you know my final choice


Are your sure you did all the steps? Step 1: in mytheme.theme
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    case 'system.401':
      // Unauthorized Access.
      $error = 401;
      break;

    case 'system.403':
      // Access Denied.
      $error = 403;
      break;

    case 'system.404':
      // Page Not Found.
      $error = 404;
      break;
  }
  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }
}

Step 2: create the page--404.html.twig file
Step 3: clear cache
For some markup, check https://stefvanlooveren.me/blog/styling-404-error-pages-drupal-8


how do i create a site that allows users to create and view events?

It is very simple to do this task.

You need to create a new content type. add to it corresponding fields and set to it create/edit/delete permission for anonymous and registered users in the permissions page.

As I see, your are a newer on Drupal. I advice you to go throught the documentation to learn about Drupal, its conception and how it works.


add #ajax property to email field in node add form usion hook_form_alter

If the field is provided by the Email Field module it'll probably be:

$form["field_user_email"]['und'][0]['email']['#ajax'] = array(...

If it's just a standard text field it will be:

$form["field_user_email"]['und'][0]['value']['#ajax'] = array(...


autocomplete field show name pass uid to form

In your foreach you can add it

foreach ($return as $row) {
   $matches[$row->name . '[uid:' . $row->uid . ']'] = check_plain($row->name);
}

And in your submit handler you can find it with a simple preg_match like this one :

preg_match('/\[uid:(\d+)\]/', $form_state['values']['user_autocomplete'], $matches);
$uid = $matches[1];

Note that the $matches variable are not the same from the auto-complete part and the submit handler part.


How to ask drush to add timestamps to output?

It doesn't look this is possible. There is a list of available commands for drush make here: http://www.drushcommands.com/drush-7x/make/make


Multiple Views filters criteria : query with LEFTJOIN instead of INNERJOIN?

Checking the "reduce duplicates" fixed the issue for me.

In "Views setting" (admin/structure/views/settings), check "Show the SQL query"

Then, we can see the SQL query built with views.

With reduce duplicates, INNER JOIN are converted to LEFT JOIN, which is exactly what I need I think.

When it was unchecked, the SQL query was :

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
INNER JOIN {taxonomy_index} taxonomy_index ON node_field_data.nid = taxonomy_index.nid
LEFT JOIN {taxonomy_index} taxonomy_index2 ON node_field_data.nid = taxonomy_index2.nid AND taxonomy_index2.tid != '2'
WHERE ((taxonomy_index.tid = '2')) AND ((taxonomy_index2.tid = '10'))
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0

When it is checked :

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {taxonomy_index} taxonomy_index_value_0 ON node_field_data.nid = taxonomy_index_value_0.nid AND taxonomy_index_value_0.tid = '2'
LEFT JOIN {taxonomy_index} taxonomy_index_value_1 ON node_field_data.nid = taxonomy_index_value_1.nid AND taxonomy_index_value_1.tid = '10'
WHERE (taxonomy_index_value_0.tid = '2') OR (taxonomy_index_value_1.tid = '10')
ORDER BY node_field_data_created DESC
LIMIT 11 OFFSET 0


Show block only on node view page, not in node create or edit form

Use this in your block configurations page "Show block on specific pages" > "Show if the following PHP code returns TRUE"

if(arg(0) == 'node' && is_numeric(arg(1)) && ((arg(2) == "" || arg(2) == 'view'))) {
  return TRUE;
}

Hope this will help.

You will need to enable the core module PHP.


How to inject a service in another service?

The service you need is entity_type.manager:

.services.yml

services:
  hsbxl_members.membership:
    class: Drupal\hsbxl_members\MembershipService
    arguments: ['@entity_type.manager']

MembershipService.php

namespace Drupal\hsbxl_members;

use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Class MembershipService.
 */
class MembershipService {
  protected $hsbxl_member;
  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public function MembershipsAll() {
    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $query->condition('status', 1);
    $nids = $query->execute();
    return "Hello World!";
  }
}

The create() method is unnecessary as services use constructor injection.


Field rendered invisible when code block enabled

I found out why. It seems our designer chose to add display:none to ajax-processed class, which is added to #ajax calls.


The modules you were experimenting with and then disabled, did you go through the uninstall process?
Also, flush you caches.

I hope that helps.


Is there a way to add terms for the Spell Checker in editor to reference?

Checkout the following modules:

Wysiwyg SpellCheck

  Wysiwyg SpellCheck module is a plugin for wysiwyg editor that enables TinyMCE spellchecker plugin.

Spell Checker

  This module supports spell checking of node content (including title, body and CCK fields).

Image from project page.


How can I display a custom field for node reference in another content type?

You can create a view for the entity reference field  with the fields whichever you want to list.

Below is the setting for the entity reference to select a view

In Field Setting--> Entity selection-->Mode -->Select Views and assign the same to "View used to select the entities *"

Here is the link to create a view of entity reference type link,


Can you set the directory from which the Media module populates its Library tab?

The Media Browser does not work with a physical path, but with the file managed table, and Drupal file system uses the uri of the file to get to the actual file.

Go to the views settings page admin/structure/views/settings and turn on 'Show the SQL query'.

Then open up the media browser and look at the SQL query. It starts of with

SELECT file_managed.timestamp AS file_managed_timestamp, file_managed.fid AS fid, SUM(file_usage.count) AS file_usage_count
FROM
{file_managed} file_managed

which means it is using the file_managed table as its base. That comes from the file module in Core. Looking at that table definition in PHPMyAdmin for instance will reveal a fid as the primary identifier, a filename, a uri, filemime and some other fields. The uri is the important part as it tells Drupal how to get to files. The uri is prefixed by the stream wrapper (PHP classes that provide a common interface for getting to resources) and the two common Drupal ones are public:// and private://.

The media module already provides a remote internet sources wrapper, and Remote stream wrapper module provides a Remote Url plugin for the media module.

You can also write your own. Writing stream wrappers


CDN module - serving files from subdomain - setup

If you are using the Amazon Cloudfront - You are using origin pull cdn in which case you can:

Create an custom origin in there service
http://aws.typepad.com/aws/2010/11/amazon-cloudfront-support-for-custom-origins.html
Point that url that you get from cloudfront to a cname in your dns info in you admin panel in hosting setup
Install the cdn module enable it select origin pull and add the mapping the for files

Then save and you should be good to go

If you wanted to make an attempt at file conveyor that can be found here

http://fileconveyor.org/


Set a condition in views to remove title link

Add a boolean field to your node to determine if the link is shown or not. Let's suppose it's called Show Link
In Views add the Title field and then check 'Exclude from display'. Don't check 'Link this field to the original piece of content' here.
Add a Field that you can use to build your link, e.g. Content: Path. (You could also use Content: Nid.) Check 'Exclude from display' so this does not show.
Add the Show Link field and select the formatter type to be Key - this is important! it won't work without it
Rewrite the output of the Show Link as, e.g. [Title]. Check the box to 'Output this field as link'. And then fill in the path box with, e.g. [path] or if you've gone the Nid route node\[nid]
Now edit the No results section of the Show Link field. In this case you want to output the Title without the link, e.g. [title]. Check the 'Count the number 0 as empty' In my testing I also have 'Hide if empty' and 'Hide rewriting if empty' checked.

Make sure you order the fields so that the ones providing the tokens for the rewrites come before the Show Link field.


CKEditor 4 library is not detected by Wysiwyg module

The WYSIWYG module is not compatible with CKEditor 4, because CKEditor 4 uses double quotes " around it's version string, where CKEditor 3 used single quotes '. This breaks the version detection regex in the WYSIWYG module.

You could use CKEditor 3, like Bruno suggests, or you could patch the WYSIWYG module like described here https://drupal.org/comment/6790812#comment-6790812.

In editors/ckeditor.inc, replace line 81:

if (preg_match('@version:\'(?:CKEditor )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

with:

if (preg_match('@version:[\"|\'](?:CKEditor )?([\d\.]+)(?:.+revision:[\"|\']([\d]+))?@', $line, $version)) {

If you're not bound to using the WYSIWYG module, you could also use the CKEditor module.


Getting all the Submitted field values after the Webform is just submitted in Drupal 7?

If you are able to upgrade Webforms, preview functionality is now part of the 7.x-4.x branch of the Webform Module. There is an involved discussion about it here: Summary/review/preview page before final submission in multistep forms.


answer found.

I've resolved this by adding new Blocks instead of background images:

Thereby adding Images, that are links to my header.

In the CSS files i then adjusted the position and opacity.

Greets,
Chris


302 redirect can happen due to Either server settings or manual redirect inside modules using functions like drupal_goto....

You need to debug to understand the problem.. Here are the steps to find out where it is going wrong...

To make sure it's not related to server settings go and comment below line in drupal_cron_run function inside includes/common.inc...

// module_invoke_all('cron')

If you cannot able to replicate 302 error then it's for sure some module which is implementing hook_cron is doing above redirect other wise check your .htaccess or server settings to debug more..
If you don't see 302 error go and uncomment above code you have commented to debug further...
Run below code in any page to understand which are modules implementing hook_cron.....

Code:

foreach (module_implements('cron') as $module) {
  drupal_set_message($module);
}

Verify all above modules which implements hook_cron doesn't have any redirect code.. Check custom modules in particular...
If nothing works.. Use Debugger like XDebug to debug step by step.