You don't have to wrap your code with a behavior or jQuery at all. That depends:
If you want to use jQuery object with the $ as a shorthand:
Wrap your code like this:
(function($){
  //$('#something').show();
})(jQuery);

If you want to execute something after an Ajax DOM change and on document ready event
Use behaviors.
Drupal.behaviors.ysu_premium = {
  attach: function (context) {
    //jQuery('#something').show();
}}

You can wrap the behavior with the above jQuery wrapper if you want to use jQuery.
(function($){
  Drupal.behaviors.something_unique = {
    attach: function (context) {
      //$('#something').show();
    }}
})(jQuery);

When I'm working on Javascript, I always use the last snippet above.


How to register Post Submit handler for form?

I added the following snippet in hook_form_alter:

array_unshift($form['#submit'], 'callback');
foreach ($form['actions'] as $action => $values) {
    if (isset($form['actions'][$action]['#submit']) && is_array($form['actions'][$action]['#submit'])) {
        if (!in_array('callback',$form['actions'][$action]['#submit'])) {
            array_unshift($form['actions'][$action]['#submit'], 'callback');
        }
    }
}

This registers to all actions.


Is it possible to call a function but disable that functions hook calls?

You can't stop the hooks from being invoked unless you edit drupal_alter (or file_create_url) directly.

But you can use static vars to short circuit your own implementation so it only runs once for a given $uri:

function MYMODULE_file_url_alter(&$uri) {
  $processed_uris = &drupal_static(__FUNCTION__, array());

  if (!in_array($uri, $processed_uris)) {
    $processed_uris[] = $uri;

    // Even though this call will re-invoke the current function, the URI has been
    // processed, so no infinite loop.
    $foo = file_create_url($uri);
  }
}


How to add tri-state checkboxes to form created with Form API?

From what I understand, the indeterminate property of a checkbox is purely a visual thing, and also cannot be set with HTML, which in turn means that you won't be able to use the FormAPI or create an indeterminate element without JavaScript.

Chris Coyier sets out some example situations though in this blog post, but an important quote is below (in case the post goes down).

  Here are some things to know about indeterminate checkboxes:

  You can't make a checkbox indeterminate through HTML. There is no
  indeterminate attribute. It is a property of checkboxes though, which
  you can change via JavaScript.

I should imagine you could probably use Drupal.settings to your advantage here though, and run the check server-side for "true for some children", and pass an array of ID's through to Drupal.settings. Following that run something like the following in a Drupal behaviour:

 // This is an array of IDs
 trueForSomeChildren = Drupal.settings.myModule.trueForSomeChildren;

 $(trueForSomeChildrenjoin(', ')).attr("indeterminate", true);

Howeverm I don't think there's an already-built module to do what you want. There is a patch here for the FacetAPI where they allow for indeterminate, but it kind of follows this example.


Does Drupal strip out style and span tags?

Go to Configuration -> Content Authoring -> Text formats. Here you can configure what tags are allowed.

All unallowed tags are stripped out,  is always stripped out.

Check out https://www.drupal.org/project/wysiwyg_filter for more advanced filtering.


Rotating Banner Module Shrinks Banner Image When It Should Not

I think the module is a bit buggy.
I changed it to not have the dynamic size setting, but went with static
but just didn't put in a height/width.
Since I am using bootstrap with drupal I surrounded the image with a

...

Which then forces the image to dynamically respond properly.
So, a hack.


Adding a flag to Menu Content Link to display as a non-link

The module Special menu items allows you this, even some control over the HTML output.

This is now in Drupal core (although Docs need some updating):

  This features is in core for >=8.2.0. Create menu without link by entering route: <nolink>.

That is, you enter into Link:

route:<nolink>

and select:

Show as expanded

if you need it for drop-downs.


You can't add a form field to an entity display. You have to approach this the other way. Build a form class with the field and the submit button and add the entity content to it. Then you can respond to the posted data in the submit method of the form class and save it to the entity.

For the ideal solution you can attach ajax to the submit button to avoid a page reload.

An alternative option is an entity form using a custom form mode containing one field. This could be set up without code by using blocks for both, the entity content and entity form or only one of them and the other as page. This depends on what the end result should look like. You need a module to control the form modes Form mode control and to put an entity form in a block Entityform block. The entity content can be placed in a block with Views. For a custom entity all of this can be done in code as well.


By trawling through the code, I found this handy function in the Entity code, and it works perfectly:

 $elements = $webform->getElementsDecodedAndFlattened();

This gives a nice array of the elements in the webform itself.

If you want the results of a submission, grab that entity and use:

$data = $entity->getData();

I hope this helps


Thank you for Berdir's help but I noticed that I was missing some information on my drupal7_fruit migration file like the values for field_image and migration dependencies.

The working solution:

migrate_plus.migration.drupal7_image.yml

id: drupal7_image
label: Images
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_file
  constants:
    source_base_path: '/var/www/username/drupal7/' # Full location of your drupal7 site
process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
  uid: uid
destination:
  plugin: entity:file
migration_dependencies: {}

migration_plus.migration.drupal7_fruit.yml

id: drupal7_fruta
label: "Migrate Fruit Content Type"
migration_group: drupal7
migration_tags:
  - Drupal 7
source:
  plugin: d7_node
  node_type: fruit
process:
  nid: nid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_description: field_body
  field_image: # Image field name in Drupal 8 site
    plugin: iterator
    source: field_photo # Image field name in Drupal 7 site
    process:
      target_id: fid
      alt: alt
      title: title
      width: width
      height: height
destination:
  plugin: 'entity:node'
  default_bundle: fruit

migration_dependencies:
  required:
    - drupal7_image

Hope this may help anyone with the same problem in the future!


HTML tags after umlauts causing premature header sending - CK editor

Issue solved by server admin. It was about ModSecurity Apache2 settings. POSTs were rejected because they triggered new ModSecurity XSS alerts. So server admin excluded some rules. He found them in Apache2 error log and exluced them in Apache 2 conf file.


Attempt to charge recurring fee 2 failed

Authorize.net renewals cannot be tested while your authorize.net account is in "Test Mode". I have tested and confirmed this. It will work if you set the account to live mode.

You can see the relevant discussion here: http://drupal.org/node/812922


The Userpoint provides a mean to store a user credits and can be combined with the Userpoints Node Access to sell node (ie. content) access in exchange of userpoints (credits). The User points Nodes and Comments allow you to setup automatic rewards for content contribution (ie. nodes and comments creation). But it doesn't seems to provides the rating feature you ask for, nor does any of listed User Points Contributed modules.

What should be easily doable, is to use the Fivestar to rates node and then to grant, and revoke userpoint to the rated node author on voting (hook_votingapi_insert() and hook_votingapi_delete()). By restricting access to voting (ie. the 'rate content' permission or through an hook_fivestar_access() implementation), you can control who is allowed to grant credits to your users.


How to set specific Meta Tag values while creating Article Content.?

You don't need any code for that, that Metatag module has that functionality built into it

These 2 listed features could apply to your use case specifically:

  Per entity and per entity bundle to control default meta tags for all items of a certain type, e.g. all nodes of a certain content type.
  Ability to override meta tags on each entity object, e.g. to override meta tags on an individual node.


Create custom path alias when new user is added in drupal 7

If I understand your question correctly, you're wanting to implement Pathauto's API. Here's a tutorial on how to do so. Basically, you need to implement hook_pathauto() and make use of pathauto_create_alias() & path_delete() when you're performing your Create/Update/Delete operations. It looks like you can use the token_type of user for your token replacement.


How to get flag count for any time period

Did you try to use the filter criteria : Flagged Time and eventually expose it to users?

Then you can define :
- the operator: is equal to / is less than / ...
- a specific date or offset

Is that what you are looking for?


How can one Rewrite results of a view using a Group By

You can use both Rewrite and Grouping at the same time. You can Rewrite the field and use that as Group by.

If you need the same Field in the results as well as in the Group by headings, then simply add the Field twice. You can style/Rewrite them separately too.

If you want to style the grouping in a special way, or need more than one field in the Group, then you can use the Custom text field for advanced styling of the Group. You can see an example in this article: Control Group by styling with Custom text field


You can implement hook_menu_alter() in a module to alter the access callback used for the "user/%user" path.

The code I would use is the following one, which is generic enough not to take assumptions about the access callback already set, and the arguments passed to that access callback. This means the code will work even if there is another module that alters the access callback for the same path.
The same code would work for Drupal 6, once you replace any occurrence of user/%user with user/%user_uid_optional.

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

function mymodule_user_view_access($account, $callback) {
  $args = func_get_args();
  // Remove $account and $callback from the arguments.
  unset($args[0], $args[1]);

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

  // 1
  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return ($GLOBALS['user']->uid == 1);
  }
  // 1

  // Let the previously set access callback decide who has access to the user account.
  return call_user_func_array($callback, $args);
}

The code would not allow any user to access the super user account, except to the super user. If you want to allow the users with the permission to administer users to see that user account, you can replace the control statement commented with // 1 with the following one.

  if ($uid == 1) {
    // The user ID is 1; only that user can view that user account.
    return user_access('administer users');
  }


How to map path aliases when migrating from Drupal 6 to 8?

You need to explicitly disable pathauto in your migration:

process:
  path/alias: alias
  path/pathauto:
    plugin: default_value
    default_value: false


What's the difference between enabling Node View (and adding a variant) and creating a new Panel page?

Page Manager allows you to intercept existing paths or create new paths in the system.

As the node view path already exists, and you want to change the way it operates depending on some conditions (bundle for instance) you need to enable a copy of node view path in Page Manager, instead of creating a new one (as it already exists you cannot create a new one as it will conflict)

EXAMPLE: For all nodes of bundle type Article, when the user attempts to view such an article, you want to perform some ACTION. So you override the node view path, create a variant that filters on bundle of Article, then perform some ACTION.

The ACTION is pluggable. You can do a redirect for instance. So when the user attempts to view an Article you intercept that, look at some context on the specific article (lets say there is an Entity Reference field to a Basic Page), then redirect to that Page.

Panels has a plugin component for Page Manager. So when your condition to view an Article for instance is satisfied in Page Manager (via your variant), you can select that Panels take over the rendering of the page.

The beauty of Page Manager is that it intercepts the requested page and then makes all kinds of context on that page available, such that you can make decisions (via created variants) on what to do, and when you for instance make the decision to pass the rendering over to Panels, you have all the context available to you. You can even load more context if you wish. On a node you have limited author information available such as the Users uid, but with Page Manager you can request that it pulls in the User entity to make other fields available such as email etc. You can continue to bring in related context in this fashion: think about the case of a node that has an entity relationship to another type of node that has an author (User) that has a taxonomy reference etc. Access to more context is very helpful. Think of the difficulty with a Views Block. It only has access to the menu object's key (node id etc) and url parameters. But in Panels (via Page Manager) you can embed a View Content Pane and pass as much context to it as needed.

SO in essence, the Page Manager - Panel relationship is merely the way by which you decide what paths and what conditions on that paths must be satisfied in order for Panels to take over the rendering with access to lots of context.


"Undefined index: #parameters" and other error in custom module

You could write a small custom module that -

Form alters views exposed filter form of the particular view in question
Add a new validate function to the form above (validate function is called before the actual form submit function is called and allows you to manipulate values)
Then in the validate function you could edit the particular exposed filter form field replacing commas with nothing.

Here is a sample code that I found on Googling around - http://drupal.org/node/716420#comment-2634540

Hope this helps.


How to display users with same select list value on a custom user profile page

The problem is you're relying on your contextual filter to mean 2 things:

For the page it has to be the UID.
For the block it has to be the country select value that corresponds to the UID.

If you're wanting to configure it this way, you'll need your block view to derive the profile country value from a UID. One way you could do this is to use Provide default value > Type: PHP Code options with something like this:

if ($user = user_load(arg(1))) {
  $profile = profile2_load_by_user($user);
  return $profile['my_profile_machine_name']->field_my_country_field_name[LANGUAGE_NONE][0]['value'];
}

The actual code will vary based on your Profile2 configuration.


Drupal implementing an advertising takeover with page background image

In your theme's preprocess_page() hook you could set a variable that is accessible in your page.tpl.php file.  Basically something like:

function YOURMODULE_preprocess_page(&$vars) {

  $vars['background_image']=make_me_a_background_for_page($_GET['q']);

  // other page preprocessing goes here

}

where make_me_a_background_for_page() is a custom function that returns a path to an image based upon the page being viewed.  You can then use that variable however you want to create the background.

One way would be to put a quick div in the page somewhere like...

<?php if (!empty($background_image)): ?>

<?php print $background_image; ?>

<?php endif; ?>

and have it hidden in css:

#use-this-background-image {
  display: none;
}

and then use jQuery to set the body's background to it:

// Drupal Behaviors Wrapper here :)

  if ($('#use-this-background-image').length) {
    $('body').css('background-image','url("' + $('#use-this-background-image').text() + '")');
  }

// Drupal Behaviors Wrapper here :)

An added bonus of doing it in this somewhat convoluted way is the background image isn't loaded until after your page is, so it pops in after the content, which, to me at least, is nicer looking than watching a big background load and THEN the content.


Only the original author knows what he meant by this, as the distinction between implicit and explicit does not have any special technical meaning within the context of Drupal that differs from the normal distinction made in plain English.  Nonetheless, here are my thoughts.

The relationships are implicit because there is nothing in the database to define them and give them meaning.

For example, take nodes and users.  The {node} table has a uid column.  What does this mean?

It is implied in Drupal that this is the author.  But, it could really be anything: author, owner, sponsor, etc.

In some database designs, tables will never have relationships (ie, foreign keys) to other data
tables directly (I forget which normal form this is).

To do this in Drupal, you would alter the {node} and delete the uid column.  Then
make a {node_x_users} table that looked something like

CREATE TABLE  `node_x_users` (
  `xid` int(10) unsigned NOT NULL default '0',
  `nid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `rid` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`xid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`),
  KEY `rid` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The actual relationships, via (foreign keys to other tables) would be stored in this table and not in {node} or {users}.  You would also make a table like

CREATE TABLE  `relationship_labels` (
  `rid` int(10) unsigned NOT NULL default '0' COMMENT,
  `type` varchar(128) NOT NULL default '',
  PRIMARY KEY  (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This would store a text version of what the relation type is so you could explicitly define them.

So, when you make a node, you insert the node into {node}, get the $nid (which is the PK of the table), then insert the relationship into the cross table, {node_x_users} along with the $uid and the key representing the type of relationship.  When you render a node, you also JOIN on the {relationship_labels} to get the "Authored by", "Edited by", etc text.

In the code you end up with more JOINs (but they are all on simple, indexed types), but you also gain some other advantages, the biggest benefit is a very flexible data model.

Personally, I see this as one of the biggest problems with the current Drupal architecture.

An example of a system that does relationships like this is CollectiveAccess.


How do I increase the memory assigned to PHP?

I increased the max_execution_time to unlimited and I used output buffering for keep my script in progress. Change the memory limit to 1024M. I got it from This URL.


How to direct user to a custom path after executing a Views Bulk Operations action?

Its like altering normal form using hook_form_alter:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}


render form in page--node--add--contenttype.tpl.php

Can you try this code in page--node--add--yourcontenttype.tpl.php

module_load_include('inc', 'node', 'node.pages');

$form = node_add('your node type');

print drupal_render($form);

Refer Change aspect of node add form (not only via css)


Drupal feeds module causing high cpu usage when pulling feeds

If you are in shared hosting, then it is the right time to upgrade to VPS or Dedicated Server.

I had a same issue How to control resource usage of my website? , better you can remove the unwanted bots. You need to see the Access Log in your hosting control panel.

try disabling your modules one at a time to decide when the load time gets really high and remove the unwanted modules and also it delete from modules folder.


If I understand your question correctly, you want to display the 'Search form' block for a specific content type.

On admin/structure/block/manage/search/form/configure you can change the 'Visibility settings' and show the block for specific content types. Below a screenshot where I have selected to display the search form on nodes of my custom content type 'Blog overview':


You can use Form API #states attribute. This will allow you to trigger something based on another fields information. Below should be a working example.

$form['vin'] = array(
  '#type' => 'textfield',
  '#title' => t('VIN'),
  '#default_value' => '',
  '#states' => array(
    'required' => array(
      ':input[name="ask_required"]' => array('checked' => TRUE),
    ),
  ),
);


What's the command to migrate images too?

Thanks guys for helping out! I figured it out and migrated all my images and files. Here's what I did for anyone who has the same problem:

I'm was using WAMP and WSL Ubuntu, I was setting the legacy--path incorrectly so my source_base_path was incorrect. I had to open up migrate_plus.migration.upgrade_d7_file.yml and used the correct path. Then I ran drush config-import to import the updated file and then ran the migrate.

Here's my file:

uuid: 2a4842a5-0869-4984-aaae-68d6c5814f5d
langcode: en
status: true
dependencies: {  }
id: upgrade_d7_file
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Content
migration_group: migrate_drupal_7
label: 'Public files'
source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: /mnt/c/wamp64/www/d7
process:
  fid:
    -
      plugin: get
      source: fid
  filename:
    -
      plugin: get
      source: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    -
      plugin: file_copy
      source:
        - '@source_full_path'
        - uri
  filemime:
    -
      plugin: get
      source: filemime
  status:
    -
      plugin: get
      source: status
  created:
    -
      plugin: get
      source: timestamp
  changed:
    -
      plugin: get
      source: timestamp
  uid:
    -
      plugin: get
      source: uid
destination:
  plugin: 'entity:file'
  source_base_path: /mnt/c/wamp64/www/d7/sites/default/files/
migration_dependencies:
  required: {  }
  optional: {  }


You can pass down your region's ID as parameters to your route. For example:

...

As explained here you can add arguments from the route to your form.

On the buildForm method you can have something like this

public function buildForm(array $form, FormStateInterface $form_state, $region = NULL) {
  // Your code...
  $form += [
    'button' => [
      '#type' => 'button',
      '#value' => $this->t('Submit this form),
      '#name' => 'ajax_trigger',
      '#ajax' => [
        'callback' => '::updateRegionAjaxCallback',
        'wrapper' => $region, // Assuming $region is the argument passed down.
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'click',
      ],
    ],
  ];
}

Later your callback method could look like.

public static function updateRegionAjaxCallback(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $response->addCommand(new AppendCommand(NULL, [
    // Your render array with the data to be displayed.
    '#cache' => [
      'max-age' => Cache::PERMANENT,
      'contexts' => ['url'],
    ],
  ]));

  return $response;
}

This should work but keep in mind that will be best capture the form submit and triggering a custom AJAX event.


How can I create a "related content" view but display it as a page with an url alias?

You could create two new views for this. For example:

Create a new page view and name it something like Event_Photos.
Set the path to be something like `event/photos/%'.
Add an argument of type Content:nid.
Setup a relationship using the field that references the photos from the event content-type.
Add a filter using the above relationship of type Content:Type = photo.
You will also need to use the relationship for all your fields.
In your first view, rewrite the output for the photo link to event/photos/nid.
Create a second view for your other content type and follow the above steps.

It would also be possible to use a url in the form your-event-title/photos. Then you would have to change the path to %/photos and use a argument like Content:Title instead.


How to modify field value in other nodes after node update?

Use hook_form_alter or hook_form_FORM_ID_alter
Add a custom validation that runs after all validation has passed
$form['actions']['submit']['#submit'][] = 'mymodule_update_referenced_nodes';

Then in that function
function mymodule_update_referenced_nodes(&$form, \Drupal\Core\Form\FormStateInterface $form_state){

  $field_other = $form_state->getValue('field_other')[0]['value'];

  $references = $node->get('field_referenced')->referencedEntities();

  foreach ($references as $referenced_node) {
    $referenced_node->field_other->value = $field_other;
    $referenced_node->save();
  }

}


I used ckEditor, it works fine.

You can also install wysiwyg which manage many wysiwyg editor like ckeditor and others.
You can try simple editor too.


How do I manually set tnid when migrating nodes?

You want to give the node a language, and set the source node in the translation_source key:

$node->language = 'es';
$node->translation_source = node_load(66);

Reference: https://api.drupal.org/api/drupal/modules!translation!translation.module/function/translation_node_prepare/7


how can I set #attributes for each item of selectlist

function MYTHEME_select($vars) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . MYTHEME_form_select_options($element) . '</select>';
}

function MYTHEME_form_select_options($element) {
  // Build up your own version of form_select_options here
  // that takes into account your extra attribute needs.
  // This will probably involve inspecting your custom FAPI property,
  // which we'll call #extra_option_attributes
}

And your code in the form would be something like:

$form['select'] = array(
  '#type' => 'select',
  '#options' => array(1 => 'One', 2 => 'Two'),
  '#extra_option_attributes' => array(
    1 => array('title' => 'Test title'), // Attributes for option with key "1",
    2 => array('title' => 'Test title'), // Attributes for option with key "2",
  )
);

In MYTHEME_form_select_options() you can then inspect the element's #extra_option_attributes key (if one exists) to see if you need to physically add any more attributes in the HTML you create.

Credit to @Clive for this post : https://stackoverflow.com/questions/9261224/adding-attribute-to-option-element-using-forms-api-drupal-7/9264589#9264589 .. Cross posting here in Drupal Q & A


is it possible to disable ckeditor for private messages?


Key / Value fields module where you can choose the type?

You can use the Field Collection module to achieve that functionality:

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

The idea is:

Create a Field Collection.
Add key/value fields to it with the field types of your choice.
Add a Field Collection field to the content type you want these key/value fields on.
Set the source of that Field Collection field to the new Field Collection you've just created.
Repeat for whatever other content types you need to.


You can use

{{ loop.index }}

this will count up each time it goes through the loop


Only allow 1 submission from an email address in webform

Edit the email field in the webform and check both the "mandatory" and "unique" options.

In this case, it would accept entries only for unique mail id's


the simple solution to this issue, is to pass $element by reference to the first element validator:

function MYMODULE_validate(&$element, &$form_state) {
  (...)
  form_set_value($element, $new_value, $form_state);
  $element['#value'] = 'new_value';
}

This way, the $element['#value'] (used by the taxonomy_autocomplete_validate) can be modified and the following validators will.

The form_set_value() is not required, but since the form value has changed, it makes sense to update the state as well.

* many thanks to @ciss for helping troubleshoot the issue on #drupal and suggesting the pass by reference.


Change the front page basing on the domain

I've already find the answer by referring to Programmatically set the front page per site?. It is much simpler than the reference, because I just want to map the domain with my static page and I don't have a multisite drupal.
So, I just add an event subscriber and put all the mapping there.

  In the getSubscribedEvents method you need to set the weight to something greater than 30 which overrides the Page Cache and Dynamic Cache.

$events['kernel.request'] = ['kernel_request', '35'];

  Add this function in the same event subscriber file

public function kernel_request(Event $event) {
$config = \Drupal::configFactory()->getEditable('system.site');
$site_path = \Drupal::service('site.path');
$site_path = explode('/', $site_path);
$site_name = $site_path[1];

if ($site_name === 'site2' && $event->getRequest()->getPathInfo() == '/') {
  $config->set('page.front', '/node/239')->save();
}
else {
  $config->set('page.front', '/home-content')->save();

}
}


Pass along field delta value to a rendered entity in an entity reference field

I did something like this in Drupal 7 and did have caching issues as 4k4 mentioned, but I think the cache issues would be easier to avoid in D8. I think you could do this by creating a new Field Formatter that extends EntityReferenceEntityFormatter.

You should be able to alter just the viewElements() method and add the delta information to the referenced entities. You'll have an issue with the view mode being cached with your delta info. For example, you may have an entity be the first item the first place it's referenced and the second item the second place it's referenced, but it'll be cached from the first call so your delta alterations won't work how you'd expect. I think you can update the #cache settings for the entities and add a new key for the delta. I would start by calling parent::viewElements() and then make a pass through that result to make the alterations (adding the delta value and updating the cache settings). I think this will work, but I still get confused by the different caching layers in D8.

I would still alter the field template for the parent EntityReference field and add the class to a wrapping div rather than on the entity itself. You could create your own template file and add your own theme suggestion to make it more reusable, something like field__zebra, rather than relying on the default theme suggestion you mentioned above, field__my_field_name. I love Display Suite so I would create a Zebra DsFieldTemplate that I could easily reuse on any field I wanted.


Where is body field label stored in database

The field label, together with all other settings are stored as a serialized array in the field_config_instance table.

Manually changing a serialized array is usually a bad idea, it can destroy the data in there if you don't know what you are doing.


I'm not sure you can do that, I think the Zoom level has to be an INT.
Basically there is as many tiles'size as the number of zoom available.
That means there is no tiles available for a float value, otherwise it will require too many tiles to have a map not fuzzy.


Copy value of field into the value of a different field

@Volker's tip gave me everything I needed and it's pretty simple as it turns out.

if (!empty($form_state['values']['some_other_field'])){
  $form['title']['#value'] = $form_state['values']['some_other_field'];
}

Set that in a hook_form_FORM_ID_alter and it works great.  The part I didn't have was the #value.


How to programmatically submit a form that has a file-field using drupal_form_submit()?

This wasn't as hard as I expected; Drupal has different handling for fields with '#type' => 'file' as opposed to other types. There are two ways of solving the problem. One is simply adjusting the request-payload, expressed here as a curl command:

curl -i \
    'https://example.com/drupal/my_rest/my_resource' \
    -H 'Accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -F "files[spreadsheet]=@my_spreadsheet.xlsx" # note the weird field-name
# This automatically uses the POST method, so Drupal reads it as a 'create'

Drupal munges file-field-names by default apparently apparently to match the file.inc code. This is stated expressly in comments:

if (!isset($element['#name'])) {
    $name = array_shift($element['#parents']);
    $element['#name'] = $name;
    if ($element['#type'] == 'file') {
        // To make it easier to handle $_FILES in file.inc, we place all
        // file fields in the 'files' array. Also, we do not support
        // nested file names.
        $element['#name'] = 'files[' . $element['#name'] . ']';
    }

If you want to API-endpoint users from the implementation shown above, the other solution is to explicitly provide a '#name' value for the file-field in question, as should be obvious:

return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#name' => 'spreadsheet_file', // <-- adding this prevents name-munging
            '#title' => 'Spreadsheet file',
            // ...

Note of course that the above might have consequences for other sections of code if the file used to be expected under the old name.


If I gather correctly what you are asking then you are hitting https://www.drupal.org/node/2824714 . You need to write your own composite element, webform for now doesn't support this.


I used something like this in one of my installations:

// create a table of nodes of a specific content type
function MYMODULE_create_table($node_type) {
  // setup headers
  $headers = array(
     array('data' => 'Nid'),
     array('data' => 'Title', 'field' => 'title'),
     array('data' => 'Status')
  );
  // build query
  $query = db_select('node', 'n')->extend('PagerDefault');
  $query->limit(30);
  $query->fields('n', array('nid', 'title', 'status'));
  $query->condition('n.type', $node_type, '=');
  // make it sortable
  $query = $query->extend('TableSort')->orderByHeader($headers);
  // execute query
  $result = $query->execute();
  $rows = array();
  foreach($result as $node) {
    $rows[] = array(
       $node->nid,
       $node->title,
       $node->status
    );
  }
  // add a pager if needed
  if(count($rows) && ($pager = theme('pager'))) {
    $rows[] = array(
      array(
    'data' => $pager,
    'colspan' => 3,
  )
    );
  }
  // return html for table
  return theme('table',
            array(
                'header' => $headers,
                'rows'=>$rows,
                'empty' => 'No products found...',
            )
    );
}

The above perhaps work just as is, but it might give you some clue on how this can be done.

TableSort


Close the iframe after login with Shadowbox module

Looks like a Closed [Fixed] bug in Issues for Shadowbox From the page here is a patch file.

shadowbox_login-additional_links-1488718-25.patch Or read the ISSUE alos check #6


Help text blocks show up randomly in node add/edit form with Drupal Bootstrap theme

The solution was very simple actually. It was a config in theme administration that set all text blocks having less than 200 chars as tooltips and not as help blocks. All I had to do is disabling that config:


How to remove number of reads under each node?

I needed a simple page counter but did not want to see the "reads" on every node page even as the site admin. For my drupal 7 "fusion" sub theme I used this in my template.php

function yourfusionsubthemename_preprocess_node(&$vars) {

unset($vars['content']['links']['statistics']['#links']['statistics_counter']['title']);

}


Views PDF CSS file not being applied on generated PDF

What worked for me is to rewrite the field. For the title field it would be something like:

[title]

And then use this custom class in my CSS file.


A way by which you can elegantly do this from a custom module would be:

/**
 * Implements hook_node_view_alter().
 */
 function my_mod_node_view_alter(&$build) {
   $node = $build['#node'];
   if (isset($build['comments'])) {
     // It is good practice to allow the administrator to see comments of all nodes.
     $build['comments']['#access'] =
       user_access('administer comments') || ($node->uid == $GLOBALS['user']->uid);
   }
 }


render($page['content']) in the wrong place!

The content in my node.tpl.php was wrapped in a tr tag. Don't know how it got there. When I removed it everything was fine.


How to print formatted contents of Computed Field and Full HTML Textarea in a custom template?

The Computed field defines its own formatting in the Display Code (PHP) box. If you have done your formatting there, when the page is processed, $vars will contain the output as:

Unsanitized: the output of Display Code (PHP) ($display_output) is unchanged.
Plain text: $display_output is filtered through the Plain Text filter.
Filtered markup: Non-permitted HTML tags are stripped from $display_output.
Raw Value: Display Code (PHP) is ignored and the value from Computed Code (PHP) is used ($entity_field[0]['value'] ).

This is fine for a rendered field using $vars. The Display output code is used when the node is preprocessed. If, however you wish to access the fields from the $node object, only the field value (Raw value) is presented. So you either have to duplicate the Display output code in your template, or you have to move the formatting into the Computed code box.

If you set your $entity_field[0]['value'] to the actual formatted string, then use the default $display_output = $entity_field_item['value']; in the Display output, you should be able to use the above code to display the field as is.

This is why it is much easier to use the processed fields. Instead of coding something like:

print $node->field_fieldname[LANGUAGE_NONE][0]['value'];

If $vars['field_fieldname'] has been set, the template file receives the result of extract($vars). Each array element becomes a variable in its own right and all you have to do in the template file is:

print $field_fieldname;

or

print render($content['field_fieldname'];

if you have not separately included it in $vars in a preprocress. Much simpler when you understand how the data gets moved around.


Yes You can just follow few steps given below :

Go to Structure > Content-Type
Click on Manage Fields of  {{Custom Content Type}}.
Edit the file field . From File directory remove [date:custom:Y]-[date:custom:m].
And you will end up with storing files under files directory


Is possible to update a project that has been installed from the archive file?

I got this working, I was very close but removing /vendor and composer.lock was what helped in the end.
Here are the steps from the top:

add the line
        "drupal/core": "~8.1"
to the 'require' statement (or update it to whatever version you require - in my case ^8.0 - latest Drupal 8 release).
Remove the drupal/core line from the 'replace' statement.
Add the following line somewhere (at the end? I believe this should replace the existing repositories statement, more information here.
):

"repositories": {
    "drupal": {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
}

Remove the /vendor folder
Remove the composer.lock file
Run your core update as follows

composer update drupal/core --with-dependencies


MODULE_preprocess_block() get rendered region in drupal 8

So, getting everything working here is the code I got to work.

use Drupal\block\Entity\Block;
/**
 * Implements hook_preprocess_block().
 */
function harfang_preprocess_block(&$variables) {
  $block = Block::load($variables['elements']['#id']);
  $region = $block->getRegion();

 // Add classes to all bocks in footer region.
  if($region == 'footer') {
 // Do something.
  }
}

added the use statement at the top and removed the non-joiners


'og:url' meta property displaying wrong path, messing up posting on external sites

Assuming your permissions are correct, you can override the settings for anything.

In your case, override Content, and expand the Open Graph section.  Then, you can pick the proper token.  I use [current-page:url:absolute]


How output JSON for multiple "Rest export" views?

One option would be to create a parent view and use Views Field View to reference the other 2 views displays.

For example, /car-stuff would contain 2 fields, "Cars" and "Tires", each one is a views field view field referencing the relevant json view display. For the parent view, you'd need to add REST Export Nested so the JSON of the child views would be proper JSON instead of a string.

Alternative Solutions

There may be a cleaner way to achieve what you're after.The easiest would be to make 2 calls to retrieve the JSON feeds and join them on the front end.

Depending on your requirements, you could also retrieve the specific tires for each car type.

{
    "cars": [
        { "nid": 1, "brand": "BMW", "weight": 100, "compatible_tire_nids": [100,101,102],
            "tires": [
              { "nid": 100, "brand": "Michelin" },
              { "nid": 101, "brand": "Good Year" },
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 2, "brand": "Mazda", "weight": 100, "compatible_tire_nids": [102],
            "tires": [
              { "nid": 102, "brand": "Dunlop" }
            ]
        },
        { "nid": 3, "brand": "Volvo", "weight": 1000, "compatible_tire_nids": [103],
            "tires": [
              { "nid": 103, "brand": "Unknown" }
            ]
        }
    ]
}

The above would also use Views Field View, with the child view Tires having a contextual filter of nid. For an example of this approach, see the answer I provided here.


How can I adjust Drupal links on shared hosting so that they don't point at the root?

You have a variable ($base_url) for this in settings.php, in /sites/default usually.

Set $base_url to match the address to your Drupal site:

$base_url = "http://www.example.com/~stef";

Hope that helps!

PS: There is also a url setting in .htaccess you may want to look at if the above does not work.


How to update all hyperlinks which are in the content

Export the database, run a find and replace over the dumped sql and re-import it.

e.g.:

#1 mysqldump ... > output.sql
#2 copy output.sql to output_mangled.sql as a backup
#3 perl -pi -e 's/content\/2012/content\/2013/' output.sql
#4 cat output.sql | mysql ...

Replacing ... with authentication and database specification parameters.

To be safer, make the regular expression in the replacement step more specific.


Add class and extra HTML to specific menu items with hook

You can add a custom class to menu items by using the Menu Attributes module. You can also use hook_menu_link for the same. For displaying the menu description, here is a sample code. Paste it in your template.php file

/**
* Implements theme_menu_link().
* Adds menu description under main menu
*/
function themename_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $element['#title'] .= '' . $element['#localized_options']['attributes']['title'] . '';
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Note : You've to use css/js to show/hide the menu description based on the screen size.


How do you create a custom Panels layout in an Omega sub-theme?

The basic process is:

Edit the MYTHEME.info file:

; PLUGINS
plugins[panels][layouts] = panels/layouts

Create a directory in panels/layouts/mypanel

Create your include panels/layouts/mypanel/mypanel.inc

/**
 * Implements hook_panels_layouts().
 */
function mytheme_mypanel_panels_layouts() {
  $items['mypanel'] = array(
    'title' => t('My Panel'),
    'category' => t('My Site'),
    'icon' => 'mypanel.png',
    'theme' => 'mypanel',
    'regions' => array(
      'top' => t('Top'),
      'left' => t('Left column'),
      'right' => t('Right column')
    ),
  );

  return $items;
}

Create your 50x75 mypanel.png, and place it as panels/layouts/mypanel/mypanel.png

Create the template file as panels/layouts/mypanel/mypanel.tpl.php

<div class="panel-display mypanel" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>>

<?php print $content['top']; ?>

<?php print $content['left']; ?>

<?php print $content['right']; ?>

Upload, clear cache, and see if you can make a panel page.  Nine times out of ten, the problem with Panels picking up custom panel layouts has to do with a misnamed include or template file, which I suspect is your problem.


There is (and should only ever be) one anonymous "user" for your site.  That will be in your db users table as uid 0.

If you'd like to count the number of anonymous users that are visiting your site at a certain time you can adapt (to a custom module) something like this that is used in the admin_menu module (this is from admin_menu.module 7.x.3.0-rc starting around line 395:

function admin_menu_get_user_count() {
  $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
  $count_anon = admin_menu_session_count($interval, TRUE);
  $count_auth = admin_menu_session_count($interval, FALSE);

  return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}

function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

And then output the return values. If you want to count the all time number of anon visits to your site than that is a different story. If so, please update. Thanks.


$form['redirect'] = "something=$someId"; doesn't work in Drupal 7

What you set in $form_state['redirect'] can be:

a string containing the destination, such as node/1, admin/reports/status, or user/1.
an array of arguments compatible with drupal_goto().

The examples shown in drupal_redirect_form() are the following ones:

This redirect the form to node:

$form_state['redirect'] = 'node';

This redirect the form to node/123?foo=bar#baz:

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

In your case, if you want to redirect to page/$nid, you should use the following code:

$form_state['redirect'] = "page/$nid";

If you really want to redirect to page=$nid, then you should use the following code:

$form_state['redirect'] = array(
  array(
    'query' => array(
      'page' => $nid,
    ),
  ),
);


Can someone explain how Text Formats work with CKEditor profiles? Very confused

The text formats have to do with how the text is being processed as you can have functions that process icon labels, tokens, video snippets, etc. Sometimes you don't want certain roles to have access to these properties.

For example, I wouldn't want to give a normal user access to add certain HTML tags or YouTube video tags, but I would want to give that access to a content editor.

With CKEditor, you can then assign a CKEditor profile with a certain set of buttons to each text format. For example, I would give a CKEditor profile with a lot of buttons and functionality to an admin or content editor, so I would pair that with the Full HTML text format, but I want to slim down the CKEditor profile for a regular user, so I would pair that with the Basic HTML text format (if I created one).


If the PHP file is in the same directory where cron.php, and index.php files from Drupal installation are, then you can use the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}

If the PHP file is in another directory, then you should use the following code.

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', 'the directory containing the includes directory from Drupal');
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  //...
}


How can I "form alter" fields in a nested Paragraph, depending on where the field is used

In this scenario, we have field_caption being used in various places inside a cta paragraph. The business has asked to limit field_caption to 25 charaters, but only when it is being used in a node on an entity reference field called field_foo_cta.

First we add a #process callback to the widget based on whatever rule, by implementing hook_field_widget_form_alter:

function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, &$context) {
  $field_definition = $context['items']->getFieldDefinition();

  if ($field_definition instanceof FieldConfig) {
    $config = $field_definition->id();
    list ($entity_type, $bundle, $field_name) = explode('.', $config);

    if ($entity_type == 'paragraph' && $field_name == 'field_caption') {
      $element['#process'][] = ['\Drupal\mymodule\BusinessRules', 'alterFieldCaption'];
    }

  }
}

Then we create a new class in src directory of the module.

namespace Drupal\mymodule;

class BusinessRules {

  public static function alterFieldCaption(array &$element, FormStateInterface &$form_state, array &$complete_form) {

    // Use whatever logic to target instances of `field_caption`.
    if (reset($element['#parents']) == 'field_foo_cta') {
      $element['value']['#maxlength'] = 25;
    }
    return $element;

  }

}

Thanks @larowlan for help on this.


Social Field Module: Icons not showing up in options

Just copy "font" and "Css" folder in your activated theme and if it ask to merge just allow them to merge and check further.

Hope this helps you.

Thanks!


Creating a Field in order to add Icons to content's Title

You can do this by creating node.tpl file.

    <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
     //"print image here"
 <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

You can get all the field value here and just print the image before the title.


Append current query string to private file urls?

Adding this cache context seemed to do it (although I do not know if this is bulletproof):

  if (preg_match('/private:\/\//i', $file_entity->getFileUri())) {
    $query = \Drupal::requestStack()->getCurrentRequest()->query->all();

    if (!empty($query)) {
      $options['query'] = $query;
    }

    $variables['#cache']['contexts'][] = 'url.query_args';
  }


Create a block Most popular content using google analytics

Consider looking (also) at the Google Analytics Reports module. Here is an excerpt from its project page:

  ... provides graphical reporting of your site's tracking data. Graphical reports include a dashboard widget for admins, a small path-based report in blocks, and a full path-based report.


How to detect order type (recurring or not) in order confirmation and shipping confirmation email templates?

Found the way - I can check variable order_entity.bundle for order type and it's value can be "default" or "recurring".
However order receipt email is sent only once, when order is placed and not when recurring order is created, so it's not used for recurring order types at all. I guess that's normal.


Ability to only allow certain content to be added between a range of dates

I would suggest looking into the Rules module for this.

Using this module, you can use its Condition feature to:

Check the date ranges that you specified
Check what content type is being created
Check the current logged in user's role if it's the permitted user role to create a content type

Based if these conditions are met, you can then add what event or message for this matter to display to the user. You aren't also limited to creating one rule but you can create multiple rules based on your conditions.

Hope this gives you an idea and solution.


Drupal doesn’t create clean links – checkbox doesn’t do anything

1)enable rewrite module on apache.

a2enmod rewrite

(to disable type a2dismod rewrite)

2)Set directory permission.
You must find the file that sets permission of each directory for apache. In my case it was /etc/apache2/sites-enabled/000-default
edit the page so that the directory that you will be using to serve webpages has "AllowOverride All". My file contains the following:

Options Indexes FollowSymLinks MultiViews

AllowOverride All

Order allow,deny

allow from all

3)Just restart apache and it should be working:
/etc/init.d/apache2 restart

There are several other checkpoints to fix this issue. All the points are discussed here


Front class not included in body tag in my custom module

If memory serves me correct the "front" class will only be set on the body, if the URL you are on matches what is set in the "Site Information" > Front Page field.

My guess is that you'll need to override the string or array of body classes in the template.php file of your theme. To do this you'd want to use the template_preprocess_html function provided by Drupal core.

Here is a quick and dirty example of how to add the class to the body of your theme:

function THEMENAME_preprocess_html(&$variables) {

  if (theme_get_setting('my_variable') == 0) {
    $variables['classes_array'][] = 'front';
  }

}

From there you'd need to figure out what classifies the home page as the home page with some conditionals or custom functions.


Display of View (using grid) is unevenly distributed

My guess (I cannot be sure without seeing the HTML and CSS) is that the grid display uses HTML tables to create the grid. Because this looks exactly like what HTML tables do: they adjust their column width to the content in it. For instance, "General Fiction" is longer than "Genre" so the first table column is wider than the second. Because your view is grouped, every group would render a separate table, so that's why the columns cannot align.

Assuming that tables are indeed the cause, the solution would be to add custom CSS setting the width of <td> elements in this view to 33.3%. (How you can do that, depends on your theme setup and is beyond the scope of this answer.)


Taxonomy: allow "All values" choice, visible as "All values" in results

Uncheck the Required option from exposed form field settings. Then there will be one more option - Any - will appear in filter dropdown. It will work same as All values.

You can also change - Any - value in to All Values by using hook_form_alter.

*EDIT :*

So the good structure is :
- Create a taxonomy vocabulary for the values ;
- Create a level 1 with an "All values" term ;
- Create a level 2 with all individual values ;
- Add the taxonomy relationship in the views and load the field taxonomy terms for each result ;
- Add the taxonomy as an exposed filter with depth ;
- In the settings of this filter, define a depth of -1, so every individual value chosen will also return the parent value.
As an example, a chosen region (as a taxonomy term) will return content indexed for "all regions" parent term.


Create a view of nodes based on user record

For entity reference fields there are 2 types of relationships added to views: a Referenced entity and a Referencing entity.

Referenced entity is used for a reference from the base table (e.g. A user view that references a fruit node).
Referencing entity is used for a reference to the base table (e.g. a fruit node view that references a user)

In your case, it's Referencing entity that you want.

Create a node view and a Entity Reference: Referencing entity relationship (the description should read A bridge to the User entity that is referencing Content via field_FRUIT_NODE_REF) that refers to your fruit node reference.

That should handle the data/reference part. What remains is aggregation/filtering (e.g. there will duplicates if fruit node references aren't distinct for each user) and display (e.g. how to display marking a fruit node referencing a current user).

Depending on your needs, you might need a custom field/template since there is a limit of what you can do with field basic rewriting and default user contextual filters.


Drupal Authentication with ActiveDirectory

I have the following set of parameters that allow authentication by Active Directory 2003:

server type: "Active Directory LDAP"
server address: ad.example.com
ldap port: 389
binding method for Searches: Bind with Users Credentials
base DNs for LDAP user entries: cn=users,dc=example,dc=com
username attribute: sAMAccountName
expression for user DN: %username@company.com
email attribute: mail

I think the problem mainly stems from the fact that AD typically does not have the login name in the LDAP DN.


Steps for Changing the Order of the Payment Methods on Checkout

Edit the payment method and click on SETTINGS on the bottom of the page.


Set default values for a field from a node

Ahmed was close, but to take it all the way you need to fetch the field's value:

function MODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id = 'YOUR_FORM_ID_HERE') {
    // Fetch node that has default value
    $node = node_load($nid);
    // Fetch the value from price field
    $node_wrapper = entity_metadata_wrapper('node', $node);
    $field_val = $node_wrapper->field_price->value();
    // Set fetched value as default
    $form['field_price'][LANGUAGE_NONE][0]["value"]['#default_value'] = $field_val;
  }
}

I am itching for a clean way to avoid having ['und'][0] in there,  as these values can change with localisation, but this would still work.


how to use "views field view" for entity reference - Not taxonomy

You don't need additional modules to introduce data from referenced entities into your views, you can do it with Relationships.

Your question title is about the Views field view module, but your question text reveals what you're really after, so I won't go into the Views field module solution because it's not the best way to go (performance-wise) if you can do it otherwise.

The Entityreference field on your "Webinar" nodes only lists titles of the "Speaker" entity, both on node pages and in Views.

To display information other than Title of the "Speaker" entities within "Webinar" views you have to add a Relationship through the entityreference field. That acts as a bridge to the other tables/data and makes them available for use within views.

In your case you should:

Add a Title field and the "Speaker" entityreference field for your "Webinar" nodes (you probably already have this step)
Edit the Speaker field and under Multiple field settings untick Display all values in the same row.

This will make every speaker display as a separate views row.
Add a Relationship Content referenced from field_speakers (or whatever the field name is in your case), require it if you don't want to see webinars in your results that don't have any speakers selected
Add the "Speaker title" field, it will automatically use the above Relationship
Add the "Speaker company" field, it will automatically use the above Relationship
Under Format Settings set the Grouping field Nr.1 to Title (the Webinar one).

This will take care of the way you want results grouped under each webinar title.
Edit the Title field (Webinar) and set it to Exclude from display and under Style settings set the Customize field and label wrapper HTML to H2 or whatever makes the most sense in your case.


This question got me scratching my head also for a couple of hours, until I found File Entity Inline module.

Basically this module provides the functionality the OP wanted. You just create the field in the file entity you need to and then when creating the file/image field you have an additional box in the editing window where you can select the fields you want to be displayed next to each file.


The Token module provides very simple and limited taxonomy options. It will only provide the top most term of the top most vocabulary by weight.

The simplest solution will be to use a module like this: http://drupal.org/project/taxonomy_token

It will allow you to configure custom tokens for exactly the term/vocab you need.


A Drupalogical question about Slider captions

Using the Media module, you can add fields to images, such as description or caption. https://drupal.org/project/media

Alternatively, you could use the Field collection module to create a 'Gallery image' field type, which has the extra fields that you need.


Yes you can. After installing the ldap module:

Set up the two servers via: admin/config/people/ldap/servers
Set up authentication via: admin/config/people/ldap/authentication. Make
sure to "Check all LDAP server configurations to use in authentication."
Do your other settings as per your requirements.


It will help if you add the rule that you have added. Also if you think it's a complex rule to be applied, you can apply the discount in the checkout page rather than before that without using the rules itself. In other places just display the 1pcs price with the discount applied.


Profile 2 - My account displayed together

Do you mean you want to have separate tabs to edit your account information and profile information? If so, edit the profile type and check the "Provide a separate page for editing profiles." option.


How to move the user account/Profile 2 information from the content region to a sidebar region

You can create a View (show Users) with display "block" and add User:ID as Context Filter. For the Context Filter set "When the filter value is NOT available" to "provide default value - User ID from URL". Add all user fields that you would like to output to your view. Created Views block will then be listed on you Blocks page (structure > blocks). Once the block is there, you can drag it into the sidebar region.

If you need to remove user profile fields that are rendering in content region by default or override them, you can do so by overriding "modules/user/user-profile.tpl.php" - copying it into your theme's template folder and replacing  the line that renders user profile - <?php print render($user_profile); ?> with the desired content.

Page Manager Existing Pages + Panels is another convenient method of changing the layout of user profile. This method will work in combination with existing layout regions.


Best way to Improve live site and then push changes from dev to live?

Is it possible that my dev database gets updated automatically if changes are made on live site ?
So once the theming is finished, i can drop the live DB and replace with Dev one:) Seems like a dream to me ..

Databases shouldn't be migrated up (ie dev -> prod), only down (ie prod -> dev). If you migrate a database up, you will overwrite anything new on the production server. For example, any new accounts, comments, pages, or anything else that is in the database.
If you use the Features module, it will allow you to migrate some database settings as code (a features module) that can potentially solve your issue. Or if you are on D8, you can export configuration and import it in the other site.


create a copy of a field-collection for entity clone

This has been solved by chalee on d.o on the following issue: Integrate node_clone with field_collection module.

This is his function that works just fine for my use case:

<?php
function clone_fc_items($entity_type, &$entity, $fc_field, $language = LANGUAGE_NONE){
  $entity_wrapper = entity_metadata_wrapper($entity_type, $entity);
  $old_fc_items = $entity_wrapper->{$fc_field}->value();
  if (!is_array($old_fc_items)) {
    $old_fc_items = array($old_fc_items);
  }

  $field_info_instances = field_info_instances();
  $field_names = element_children($field_info_instances['field_collection_item'][$fc_field]);

  unset($entity->{$fc_field}[$language]);

  foreach ($old_fc_items as $old_fc_item) {
    $old_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $old_fc_item);
    $new_fc_item = entity_create('field_collection_item', array('field_name' => $fc_field));
    $new_fc_item->setHostEntity($entity_type, $entity);
    $new_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $new_fc_item);

    foreach ($field_names as $field_name) {
        //if (is_array($old_fc_item->{$field_name})){
            if (!empty($old_fc_item->{$field_name})){
                $new_fc_item->{$field_name} = $old_fc_item->{$field_name};
            }
        //}
    }
    $new_fc_item_wrapper->save();

    //Now check if any of the fields in the newly cloned fc item is a field collection and recursively call this function to properly clone it.
    foreach ($field_names as $field_name) {
        if (!empty($new_fc_item->{$field_name})){
            $field_info = field_info_field($field_name);
            if ($field_info['type'] == 'field_collection'){
                clone_fc_items('field_collection_item',$new_fc_item, $field_name,$language);
            }
        }
    }

  }
}
?>

Again, kudos goes to @chalee - thanks :)


hope this will help

/**
 * Post process any rendered data.
 *
 * This can be valuable to be able to cache a view and still have some level of
 * dynamic output. In an ideal world, the actual output will include HTML
 * comment based tokens, and then the post process can replace those tokens.
 *
 * Example usage. If it is known that the view is a node view and that the
 * primary field will be a nid, you can do something like this:
 *
 * <!--post-FIELD-NID-->
 *
 * And then in the post render, create an array with the text that should
 * go there:
 *
 * strtr($output, array('<!--post-FIELD-1-->' => 'output for FIELD of nid 1');
 *
 * All of the cached result data will be available in $view->result, as well,
 * so all ids used in the query should be discoverable.
 *
 * This hook can be utilized by themes.
 * @param $view
 *   The view object about to be processed.
 * @param $output
 *   A flat string with the rendered output of the view.
 * @param $cache
 *   The cache settings.
 */
hook_views_post_render(&$view, &$output, &$cache)
    {
if ($view->name == 'your_view_name')
    {
   //do your logic
   }}


After setting up the plugin in phonegap simply add this to a page:

var html = theme('button_link', { text: 'Start Scan', path: null, attributes: { onclick: "startScan()" } });
$('#my_container').html(html).trigger('create');

Thanks to TylerFrankenstein for this one.


Which contributed modules are being moved into Drupal 8 core?

Modules brought into core
Entirely:

Breakpoint
CacheTags
Content Translation
Email (simple field, HTML5 validation only)
Entity API
Entity Reference
Entity view modes
File Entity
Link (simple field, HTML5 validation only)
Phone (simple field, HTML5 validation only)
Picture
Quick Edit
Transliteration
UUID
Views
RESTWS (Renamed to REST module)

Partially:

Admin Views (reworked)
CKEditor
CTools
Date (all except recurring dates)
Display Suite (view modes)
Internationalization
Migrate
Views Bulk Operations (reworked)

Removed

Blog (moved to contrib)
Dashboard (moved to contrib as Homebox)
Open ID
Overlay (fundamentally reworked to not provide an "overlay")
PHP Filter (moved to contrib)
Poll (moved to contrib)
Profile (Use Profile2 now)
Translation (replaced by Entity Translation)
Trigger (use Rules now)
Signature (functionality provided by User moved to contrib)
XML-RPC (moved to contrib)

Modules fundamentally changed by Drupal 8:
Deprecated (you won't need these anymore)

Admin
Administration Language
Bean
Boxes
Caption Filter
Computed Field
Ctools exportables
Fallback Language Negotiation
Field Hidden
Fieldable Panels Panes
Float Filter
Hidden Field Widgets
History
IMCE
Localization update
Localized Drupal Distribution
Menu Block
Menu Trails
Module Filter
Node Reference
Placeholder
Profile2
RSS permissions
Services
String overrides
Strongarm
Token
Transliteration
User Picture Field
User Reference
Vertical Tabs
Wysiwyg * (the module and everything related to it)

Reduced (these will have less work to do)

Backup and Migrate
Context
Custom Breadcrumbs
Features
Feeds
Menu Breadcrumb
Service Links
Rules
Views * (every module related to views)


User ID problem when programmatically creating nodes

The problem is that node_submit() contains the following code.

  if (user_access('administer nodes')) {
    // Populate the "authored by" field.
    if ($account = user_load(array('name' => $node->name))) {
      $node->uid = $account->uid;
    }
    else {
      $node->uid = 0;
    }
  }

When it's not able to load the user object having $node->name as username, it sets the user ID to zero.
As you have already set the values for the node object, it is useless to pass the node to node_submit(); it would be better to just pass it to node_save().


After every cron job, the Media tags in WYSIWYG markup change to https upon a robot crawl

If you don't want HTTPS, simply turn it off. And if, for some reason, you want HTTPS links to still work, you should redirect HTTPS to HTTP - but that's out of scope of this site. Just never leave https on without proper certificate.

That said, you have some serious bug in your caching configuration, and data you provided is not enough to identify it. Luckily, there is no need to do so.


How can I install a beta version of a module?

This installs the latest beta-12 for me:

composer require drupal/webform:5.0.*@dev

You need to do a bit of translation from the Drupal version number. From Using Composer to manage Drupal site dependencies:

  Specifying a version you can specify a version from the command line with:

 $ composer require drupal/<modulename>:<version>

  For example:

 $ composer require drupal/ctools:3.0.0-alpha26
 $ composer require drupal/token:1.x-dev

  In these examples, the composer version 3.0.0-alpha26 maps to the drupal.org version 8.x-3.0-alpha26 and 1.x-dev maps to 8.x-1.x branch on drupal.org.

  If you specify a branch, such as 1.x you must add -dev to the end of the version.

Hence for Webform, 8.5 becomes 5.0.x, and that's what you need to use to identify the package correctly.


Display node author picture through tpl file

The following lines did it:

$user = user_load($uid);
print theme('user_picture', array('account' =>$user));


How to check if a multi value reference field already has a value

You can check the field's values before saving:

// Id to check if exists.
$query_id = 123;

// Create array of existing ids in field.
$existing_ids = array_column($entity->my_entity_reference_field->getValue(), 'target_id');

// Check if the $query_id is not in the existing ids.
if (!in_array($query_id, $existing_ids)) {
  // In here means your $query_id doesn't already exist in the field's values.
}

Your code updated:

// Load portfolio node id and new location id from form_state.
$portfolioId = $form_state->getValue('portfolios');
$newLocationId = $form_state->getValue('location_nid');
if (!empty($portfolioId) && !empty($newLocationId)) {
  // Load portfolio node.
  $portfolioNode = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->load($portfolioId);

  // Get existing location ids from portfolio node.
  $existingPortfolioLocationIds = array_column($portfolioNode->field_portfolio_locations->getValue(), 'target_id');
  // If new location id is not an existing location id, add to node and save.
  if (!in_array($newLocationId, $existingPortfolioLocationIds)) {
    $portfolioNode->field_portfolio_locations[] = $newLocationId;
    $portfolioNode->save();
  }
}


It's just simple jQuery.

SEE THIS EXAMPLE I MADE FOR YOU

In Drupal to use jQuery you need to wrap it in

(function ($) {

    //code goes here

})(jQuery);

so your code should look like this

(function ($) {

    $(document).ready(function() {
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

Remember that you need to add to your css .content { display: none; } OR you could do it with jquery

(function ($) {

    $(document).ready(function() {
       $(".content").css("display", "none");
         $(".button").click(function () {
             $(this).next('.content').slideToggle();
         });
    });

})(jQuery);

Note: this code works assuming there are no divs in between your .button and .content. If there are divs in between them, you might need to modify the slideToggle line.


Solving "MySQL server has gone away", mysql error 2006

I had a client on a hosting company that refused to increase the value of max_allowed_packet (2MB), regularly leading to the inability to add info-items to the cache. I solved that by adding compression. See Compress cache data before storing it in the database.

In your case, reducing the resource usage may be done with spreading it out over batch operations.


How to update a module's view programmatically using hook_update_n?

we ended up adding the following code inside the update_n function:

  $views_dir = drupal_get_path('module', 'mymodule') . '/views';
  $views_files = scandir($views_dir);
  $views = array();
  foreach ($views_files as $filename) {
    if (substr($filename, -4) == '.inc') {
      include_once $views_dir . '/' . $filename;
      if (isset($view) && is_object($view)) {
        views_save_view($view);
      }
    }
  }


Wysiwyg (ckeditor) disappeared after drush rr

Go to yourwebsite.com/admin/config/content/ckeditor/editg

In there you probably need to change the path to ckeditor. As you can see from the screen shot the %m stands for /sites/all/modules/ckeditor

so you need to erase %m/ckeditor and instead put /sites/default/modules/ckeditor/ckeditor

Click image to enlarge


How to create User Account Registration form with Webform?

Storing the password as a regular Webform field is not nearly as secure as using Drupal's built-in user registration password. I would recommend instead of trying to create user registration via Webform, that you use something like Profile 2 to add additional information fields to the core registration form.


Unable to add css class to a Panels region

The option to add a CSS class is on the actual pane content. In a Bootstrap panel region the cog on the left gives you the option to set the grids up. If you need to add a class to that you will need to find the template file for the region you are using and copy it to your theme/sub-theme and add the class there or write a cTools plugin for that yourself. The ability to add a class is on the actual content panes that you add inside the region, so for instance if you were to add a view pane into the left region inside your panel you could place that view inside a bootstrap .well or bootstrap .alert using the cog on the right hand side (the cog on the content inside the region) of the content pane. So you can add the class to the content pane via settings that way.

If you need to add a class to the whole region you need to copy your template file for your layout to your theme. So if you were using Bootstrap three column stacked you would copy bootstrap-threecol-stacked.tpl.php to your templates folder in your theme. And modify the outer div for the region you want inside that template file. The regions are actually listed in that template file (you will see them inside the file). You can modify any of those template files inside the module, if you want to see what template files have what markup turn theme debug on and inspect your HTML of the page (see here for how to do that).

There is this module where you can add the alert or well into a region: https://www.drupal.org/project/panels_bootstrap_styles but I've never actually used that one and it looks limited. I would stick to the bootstrap panel layouts and proper templating, or cTools plugins for these types of things work great also. You can write them like that module does for just about any markup you need :)

You can also use a module like Semantic Panels to do this, it was a little overkill for something like adding a CSS class so I didn't add it before but you may find it easier to use.


how to create a sub menu accordian using api

Try the jQuery Menu module. It was somewhat easy to style -- all I had to add was CSS.

Jquery menu uses simple, cross browser compatible jquery to transform your multilevel menus into click and expand menus. Yes this module is similar to dhtml menus and active menus, but it is different in a couple of key ways.

Unlike dhtml menus (which requires you to click twice on a link to actually follow an expanded link) Jquery menus separates the link from the expanding mechanism (there is a small plus symbol that you click instead to expand the menu). This makes for a more natural navigation.
Unlike active menus, which makes ajax calls to fill in the lower level menus when you click the plus symbol, Jquery menu creates the menu in full on the initial page load. I personally have used active menus for several months and have found that those ajax calls sometimes fail, and are not as stable as jquery.
Unlike Active menus which transforms all menus into active menus once the module is turned on, Jquery menu only creates a jquery block for the menus that you specify. To chose which menus you want to be active you just have to visit the admin page at 'admin/settings/jquerymenu' .
Jquery menu is easily themable. Since the jquery menu blocks only use a small number of styles, and don’t use the default list styles, overriding it with your own css is easy. Also the important display elements are contained in themable functions so you can tinker with the layout if you like.


D8: The same content type, but different url path aliases pattern based on paragraphs. Possible?

Since you mention that you only have a single allowed paragraph, something like [node:paragraph_field:entity:type:target_id] might work, but untested. That will use the machine name of the referenced paragrap type.

If not, you can always implement a custom token on nodes and then do whatever you want using hook_token_info() and hook_tokens().

I also agree with others that this seems like a somewhat strange architecture and usually list/term fields are used for such a categorization, this will most likely also work better if you ever need to do something like an exposed filter in a view and so on.


cache_form error: myisam_sort_buffer_size is too small

mysqlcheck is a client utility that actually logs into mysql

myisamchk is a client utility that does not require logging in. It does require

access the raw file(s) needed, provided the datafile is not in use by the mysqld process
your current directory is wherever the datafile is located

For the table mydrupaldb.cache_form, here is what you must do:

Step 01) Run this query : SHOW VARIABLES LIKE 'datadir'; In most instances, this will be /var/lib/mysql. For the sake of this example, let's assume it is /var/lib/mysql.
Step 02) cd /var/lib/mysql/mydrupaldb
Step 03) service mysql stop
Step 04) myisamchk -r -q cache_form.MYI --sort_buffer_size=2G
Step 05) service mysql start

Give it a Try !!!

CAVEAT : The error message probably means you were not standing in the proper directory where cache_form.MYI is located at the time you first ran myisamchk.


How to have new activity count above any view?

Have a look at the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice.
Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.


How can I provide anonymous user to access my REST GET API without providing any auth information?

You could create your own authentication provider; it could then allow anonymous users access to your resource. It is not that difficult, the only thing I found is that you have to be careful to make sure the authentication provider only applies whe you specifically want it to. Look here for a tutorial:

http://enzolutions.com/articles/2014/12/28/how-to-create-an-authentication-provider-in-drupal-8/


"Shopping cart form" view breaks after adding a field

what you're experiencing is actually the same as another user whose anonymous users were not able to view their carts. It's related to Views relationships and the automatic access checks they add to Views queries. For more information, please see my answer here:

Anonymous cannot see cart in cart page


How can I get an entityform attached to an order in drupal commerce?

Have you tried first checking to make sure $order is set? If not then load cart from $user->id first and then wrap it.


Authenticathed users can't edit Etherpad-enabled field

I just found out that the user needs to have permissions to edit the entire node. Don't know why the field-specific permissions don't work. I had to create a separate content type in order to implement this.


Sure, add a Node: Link field, turn off the label, and set the Text To Display to "Read More" and you should be set.


Are you in a node template ? If so you can do:

print render($content['field_vote']);

Source: Display fivestar in template (node--*.tpl.php)


How to remove all attributes displayed for a field?

We ended up creating a field.html.twig in our custom sub theme where all the attributes were removed and only added them on an as needed basis.


How do I get the absolute URL when using l()?

You can make a link absolute with:

l(t('New product'), 'node/123', array('absolute' => TRUE));

See l() and url() for more.


Edit user account how to check before update if the role check box is selected?

Use hook_user_presave() for any logic that you need to happen before user data is really updated, but also have access to new values:

Parameters
$edit: The array of form values submitted by the user. Assign values to this array to save changes in the database.
$account: The user object on which the operation is performed. Values assigned in this object will not be saved in the database.
$category: The active category of user information being edited.

You need to test against $edit argument.

For Drupal 6, you need hook_user.

Act on user account actions.

Act when $op == 'submit', as:

submit: Modify the account before it gets saved.

Just as with Drupal 7, you must examine

$edit: The array of form values submitted by the user.


drupal_mail_system is returning empty object

You forgot to call format method.

Try the following snippet:

$from = variable_get('system_mail', $my_email);
$message = array(
  'id' => $my_module . '_' . $my_mail_token,
  'to' => $my_email,
  'subject' => $message_subject,
  'body' => array($message_body),
  'headers' => array(
    'From' => $from,
    'Sender' => $from,
    'Return-Path' => $from,
  ),
);
$system = drupal_mail_system($my_module, $my_mail_token);

// The format function must be called before calling the mail function.
$message = $system->format($message);

if ($system->mail($message)) {
  drupal_set_message('SUCCESS');
}
else {
  drupal_set_message('FAILURE');
}


View of users-profile who had flagged me "subscribe"

Create view with type "User"
Add Relationships "Flags: User's flaggings". Choose your flag name and set checkbox "Include only users who have flagged content."
Add Contextual filter "Flags: Entity ID". Choose in the filter settings "Provide default value" -> "User ID from URL"


How to override views title using values from several contextual filters?

There is a Replacement patterns fieldset below it that you can copy the patterns from. You need to edit each contextual filter and override the title with the pattern that makes sense in each of those contexts.


db_affected_rows in Drupal 7 for db_query

That information is directly returned by the execute() method of Delete/UpdateQuery, see for example: UpdateQuery::execute().

<?php
$affected = db_update('some_table')
  ->fields(array(
    'some_field' => $value,
  ))
  ->condition('another_field', $id)
  ->execute();
?>

And InsertQuery::execute() returns the last insert id.


From what I remember, drupal_add_js, which ultimately is called, doesn't support attributes in the script element. You can use drupal_add_html_head to add js with other attributes; the docs page has some examples on how to do this.


How to send email to all members when a post is updated by user?

EVENT

After saving new content

CONDITIONS

Entity is group content

Parameter: Entity: [node]

ACTIONS

Get group members from group audience
Parameter: Group content: [node]
Provides variables: Fetch a List of group members (group_members)

Loop
Parameter: List: [group-members]
List item: Get list of group members and their email ids (list_grp_members_emails)

Send mail Parameter: To: [list-grp-members-emails:mail], Subject: Notification: Content..., Message: Test


system/connect

  Returns the details of currently logged in user.

user/login

  Login a user for a new session

To login a user you will use user/login service call... Once user is logged in if you would like to pull logged in user details you will use system/connect service.. You can see above details in services module help section


Using Ultimate cron to set a specific time to run a function of module, but it is not working as expected

Set your crontab to wget/curl cron.php once per minute (* * * * *).


I believe the project page is referring to page_cache_fastpath(), which is called during Drupal bootstrap from the following code:

if (variable_get('page_cache_fastpath', FALSE) && page_cache_fastpath()) {
  exit;
}

The documentation page reports the following description for the function:

  By implementing page_cache_fastpath(), a special cache handler can skip most of the bootstrap process, including the database connection. This function is invoked during DRUPAL_BOOTSTRAP_EARLY_PAGE_CACHE.

The example code reported in that page helps to understand how the function needs to be implemented, and what should do.

function page_cache_fastpath() {
  $page = mycache_fetch($base_root . request_uri(), 'cache_page');
  if (!empty($page)) {
    drupal_page_header();
    print $page;
    return TRUE;
  }
}

If the module reports to utilize it, it means it actually defines the page_cache_fastpath() function, which is called by Drupal core code.
To notice that it's not a hook, but a function. This means that a module called "mycache" doesn't need to implement mycache_page_cache_fastpath(), but page_cache_fastpath(). In fact, the bootstrap code is explicitly calling page_cache_fastpath(), as it is evident in the code I reported at the beginning of this answer.


Can Drush make include username, password and settings in one file?

The responsibilities of Drush make involve downloading the files that make up your site.  Site initialization can be done in an installation profile, which is selected at installation time, or perhaps in a script that you run to set up your site.

For Drupal 8, configuration can be imported via the drush config-import command.  In Drupal 7, there are many options for managing configuration.  A lot of people (perhaps the majority) use features, but I prefer ctools bonus export.  Here is an example script I use to set up a test site for behat tests.

If you are just starting out, you might want to consider using Composer instead of Drush Make.


How do I determine the route of my view?

To find out what the route was for a view, I actually ended up doing this in a custom module, and then looking at the page route in the object.

/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_page(&$variables) {
  dpm(\Drupal::request());
}