Not certain, but it sounds like your files may not be in the correct places based on your description.

The services.yml should be in the root of your module, not in a sub folder.

Also, your service classes should be in a /src/ folder. It would be okay to have them in a /src/services folder if you want, but module namespaces in drupal start in the module's /src/ folder, not in the root; the reason for this is because drupal uses the PSR-4 naming conventions, which specify that structure. You can find more info about how drupal modules should be structured here: https://www.drupal.org/node/2156625


How to validate deletion of custom entity?

There are a few options that may mean you don't have to code anything:

A patch for the entityreference module to add this type of cleanup: https://www.drupal.org/node/1368386
A module to handle cleanup: https://www.drupal.org/project/reference_delete
A sandbox module to handle cleanup: https://www.drupal.org/sandbox/drothstein/1775816

I would go with one of those if possible instead of writing custom code.

Seeing as you do want to run custom code though I would suggest reading up on how those solutions work and implementing something similar, but with your own custom logic.

For example in the issue in that first link they discuss 3 different ways of doing the deletions and some of the pros and cons of certain possible solutions, so I think that information would be useful to you in implementing your own.

Although I don't know your exact requirements I would suggest that doing this at the validation stage is not a good idea because it means it is possible for you to delete referencing entities at validation stage and then something could stop the deletion of the referenced entities after your code runs and you will have deleted the reference when you shouldn't have.

It should be done later than the validation stage.

That patch issue suggests maybe hook_entity_delete(), which I think is a better place for it, however in that issue they also mention possible page timeouts if there are lots of references to delete.

The code in those 2 modules may also be useful to you but I haven't read those.

EDIT: just had a quick look an the reference_delete module also uses the entity delete hook.


How do I add a specific class in a row of a table output depending on a field content?

Two options:

You alter your view with a View hook and you add to the row class value your own class based on one of the field value
You use this solution, and you can check with twig the actual row content and add a class based on that(use devel module and {{ kint(row) }} to understand how to reach the values you want)


how to change the weight of a moderation state transition outside the database

Change the weight in the admin panel, then export the yaml files with drush config-export


How to output node fields of referenced nodes as plain-text key/value pairs?

Finally I got that one too :)

One can add build modes with the Build modes module an decide on $node->build_mode what to render.

In the node-"super node".tpl.php one gets the node-ids of the referenced nodes from $node. Then one can node_load() these nodes into a variable and theme them.


Normally you would iterate through the rows and call a row plugin to render the field values. As I understand the question you want to access the field values directly by row index and field id?

Then try StylePluginBase::getFieldValue:

$value = $this->getFieldValue($index, $field);

Normally a style plugin iterates the rows like this:

  public function render() {
    if (empty($this->view->rowPlugin)) {
      trigger_error('Missing row plugin', E_WARNING);
      return [];
    }
    $rows = [];

    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    ...

For this to work you have to set protected $usesRowPlugin = TRUE; and configure a row plugin which renders the map.

If you want to do all rendering in the style plugin you can use the same loop and get the field values directly:

  public function render() {
    $rows = [];
    foreach ($this->view->result as $index => $row) {
      $rows[] = render_map(
        $this->getFieldValue($index, 'field1'),
        $this->getFieldValue($index, 'field2')
      );
    }
    ...


What's the difference between "Contexts" in CTools/Panels and in Context module?

This is essentially a duplicate of Panels or Context module?. However, Lullabot has a pretty good breakdown on the differences, and at the end of the day, it comes down to a matter of preference (I personally tend to go with Context).


If you are using node translations, when Drupal gets an empty body, it first search a translation with non empty body and, if found, shows it. That's probably why you are viewing body content in the node view but an empty textarea in the node edit form, the content surely comes from one translation.


How to check if a new node is correctly created using Entity Metadata Wrapper $wrapper->save()?

Check that the entity has an identifier:

if ($ewrapper->getIdentifier()) {
  // Save happened.
}

A better approach might be handling any errors:

try {
  $ewrapper->save();

  // Try to do something with $ewrapper->getIdentifier()
}
catch (\Exception $e) {
  // Recover...
}


How to set $base_url when running a site in a subdomain?

Have you tried clearing cache after uploading to remote server?

If it didn't help, you could try installing Global Redirect module. It may resolve your problem, or at least can help reduce the possibility of problems created by path aliases.


Is it possible to force your module's update hook to run?

There are few ways of forcing module update.

Calling the update function directly.

$sandbox = [];
module_load_include('install', 'FOO');
FOO_update_7001($sandbox);

Resetting the schema version to the point of interest and run the updates again as usual.

drupal_set_installed_schema_version('module_name', '7000');

Or reset to re-run only the latest update schema:

drupal_set_installed_schema_version('foo', drupal_get_installed_schema_version('foo') - 1);

Notes:

This can be placed in hook_install, so during the update process all sequent update hooks would be executed.
In order to use this function outside of the installation file, you've to include Drupal install.inc first and installation file of the module, e.g.

require_once DRUPAL_ROOT . '/includes/install.inc';
module_load_include('install', 'foo');

Consider adding ini_set('max_execution_time', 0); for longer installation updates to prevent PHP timeouts.

Using drush. Find below few examples:

drush eval 'module_load_include('install', 'foo'); $s = []; foo_update_7001($s);'
drush sqlq "UPDATE system SET schema_version = 7000 WHERE name = 'foo'" && drush -y updb


How to get the nid of nodes created by user (on the event of logout)?

hook_user_logout() is probably called only when the user uses user/logout to log out. If users don't log out all the times after they used the site, that hook is probably not going to be invoked. (For example, I have never logged out from Drupal.org, and I log in back once my session expires for the browser I am using.)
Furthermore, once a node is deleted, there is no track of it in the database, and since hook_user_logout() is going to be eventually invoked when it is too late, it is not going to find any information about the nodes deleted by the user.

I would rather use hook_node_insert() and hook_node_delete() to collect the data that will be used from another hook. For example, the following code would work.

function mymodule_node_insert($node) {
  $_SESSION['created'][$node->nid] = TRUE;
}

function mymodule_node_delete($node) {
  $_SESSION['deleted'][$node->nid] = TRUE;
}

If that is helpful information, instead of TRUE you can use REQUEST_TIME; in that way, you would log when the user created or deleted a node.

Eventually, you can use a database table instead of a session variable, but in that case you should clean it after the user logged out, if you want to reset the information you collected once the user logs out. With the code I shown, you would lose the information when the session expires for the user, so it is probably preferable for you to store the information in the database.

The method suggested by the other users doesn't work when the user creates a node and deletes it. Counting the number of nodes associated with a user ID doesn't include the nodes that have been deleted before the user logged out. Also, since users with the permission of administering nodes can associate a node with a user different from the user who created it, counting the nodes associated with a user ID is going to give wrong information.


Create an Exposed Filter for Integer Values Using Drop Downs

Sure. You can do it with form alter hooks. Here is an example. The form id will be:

views_exposed_form_<view_name>_<view_type>


Theming and overriding taxonomy term/vocabulary page

You can have full control over the taxonomy/term/ID page by intercepting the menu call with hook_menu_alter() and let the content be generated by a custom function.

This allows you to completely customize the taxonomy term page. You can check for a certain vocabulary ("Authors") and have a custom generated page for that vocab and leave the others untouched.

You can have fine grained control over how results are displayed using view modes and templates.

No contributed modules are needed.

Here is an example to be used in a custom module. The custom content is generated using Drupals EntityFieldQuery because it is a lazy and robust way of generating a list of content, but anything goes here.
.

/**
 * * Implements hook_menu_alter().
 */
function YOURMODULE_menu_alter(&$menu) {
  if (isset($menu['taxonomy/term/%taxonomy_term'])) {
    $menu['taxonomy/term/%taxonomy_term']['page callback'] = 'YOURMODULE_taxonomy_term_page';
    $menu['taxonomy/term/%taxonomy_term']['access arguments'] = array(2);
  }
}

/**
 * Callback function for taxonomy/term/%taxonomy_term.
 *
 * @param $taxonomy_term object
 * @return * Themed page for a taxonomy term, specific to the term's vocabulary.
 */
function YOURMODULE_taxonomy_term_page($term) {
  $voc = taxonomy_vocabulary_load($term->vid);
  switch ($voc->machine_name) {

    case 'SOMEVOCUBALARY':

      // here you generate the actual content of the page
      // could be done e.g. with an entityfieldquery as follows

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
              ->fieldCondition('field_gallery', 'tid', $term->tid)
              ->propertyOrderBy('sticky', 'DESC')
              ->propertyCondition('status', 1);
      $result = $query->execute();
      if (!empty($result['node'])) {
        $build['content']['nodes'] = node_view_multiple(node_load_multiple(array_keys($result['node'])), 'teaser'); // output the node teasers. you can control the markup of the 'teaser' view mode with a template in the theme folder
      } else {
        $build['content']['status']['#markup'] = t('No results found for term ID !tid.', array('!tid' => $term->tid));
      }
      return $build;

    // If the term page is for an other vocabulary then use Drupal's default taxonomy page
    default:
      module_load_include('inc', 'taxonomy', 'taxonomy.pages');
      return taxonomy_term_page($term);
  }
}


Drupal 7 module hook_preprocess_page &$vars

You are trying to render $page['branded_footer'], but the module preprocess function is setting $vars['branded_footer'], which would be accessible as $branded_footer in the template file.

$page['branded_footer'] would be set if the theme defines a branded_footer region. In that case, you should follow what How do I create custom regions in a theme? says.


How to create new type element to form API?

You need to implement hook_element_info(). See the
form_example_elements.inc file from the Example: Form API module, and the Creating Custom Elements documentation guide.

Note that the Elements module already provides a form element type for HTML5 mail inputs.


The "duplicate" I linked to above gives you almost all of your answer, but this adds the "complete" function that you asked for.

In a custom js file in your module (this assumes that your module is named ajax_example and that the ID of the element being clicked is #edit-submit):

Drupal.behaviors.ajax_example = {
  attach: function (context, settings) {
    // Overwrite beforeSubmit
    Drupal.ajax['edit-submit'].options.beforeSubmit = function (form_values, element, options) {
      console.log('before');
      // Add your on click code here
    }
    // Overwrite complete
    Drupal.ajax['edit-submit'].options.complete = function (form_values, element, options) {
      console.log('after');
      // Add your on complete code here
    }
  }
}


How to print all the elements of a specific column from a table from database in custom module?

You made 4 errors:

You should use {} around table names, not ``.
print_r does not like objects Drupal uses, for testing purposes it's way better to use

while($row = $result->fetchAssoc() ){
}
$node may be already used elsewhere, it's not wise to use common names if you don't mean it.
SELECT *FROM should be SELECT * FROM (kudos for Clive)


You have the sites.php file in the wrong spot, it should be at sites/sites.php, it should not be inside any of the site directories, such as sites/original2.com/sites.php.


How do I capture an audit trail of changes made to a view?

You may use Features module to save your view in code and add version control system (Git, SVN) to your project. Every time when you will change the view you will need to update feature with this view and commit your changes into version control system. Then you will have a history of changes


if you have drush installed, you can do it this way:
 drush search-reindex --immediate --verbose

There is a dev module available that does the same thing.
https://drupal.org/project/reindex

It's probably a good idea to have the site in maintenance mode while you try this.


is there a way to hide a "custom field" in edit mode Drupal 8?

Making this based if it's printed on a view mode, makes things quite complex. You'll have to write a custom module.

Try using the Fields Permissions which is based on Roles. So just check mark the Roles that should be able to see the field in the front.


How should I load a node with its images programatically?

You're going to have to join another table for every field that you want to grab the data for, which is just a pain. Instead, you could just get the nid with your query, and use node_load() a second time to get the other node object, complete with attached fields.

You can do that like so:

$args = array(':type' => $current_node->type, ':created' => $current_node->created);
$sql = 'SELECT nid FROM {node} WHERE type = :type AND created < :created';
$nid = db_query_range($sql, 0, 1, $args)->fetchField();

$new_node = node_load($nid);

$title = $node->title;
$image_field_values = field_get_items('node', $new_node, 'field_image');

$first_image = array_shift($image_field_values);
$image_file = file_load($first_image['fid']);

$image_html = theme('image_style', array(
  'style_name' => 'thumbnail',
  'path' => $image_file->uri,
  'alt' => 'Some alt text'
));

$body_values = field_get_items('node', $new_node, 'body');

// And so on


Did you check How do I remove duplicates when using the random sort? before?

If it does not help you check views_distinct module

  Relationships or other joins in Views often create "duplicate"
  results. For example, a node with a field that has multiple values may
  show up in the View once per value in the multi-value field. It's
  frustrating, and the "DISTINCT" SQL query option in the Views UI does
  not actually solve the problem because the result row is technically
  distinct. This module aims to give a simple GUI method to remove or
  aggregate these "duplicate" rows.


Your question is "render a drupal 8 entity in a string". This is an example how to do this. Get an entity. Get a view builder for the entity node and us it to build your render array with the display mode "full". Render this with renderRoot to the string $html.

$node = \Drupal::entityManager()->getStorage('node')->load($nodeid);
$view_builder = \Drupal::entityManager()->getViewBuilder('node');
$renderarray = $view_builder->view($node, 'full');
$html = \Drupal::service('renderer')->renderPlain($renderarray);

You can do this for any entity. By default this will use the node.html.twig as configured in your theme. But you can change your render array before rendering.

Edit:
For emails use renderPlain().


diffrent theme for admin without use theme appearance config

Copy page.tpl.php to page--admin.tpl.php (note two hyphens) clear theme registry / all caches and should be good to go.


Dynamically add destination fields to migration - importing data when fields on destination entity are not know

I think you could try to implement something similar https://www.webomelette.com/dynamic-migrations-using-templates-drupal-8. This is a good example of dynamic migration.


Creating entity in Rules causes PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

Have a look at issue # 430274, which explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg after only a few secs or mins later on ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the entity is for sure saved ... (so that can't be the reason anymore then why things don't work as expected ...).

Note: it's tough (virtually impossible) to pinpoint what exactly is causing your issue without knowing what exactly those rules look like. Adding a copy of your exported rules to the question may possibly help, but still. However, I'd recommend you to do some Rules debugging, using any of the techniques I described in my answer to How can I display the value of a variable inside a condition?


How come javascript:void(0) is creating a 404 page?

If you are writing some JS, you can add something like:

$('a#the_link_ID').click(function(event) {
  event.preventDefault(); // This prevents to follow the link.
  // ...
  // Here goes your code.
});


Why am I getting a 403 error with this route?

Because you don't have any access checks.

If anyone is allowed to access it, you must specify so explicitly with _access: 'true' in an access section.


Solved the issue - id is actually 'commerce_invoice_confirmation'.
I was trying to print out $message['id'] and stop executing of code, but that never happened? So I assumed that my code was never called. Not sure why. So I used watchdog logger to log id value and found it out.


How to modify Parent Item under Menu Settings to display current language links only?

I am not sure about settings, but I can suggest you way to do it programmatically.

You can use TEMPLATE_preprocess_menu_tree (replace TEMPLATE with your theme name) in your template.php of theme folder. Inside the function you can loop through the tree & validate it's translation with current site language & reset or set access deny if it doesn't match.


Is there a NULL value for a multi-value list?

Select Element's API

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for
a required field and "- None -" for an optional field.
#empty_value: (optional) The value for the first default option, which is used to determine whether the user submitted a value or not.

So using this information, you are able to use the null value's defaults from the select element.


Why is my Rules data comparison not evaluating correctly?

As per the "site:current-user:field-user-profile-type:X" part of your question (X=0 or 1), it seems that your "User profile type" field is a multi value field. Whereas you're trying to use a Data Comparison rules condition. Sorry to say, but for a multi value field, you should NOT use a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense).

To get your rule to work like you want it to work, you should use these Rules Conditions (in the specified order):

Entity has field, for your "User profile type" field, to make it available for subsequent Rules Conditions and/or Rules Actions.
List contains item, whereas:

the list is also about that same "User profile type" field (since your field allows multiple values, it is also considered as a list).
the item you want to check for (if it is contained in the list) is (e.g) "Grant Network user".

With those 2 Rules Conditions, your Rules Actions should be performed as you want it to work. For the sake of (basic) unit testing, just (temporary) add a Rules Action like "Display a Drupal Message" (as the very first Rules Action), with whatever message text (eg: "bingo, Pierre is right ...").

For an example Rule (in rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.

PS: I'm assuming this question is about D7 ...


You probably don't have the Navigation menu enabled/placed in a region, or have any other links to direct a user to the Create Content page.

As an administrator, either enable that menu or create a link to "node/add" (to allow the users to see all the content types for which they can create a node); you can also add a  link to "node/add/article" in another menu or in your theme.

To allow a user to see the administration toolbar, they must have a role that has the permission to use the administration toolbar. See below:


Calling a grandparent JS function that includes jquery from a nested iFrame. D7

Introducing a closure around the whole function (as in your 2nd and 3rd examples) will take it out of the global scope, so it won't be available on the window, and subsequently the iframe's parent (which are the same thing).

What you're looking for is more like:

function grandparent_func() {
  (function($) {
    $("#fancy_regit_link").attr("href", "/my/actual/path");
    $("#fancy_regit_link").trigger('click');
  })(jQuery);
}

That makes sure grandparent_func is global, while still providing you the jQuery object.


appling different styles based on taxonomy

You can have specific template files by using theme hook suggestions. To change the node template, use the following:

function THEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Perform this only on certain content types.
  if ($node->type == 'YOUR_CONTENT_TYPE') {

    // get the taxonomy term (node category)
    $tid  = $node->field_YOURTERM[LANGUAGE_NONE][0]['tid'];
    $term = taxonomy_term_load($tid);
    $term_name = drupal_html_class($term->name);

    // add a css class with the category's name
    $vars['classes_array'][] = 'node-category-' . $term_name;

    // make drupal search for category-specific node templates
    // template files need to be named node--nodetype--termname.tpl.php
    $vars['theme_hook_suggestions'][] = 'node__' . $node->type.'__' . $term_name;
  }
}

Say your categories are like "Drink Wine", the $term_name would be "drink-wine". Lowercarse, no spaces. You can remove __$node->type if you want.

To change the page template, use the following:

function THEME_preprocess_page(&$vars) {
  $node = (isset($vars['node']) ? $vars['node'] : null);

  // Perform this only on certain content types.
  if ($node && $node->type == 'YOUR_CONTENT_TYPE') {

    // get the taxonomy term (node category)
    $tid  = $node->field_YOURTERM[LANGUAGE_NONE][0]['tid'];
    $term = taxonomy_term_load($tid);
    $term_name = drupal_html_class($term->name);

    // add a css class with the category's name
    $vars['classes_array'][] = 'page-node-category-' . $term_name;

    // make drupal search for category-specific page templates
    // template files need to be named page--nodetype--termname.tpl.php
    $vars['theme_hook_suggestions'][] = 'page__' . $node->type.'__' . $term_name;
  }
}


Module Library JS Some In Header Some In Footer

Just add it to your *.libraries.yml as an additional library this time without header: TRUE. And maybe better place all your JS files in a subfolder named /js.

headerlibs:
  version: VERSION
  header: TRUE
  js:
    js/headerfile1.js: {}
    js/headerfile2.js: {}
  css:
    component:
      css/style.module.css: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

footerlibs:
  version: VERSION
  js:
    js/footerfile1.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal
    - core/drupalSettings

Then attach everything as usual:

/**
 * Implements hook_page_attachments().
 */
function MYMODULE_page_attachments(array &$attachments) {

  $attachments['#attached']['library'][] = 'MYMODULE/headerlibs';
  $attachments['#attached']['library'][] = 'MYMODULE/footerlibs';
}

From the docs:

  Asset loading order

  As you would expect, the order in which the files are listed is the
  order in which they will load. By default, all JS assets are now
  loaded in the footer. JS for critical UI elements that cannot be shown
  unless their corresponding JS has run can be loaded in the header if
  needed like so:

js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

  Set the header property to true, to indicate that the JavaScript
  assets in that asset library are in the 'critical path' and should be
  loaded from the header. Any direct or indirect dependencies of
  libraries declared in this way will also automatically load from the
  header, you do not need to declare them individually for them to be
  available. This is the meaning of the phrase 'critical path', once an
  asset is declared to be in the header it is 'critical' for that asset
  and all of its dependencies to load first.


If we are talking about a webform, then under the "webform" tab on the webform node there will be an "email" section. You can add it directly to the email text. The link will be /node/[nid]/webform/emails .

The "registration confirmation" part is a bit ambiguous. There is a user registration confirmation also, but I'm guessing that you are referring to the webform being a type of event registration form? In the case of user registration, there is a section under /admin/config/people/accounts where you can modify the emails.


Which hook to use to reorder multi-value field values before saving content

I would suggest you hook_node_presave to modify node edit form submitted values before saving it into DB.


Error Message: "You must change the sites/all/libraries/mpdf/graph_cache permissions to be writable, as mPDF requires write-access to that directory."

Actually, it looks like it's not writeable by the "apache" user. It's read only. It is writeable by the "hpadmin" user though. Currently "hpadmin" is the owner and "apache" is the group.

drwxr-xr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

vs

drwxrwxr-x.  2 hpadmin apache      22 Jul  2 10:51 graph_cache

You can adjust the permission to group writeable with

chmod 775 sites/all/libraries/mpdf/graph_cache

or change "apache" to the owner with

chown apache:apache sites/all/libraries/mpdf/graph_cache


Views image field linked with nofollow attribute

Add Nid field , exclude to display then in rewrite section instead

[field_image]

try

[field_image]


This method should work in almost all environments:

Browse https://github.com/drush-ops/drush/releases for the release you want. You can't use drush 9 with php 5.5, so you have to choose drush 8.

Download the selected drush version

wget https://github.com/drush-ops/drush/releases/download/8.1.3/drush.phar

and try to run this php runtime file:

/usr/local/php5.5/bin/php drush.phar status

The php path is an example. You only need it, if php does not pickup the right php version.

You can keep running drush like this, but it is more convenient to rename it to drush, make it executable with chmod +x drush and copy it to a location where your shell finds it as executable (a path defined in $PATH). This depends on that your environment allows you to execute phar files.


"Call to undefined function views_get_view()" error

I'd say you just need to have Views module enabled to have this function globally available. You enable/disable modules at /admin/modules.


Is it possible to apply Authcache caching to elements in page.tpl.php?

I recommend to redo the page with blocks (or panels). The Authcache User Cookie example is rather basic and does not demonstrate how to deliver fragments from the custom front controller.

Regrettably there is still not enough documentation on how to roll your own custom fragment renderer. Look at the api.php files and read through the numerous submodules to get the picture.

Last but not least, there are some (closed) support requests in the ticket tracker covering this issue, e.g. #2780485.


Integrating dropdown menu of different views options on a page

there is no option in views to expose any changer for 3 different blocks, one thing you can do is make a drop-down and show/hide views using javascript/jQuery or make single unformatted view and change format using js/css on dropdown change.(you need to make some custom codes.)


error 500 when D8 site placed in maintenance

BEGINNER VERSION

Maintenance mode is working in general. Use the following direction of debugging: FROM "untouched" Drupal TO your state.

Download a same core version of Drupal as you have. Turn on maintenance mode (without changing anything else), visit the page with a non-admin user.
Apply the settings in your link about (Drupal 8 maintenance page theming ) visit again the page with a non-admin user.

Whenever the site brakes you know where the problem resides.

ADVANCED VERSION

500 errors are always logged in Drupal. Check what says the "recent log messages" with admin.
Also you can set in your settings.php

$config['system.logging']['error_level'] = 'verbose';

This won't just show 500 error, but also tell the reason.


I think you're over-engineering things here.

If your CSS is per-node-specific and stored in the DB anyways, then why not just use a text field to store the CSS? You just need to create a field template to output the raw content of the field in a <style scoped> tag.


To provide the custom markup, you have to override the tpl.php file for that node.
To override this, follow these steps :

1) Copy the node.tpl.php in your theme.

2)Rename it node--"yourContentTypeMachineName".tpl.php
for example my custom file is now node--image_archive.tpl.php

3) to test it out write some text(anything) in your new node.tpl file.

4)paste your new node.tpl file back in you theme folder

5)Clear all cache

Now access all the field and provide the custom markup as you want.


How to perform entity validation on code level?

Fields have constraints defined on them and as everything is a field on an entity, that's that. See Comment::baseFieldDefinitions does ->setConstraints(array('CommentName' => array()));. Then there's appropriate plugin in the Drupal\comment\Plugin\Validation\Constraint namespace in a class called CommentNameConstraint. The logic is in CommentNameConstraintValidator.

So the chain is

setConstraints in basedFieldDefinitions setting a list of plugin ids (CommentName) and their arguments (empty array in the example
A plugin in the Drupal\modulename\Plugin\Validation\Constraint namespace with the appropriate plugin id. The classname is not magic, the plugin id is what's important. Using the plugin id plus Constraint as classname seems to be best practice.
Whatever classname you picked in the previous step, append Validator to it, make it extend Symfony\Component\Validator\ConstraintValidator and put your validation logic in validate.


Is there a way to hide the price on a product using Drupal Commerce?

I guess giving the product a price is a manual process.

To make things clear I suggest adding a 'price hidden' boolen field to the product content type. Based on this field you can adjust the output of the product by implementing hook_node_view_alter.


"drush cron" doesn't work anymore after moving the site to a new server

The issue was fairly simple to solve.

I had forgotten to create a settings.php for each site. I was able to find out by running the following command:

drush --local -d -r /var/www/testproject/build/html status

And from the output I was able to see:

[debug] Could not find a Drupal settings.php file at sites/default/settings.php. [0.14 sec, 10.8 MB]

That was it


JQuery Causes Seemingly Endless Loop and page load times of 1 minute + - "Warning: reference to undefined property D.cache[a][d]"

This is obviously not a problem in Drupal core. This mean the the issue is in one of three places:

The theme
Custom module (developed by you)
Contrib module from Drupal.org

I can think of two approaches to go about and fix this.

Debugging

Replace the minified JS file(s) with non minified versions and start debugging.

Experiment

Try disabling modules/theme at turn until the problem disappears and try to pin point the part in the module/theme that causes the problem and from there try to find a solution.

Personally I would go for the experiment route, as this is often the fastest way to gain initial results.


How to override system_time_zones in Drupal 7

I was able to access the timezone dropdown list by implementing hook_form_alter() with an #after_build function.  You can filter, clean and modify the array here.

function MYMODULE_form_user_profile_form_alter(&$form, &$form_state) {
   $form['#after_build'][] = 'MYMODULE_timezone_modify';
}

function MYMODULE_timezone_modify($form, &$form_state) {
   $form['timezone']['timezone']['#options'] = array(/*Your New or Modified Array Here*/);
   return $form;
}


How to render a field in a Views' PHP code field?

<?php
  print drupal_render($data->field_field_video);
?>


suggestions needed to define a class for field per entity/node

You are looking for Image Class module - either use it directly, or use it's code - it is open source after all.

  Extends the Image formatter by adding an option to add an element class.


https://www.drupal.org/project/admin_views makes the users and content page a lot friendlier. On of the things it does is putting a search field on the users page.

One of the modules I use on every project.


Efficient way to keep Drupal 7 session alive from another web app?

If you're worried about unnecessary overhead, why not check out the High-performance JavaScript callback handler module.

It allows you to control what exactly gets loaded during the Drupal bootstrapping process, so that you would only spin up the bare essentials to keep your session alive from another app.

Check out this blog post for a good breakdown of how you implement this module:

High performance AJAX callbacks with Drupal 7 and the JS module


How to make form update/rebuild every page load?

If you are not using Varnish or other server caching, first, I would try CacheExclude Module or something similar to prevent the page that the form resides on from being cached. In this way it should reload every time.


How to create dynamic drupal 7 taxonomy views

This is fairly simple in Drupal 7 with the help of EVA: Entity Views Attachment. You are able to then create only two(2) views.

The first view will render all your categories you have in taxonomy as well as calling in the second view into a field of this view.

Your second view will then display the entities associated with the taxonomy term,
You will have to create a Term reference in your content types in order to have a field in your entity view to check against.

I have previously done this where there are categories or terms displayed with a list of entities below them, all displayed in a grid view. See Example below.


Where Can I find the output of the debug() function displayed?

The output should be logged to the Drupal watchdog (admin/reports/dblog). If you're debugging a variable that is an array or object, don't forget to pass TRUE as the third parameter (ref).

Although the code in question may be in a function cached by Drupal, so sometimes you need to flush the cache to trigger that code to be re-run.

Personally, I prefer using the dpm() function from the devel module for debugging. If using an account with admin permissions, it displays arrays/objects in a way that is easier to inspect.


How to allow a role to add users without giving them a password?

People need a password in order to log in to the site.
Therefore you need to allways insert a password when creating new users.
You can add a default password and set the field as hidden on a specific role but new users will need to know the default password in order to log in.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {

    $default_value = isset($form_state['build_info']['args'][0]['pass'] ? $form_state['build_info']['args'][0]['pass'] : 'DEFAULT PASSWORD';

    if (in_array('YOUR ROLE', array_values($user->roles))) {
      $form['account']['pass']['#default_value'] = $default_value;
      $form['account']['pass']['#access'] = FALSE;
    }
  }
}

EDIT:

Ok I took the time to work this out and therefor I want to adjust my solution:
In order to get this properly working you need to override the full $form['account']['pass'] array. This is because it has the password_confirm type as default, which has the extra confirm field, keeping this type will result in an empty password field on the node submit.
Clive is absolutely right, using a #default_value on a password field results in an error so we need to use the #value. Thas was the unsupported operand types error.
Also, in my first answer I added a condition so see if the form is used to edit a user but now I know that the registration form and edit form are two different forms calling the same user_account_form so we can remove the condition.

function mymodule_form_alter(&$form, $form_state, $form_id) {
  global $user;
  if($form_id == 'user_register_form') {
    if (in_array('USER ROLE', array_values($user->roles))) {
      $form['account']['pass'] = array(
        '#type' => 'password',
        '#size' => 25,
        '#access' => FALSE,
        '#value' => 'DEFAULT PASSWORD',
      );
    }
  }
}

I tested this code and it works like a charm so if you have any problems with it feel free to contact me.


How to apply CSS to "views-exposed-form--view-name.tpl.php"

You could add the CSS in <style> tags on top of your template. Most browsers will probably understand what you want, it does result in ugly HTML though.

You could also add the CSS in your main CSS file and use .view-id-viewname .div (etc.) to target elements specificaaly in that view


Product Variation Token to fetch field of Product Display (Commerce)

although I solved this issue a while back just by applying the same Device term reference field on every variation form, maybe someone else happens to stumble upon this sometime:

just as I was messing with some rules yesterday, I found out about a token that deal with exactly this!
I just gave it a shot and it does exactly what I was looking for: refer to fields on the node that was used to create the variation.

the token that does this:

[commerce-product:field-product-node:0:

so, for example, the token in my case would look like this:

[commerce-product:field-product-node:0:field-device-name:field-device-sku]

(note that the screenshot in my original post is outdated, as I now determine the device name and SKU via a taxonomy term reference field-device-name)

keep in mind!:
although this may keep you from having to include the same field on the product variation, I reckon this is less reliable. you may run into trouble, if you happen to create (or edit!) a product variation from a different node that does not have the reference field (or has other input). note that even when editing an already existing product, the SKU will be re-generated on submit. so make sure you only edit the product from within the original node (or any node that has the same field with the same value), if you dont want the value of the token-generated field to change.

however, I could be wrong and it may be just as reliable, if the field-product-node:0 always references to the same node on which the variation was originally created, regardless of where you edit it later on. – someone will have to test this (and preferably report back) if he/she is interested in the exact behavior of this node reference token.
if anyone knows the answer, I would be interested in hearing how this behaves exactly. but since I'm sticking with the extra field in the variation, I do not rely on this method now.

hope this helps someone else in the future. (:


How to change the directory of file_create_url to default for a custom domain

try setting the public file system path in your -test site to match that of the other in /admin/config/media/file-system


How to create a view of existing blocks?

This question seems like a perfect illustration of why you'd use the Bean module (to actually create such view as in this question). Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

This module also works great in combination with the UUID and UUID Features Integration modules. And after you become familiar with the Bean module, you might find other cases in your site where you also want to use this module (which somehow compensates the fact that you need to add another module).

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

In this specific case, after you enabled the BEAN module, you should be able to create a view of blocks. As an illustration, have a look at this (basic) view (in Views export format):

$view = new view();
$view->name = 'blocks_created_with_bean';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'bean';
$view->human_name = 'View of blocks created via the BEAN module';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'View of blocks created via the BEAN module';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'bid' => 'bid',
  'label' => 'label',
  'title' => 'title',
  'type' => 'type',
  'uid' => 'uid',
  'url' => 'url',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'bid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'label' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'uid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'url' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Block: Internal, numeric block ID */
$handler->display->display_options['fields']['bid']['id'] = 'bid';
$handler->display->display_options['fields']['bid']['table'] = 'bean';
$handler->display->display_options['fields']['bid']['field'] = 'bid';
/* Field: Block: Label */
$handler->display->display_options['fields']['label']['id'] = 'label';
$handler->display->display_options['fields']['label']['table'] = 'bean';
$handler->display->display_options['fields']['label']['field'] = 'label';
/* Field: Block: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'bean';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: Block: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'bean';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Field: Block: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'bean';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Block: URL */
$handler->display->display_options['fields']['url']['id'] = 'url';
$handler->display->display_options['fields']['url']['table'] = 'views_entity_bean';
$handler->display->display_options['fields']['url']['field'] = 'url';
$handler->display->display_options['fields']['url']['link_to_entity'] = 0;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'view-of-blocks-created-via-the-bean-module';


Commerce product variation with different variations

For something like this, you can create a Type field on the product and then have allowed values for Fiber, UTP or other. If you create these as a Taxonomy field, then they can be used to categorize other products or services with that same term.

You can create all of the fields and then use custom code to alter the form states to require/hide/show/etc. various fields on the form. All of the fields will exist, but only some of them might be shown. When you create your template for the product, you'll just need to ensure that you theme it properly.


I managed to track down the place in core where the code for this specific theme is located, it was in core/includes/theme.inc and not in the field or system module where I previously searched. Copying from there did work in the end, using render element in hook_theme() is correct, but I was missing an important preprocess function.

I defined the following function and called the original preprocess function from there:

function template_preprocess_field_image(&$vars, $hook) {
    template_preprocess_field($vars, $hook);
}


How do I create taxonomy terms from an exploded list?

An important caveat thats missing from How to add multiple terms to a taxonomy reference field via feeds? is that the taxonomy terms already need to be defined in the vocabulary that you are referencing in order for feeds tamper to assign the term reference value to the node.

In the past I have created two feeds importers, one that is a taxonomy term processor that just contains the terms to load into the vocabulary, and one that is the node importer to import the nodes and have the taxonomy terms assigned to those nodes.

I may be wrong, but I dont believe that you can import nodes and simultaneously populate the taxonomy vocabulary in one step with feeds.


How do I add custom CSS to individual pages?

Well the absolute simplest way is to look at the body class using firebug or developer tools with chrome.

You will see something like this:

<body class="html not-front logged-in no-sidebars page-node page-node- page-node-19 node-type-log-node admin-menu">

Which as you can see even has the node id for the page. Then its just a simple case of using

.page-node-19 {
background: #000000;
}

Or whatever!

And, if you want to get super in detail with adding stuff to certain pages, themes, regions, dependencies on which users etc etc then look into the context module and all its related modules.


Yes. There obviously isn't a Drupal 7 module for this yet (http://drupal.org/project/kwicks) but you can always just include the jquery plugin in your own theme / block implementation and roll your own slideshow.

Actual implementation of this would depend on what you are trying to do but according to the Kwicks documentation, all you need is to apply the kwicks js to a simple unordered list like this

So one (module-less) way you could do this is is to create a content-type of whatever it is you want to be in this slider, than create a view of these nodes with a style output of HTML list. In your views header, add a  tag to include the kwicks code in:

and then whatever jquery config you need to make the slide show, ex:

and output it as a block / page to place it where ever you want on your site.


No, not currently. As the UI suggests, the complex mappings can be set in the module's install/config/cdn.settings.yml config file, but it only allows for segmenting traffic to different CDNs based their extension.

The FileUrlGenerator service object handling the file URL rewriting doesn't consider a path context while deciding when/when not to serve file from the CDN.

You could replace this service class via the ServiceModifierInterface and its ::alter() method with a custom service class that does consider the path context.


How to show event title and time in calendar block?

Do you mean you would like to add the event name and time to the calendar you have provided on the top? If that's what you're asking, I don't think you can, and that is what the month page is there for. In Views, can you make the month page a block instead and place that wherever you need it?


How to save node text and comment text to session or cookie while typing

There was by crell: module Autosave. Not ported to d7 though.
Here is a quote about it (from the module's project page):

...  automatically saves a snapshot of your content type form using AJAX. If the user's browser or machine dies while editing a node; the edits will be presented to the user the next time they return to the node. The user may toggle back and forth between the last saved version and the version with the edits that were lost and select which of these they would like to continue with.
How often a form is autosaved as well as which content types to enable autosave for are admin configurable.


I have created a drush command to run only the scheduled_updates_cron() function from the command line and also from crontab. I didn't know why all of my updates were invalid till I saw your post, so I made some research and I managed to make my drush command work like the "Run Updates" button from Scheduled Updates Overview page, by specifying the user who should run the update.

Example (Wrong results): drush command-name

Example (Good results): drush --user=1 command-name

If you are using the drush croncommand, you should modified it to drush --user=1 cron

I hope this helps !


As per documentation you can do like this.

Logout

GET http://example.com/user/logout
Content-type: text/html
200 - OK

Note: Do not pass "?_format=json" it is not accepting.


Where can I find where this content is being loaded from?

That's not a simple question, it depends on the site. For your case you will first want to check Nodes (Content items) as that could be a WYSIWYG field. Otherwise if it's hard-coded it would most likely be in the theme folder that's currently enabled.

You can also check Views for the page that's showing all of them as a series of images. That could give you information on what type of Content they are.


Sorting Views result rows based on an array of node IDs

I got my answer via the Drupal Slack, but reposting it here for anyone who might come across this later, since that's not publicly searchable. It was more of a PHP issue than anything Drupal-specific.
Within the uasort() callback, the $left and $right arguments are objects of the ResultRow class, with nid available from them, so switching $leftPos and $rightPos to $flipped[$left->nid] and $flipped[$right->nid], respectively, gets me access to the results' nids.
/**
 * Custom uasort() callback to sort view results by points totals.
 */
function MODULE_sort_by_points_total($left, $right) {
    $order = ['704', '712', '707', '713', '711', '709', '708', '883', '882', '715', '714', '710', '705'];

    $flipped = array_flip($order);
    $leftPos = $flipped[$left->nid];
    $rightPos = $flipped[$right->nid];
    return $leftPos >= $rightPos;
}

Continuing on, I figured out that switching it to an anonymous function was what I needed to pass $songAndPoints to the uasort() function, as follows, instead of separating it:
$sortByPointsTotal = function($left, $right) use ($songAndPoints) {
    $order = array_column($songAndPoints, 'nid');

    $flipped = array_flip($order);
    $leftPos = $flipped[$left->nid];
    $rightPos = $flipped[$right->nid];
    return $leftPos >= $rightPos;
};

uasort($view->result, $sortByPointsTotal);


Hide some of the fields of user profile of profile2 module

hook_entity_view can be used all core and most contrib entities and the more specific hook_user_view can be used when the user account is used - this is, however, not the same as the user profile itself.

You should note that this wont effect fields and entities displayed by views.


how to prevent a theme from using templates of a sub themes (placed inside the parent theme dir)?

Themes are not allowed to be placed inside one another, as oppose to modules. Even though it works, there are undesired side effects.


You can use rules for this to add custom field or you can use "hook_services_request_postprocess_alter" to add new array with custom field.

Using rule you can set in event "Content is viewed of type .." and in action you need to custom php that returns $node->custom_field = val;


_entity_form doesn't accept a form class directly, only via a form handler. See https://www.drupal.org/docs/drupal-apis/routing-system/structure-of-routes

_entity_form: It is similar to _form, but it will provide an edit form for an entity. Entity form handlers are defined in the entity metadata
(annotation). For example, _entity_form: node.default will display the
default node form. "node" in node.default refers to the entity ID, and
"default" refers to the form handler key.


How can I change the selectable years in a date field?

@mpdonadio♦'s answer provides the explanation.  Here is the actual code I used:

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['field_birthday']['widget'][0]['value']['#date_year_range'] = '1950:2005';


Migrate from xml with two attributes as condition

You don't mention what XML source plugin you're using - is it MigrateSourceXML? If so, note that (as documented), it does not read in the entire XML file thus general-purpose xpath is not available, it implements a limited subset of xpath syntax for selecting the items to import. You should use MigrateSourceMultiItems when you need full xpath syntax.


Skip checkout process if special field has value

You can implement hook_commerce_checkout_router and there check if order has product that has special field value

function hook_commerce_checkout_router($order, $checkout_page) {
  /*
if $order has product with special field
drupal_goto('');
  */
}


Displaying a list of all the content types

I have done something similar using Views and the Summary option for Contextual filters.
I added the Content Type as a contextual filter with the following options:

The end result was a view that displays the following, if you have not specified a Content Type in the URL as an argument:

The only issue I found is that I won't display Content Types that have no content.


Brackets in URL Field Get Reformatted to %5B%5D

Though I have not come up with an answer to my question, the easy work-around I created was to add a text field instead of a URL field in my content type.

I then used the Linked Field Module to link the text field to the outside website.  This preserved all of the crazy characters that were needed.

For those not familiar with the Linked Field Module, after you have added a text field to your content type, go into:

Manage Display for your content type
Set the Format to Default
Click on the Gear Symbol
Say No to link to content
Check the box to Link the field
For Destination use the field item name with dashes, like this [node:field-online-link-to-resource]
Use the Advanced section to add a title, link text, etc.

FYI that I would only allow trusted content editors to add data to this type of field.


The way I deal with this issue is to use the ImageField Tokens module:

  The ImageField Tokens module extends the default functionality of
  Image fields adding the ability to specify default values and use node
  tokens in the Alt and Title text.

The module Token is required. After you install and enable the modules, you configure its settings in the field properties for each individual content type.


Views: Computing user's age "on the fly"

This might help you with the "on the fly" age calculation:

PHP calculate age
Calculate age based on date of birth

Then use the Views PHP module to implement it in your view. Or if you want to use the SQL method you could use the Views Raw SQL module.


Send mail to users including receiver's username

There isn't a setting for that, but when a user sends an email to another user, using the contact form of the other user's account, the Contact module sends a message that start with (I sent an email to myself from Drupal.org):

  kiamlaluno,

  kiamlaluno (http://drupal.org/user/55077) has sent you a message via your contact form (http://drupal.org/user/55077/contact) at drupal.org.

  If you don't want to receive such e-mails, you can change your settings at http://drupal.org/user/55077.

The first line contain the receiver's username.

The following snippet is part of the code present in contact_mail(), the function that alter some of the messages sent from Drupal.

case 'user_mail':
case 'user_copy':
  $user = $params['user'];
  $account = $params['account'];
  $message['subject'] .= '[' . variable_get('site_name', 'Drupal') . '] ' . $params['subject'];
  $message['body'][] = "$account->name,";
  $message['body'][] = t("!name (!name-url) has sent you a message via your contact form (!form-url) at !site.", array('!name' => $user->name, '!name-url' => url("user/$user->uid", array('absolute' => TRUE, 'language' => $language)), '!form-url' => url($_GET['q'], array('absolute' => TRUE, 'language' => $language)), '!site' => variable_get('site_name', 'Drupal')), $language->language);
  $message['body'][] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE, 'language' => $language))), $language->language);
  $message['body'][] = t('Message:', NULL, $language->language);
  $message['body'][] = $params['message'];
  break;

Other modules can change the content for the sent emails, if they implement hook_mail_alter(). This means that other modules could remove content from the email sent via the contact form; it also means that another module could replace the username used in the first line with the first and last name provided by the receivers in their user profile.


Possible to set user privileges on part of the text?

No, there are no ways to do this. And there shouldn't be. First of all, read PHP in database: bad practice but - this addresses exactly the situation you have here. Long story short: don't do it. Turn off PHP module if you don't need it.

And why you don't need it? Because there is Viewfield module.

  Viewfield provides a field that holds a reference to a View and renders it whenever the entity containing the field is displayed.

Exactly what you want to do, but without any snippets in user editable texts.


OK, what I came up with here:

function save_my_image($uri) {
  //copy file into drupal files directory
  $contents = file_get_contents($uri);
  //then save into drupal's file system
  $file = file_save_data($contents);
  return $file;
}

file_save_data() (http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/8) will handle creating an fid for the file and keeping track of it generally.. then simply add the fid to the node in question and you should be golden.


After implementing hook_node_access, how to stop node from appearing in view?

having run into the same problem as you I hope I can save you a headache.
Depending on the amount of results you have I can provide 2 ways to tackle this:

1. Works when you don't need pagination

HOOK_views_post_execute. This will have the rows in the variable. In here you can check the access and unset() the rows not allowed.

2. Works when you need pagination

HOOK_views_query_alter. I've used this solution for a view I needed myself with around 10000 results. I do a custom permissions check based on the user and the groups they are part of. Baed on this I generate a list of ID's of nodes they user is allowed to see. I add these ID's as an "IN" query to the view:

$cond["field"] = "media_field_data.mid";
$cond["operator"] = "IN";
$query->addWhere('1', $cond["field"], $mids, $cond["operator"]);

Where $mids has all the allowed Mids in there.
Hope this helps you get along!


With @4k4's suggestion, I found the problem. After each request has a ajax request. The request has route name is quickedit.attachments and method post. So I edited code like that:

public function setSession(Event $event) {
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (!$event->getRequest()->isXmlHttpRequest()) {
      if ($route_name == 'view.frontpage.page_1') {
        $_SESSION['page'] = 'Home page';
      }
      else {
        $_SESSION['page'] = 'Other page';
      }
    }
  }

Now it's working good. Thanks!


If you want to do it this way then you have to symlink the folder to the root of the drupal install:

cd /var/www/drupal
ln -s . site1

Then within sites.php use the following:

$sites = array(
    "example.com.site1" => "site1",
);


Block displaying one parent and many children nodes using only Views 3 Drupal 7?

I've achieved the desired output by creating a vocabulary of taxonomy terms which is essentially just a flat list of foreign keys. There is no semantic representation of a hierarchy here.

NOTE: This is a different example than the event calendar I described in the comments of my initial post, however the data model is the same.

Parent content type (Rich Menu) contains this taxonomy term field, in this example called "Menu".
Child content type (Rich Menu Item) also contains the "Menu" taxonomy term field.
If Rich Menu Item is a child of Rich Menu, the two term fields are set to match. NOTE: I wonder if this idea can be simplified using node references (References module) instead of taxonomy.

Then I created a new block view called "Rich Section Menu". This block will display the parent content type, Rich Menu, filtered by the taxonomy term from the field "Menu" (value = Section). Create an attachment to be displayed after the block which will render a list of children from the Rich Menu Item content type. The child content type will also be filtered by the Menu term field (value = Section). NOTE: Adding the relational term field to the list of filters is only necessary if you expect to have multiple parent/child relationships that share the same content types.

Tried to post screenshots of my Views configuration for clarity, but my reputation isn't high enough.

This achieves the output I desire, however it's a bit simplistic. I would prefer to create a semantically correct parent/child hierarchy using taxonomy or node references, and have Views render that output in a single block, without an attachment, with support for children more than one level deep.

So this works, but is there any way that I can do it better?


How to Render a field collection item in a Twig template in tabular view

There is not only one twig template, there are three levels of twig templates in a field collection field:

1) The field template for the field-collection field: field--field-collection.html.twig

2) The field-collection template itself: field-collection-item.html.twig

3) The field templates for the fields inside of the field collection: field--field-collection-item--field-field1.html.twig

When you are in the top level, the fields of the field collection are not built yet and you have no access to the rendered fields.

The best approach is probably to put the table structure in all three levels, in 1) the header and footer, in 2) the row and in 3) the cells.

There is one problem with this approach. In 1) you don't have the labels for the header. If you don't want to hardcode them, you can try to get them from the configuration of the field collection in a preprocess hook.


Disable Rule which is causing a redirect loop

You got a few options.

You can try to edit the data by deserializing it with PHP and try to get some meaning out of it. Most likely there is a status which is either 1 or 0.
You could delete the rule from the database entirely.
You can temporarily modify the rules_invoke_event (rules.module line 249 for 1.4), if you comment out the call_user_func_array call, no rule should be invoked on the site.

Either of these should work, personally I would go for the last one if I had write access to the rules files.


Drush archive-dump override sql dump name

Unfortunately, there is no way to stipulate what the sql dump file should be named.  See the archive-dump source code for reference.

Wouldn't be too hard to adjust; PRs would be welcome.


So I finally found the culprit. A php symlink in the bin directory linking to an old version of php. I guess even though drush showed it was using version 7.3, those scripts used that symlink and was pulling in an older php version. Error is gone and I can finally update through drush.


Conditional fields not working with hierarchical select module

Actually I found Conditional field to work with HS but you must enter numeric value of the dependee. For Example if you want to display the field only when term "abc 1" is selected then you check what is the numeric value of that field in the database .lets say the value is 12. That's all you need to enter an its working


Picture linked to user's profile in user-picture.tpl.php

template_preprocess_user_picture() uses the following code.

  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

Assuming you just want to use a specific image style for the image, and hard code it in your theme, I would use the following code for mytheme_preprocess_user_picture(). (Replace mytheme with the short name of the theme.)

  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath)) {
        $variables['user_picture'] = theme('image_style', array('style_name' => 'square', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

Doing so, the template file would just need to print $user_picture.

Keep in mind that the image style used for the user image is contained in a Drupal variable. I would investigate on how to change that variable for the theme you are using, even though you would then need to change it back for the other themes, in the case your theme is not anymore the active one.


You need to add the image in that view's template file.

For views hook suggestions refer to this page http://api.drupal.org/api/views/theme!theme.inc/group/views_templates/7

It would be best if you copy the default views-view-fields.tpl.php from views module to your theme directory and add the image there.


How do I use form_set_error() the right way?

You should be looking at form_set_error instead

if you have an element like this:

function my_custom_module_form() {
  $form = array();
  $form['my_element'] = array(
    '#type' => 'textfield',
    '#title' => 'My Text field',
    '#default_value' => 'Some default text.',
  );
  return $form;
}

in your validation callback function do this if you find that the values in $form_state['values'] aren't valid

function my_custom_module_form_validate($form, &$form_state) {
  // Do some checking on $form_state['values'], if you don't like it.
  form_set_error('my_element', 'This is the error message that will be displayed.');
}


Contextual filter that lists users who share a taxonomy term with current user?

Provided you have two fields on your user profile called field_working_in and field_want_to_work_with execute the following steps:

Add a Users view at admin/structure/views/add and set Display Format as Table
Add two fields User: Name and User: Working in
Add relationship with  User: Working in
Add relationship with Taxonomy term: User using Want to work with
Add a contextual filter: User: uid with Provide Default Value and Type: User ID form logged in User and set a relationship with field_want_to_work_with (see screenshot)
Under FILTER CRITERIA Add the following filter to exclude the current user from the results: User: Current (No)

Export of view:

$view = new view();
$view->name = 'user_sections';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User sections';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User sections';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: User: Working in (field_working_in) */
$handler->display->display_options['relationships']['field_working_in_tid']['id'] = 'field_working_in_tid';
$handler->display->display_options['relationships']['field_working_in_tid']['table'] = 'field_data_field_working_in';
$handler->display->display_options['relationships']['field_working_in_tid']['field'] = 'field_working_in_tid';
/* Relationship: Taxonomy term: User using Want to work with */
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['id'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['table'] = 'taxonomy_term_data';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['field'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['relationships']['reverse_field_want_to_work_with_user']['relationship'] = 'field_working_in_tid';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Working in */
$handler->display->display_options['fields']['field_working_in']['id'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['table'] = 'field_data_field_working_in';
$handler->display->display_options['fields']['field_working_in']['field'] = 'field_working_in';
$handler->display->display_options['fields']['field_working_in']['label'] = '';
$handler->display->display_options['fields']['field_working_in']['element_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['element_wrapper_type'] = '0';
$handler->display->display_options['fields']['field_working_in']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['field_working_in']['delta_offset'] = '0';
$handler->display->display_options['fields']['field_working_in']['field_api_classes'] = TRUE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['relationship'] = 'reverse_field_want_to_work_with_user';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Current */
$handler->display->display_options['filters']['uid_current']['id'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['table'] = 'users';
$handler->display->display_options['filters']['uid_current']['field'] = 'uid_current';
$handler->display->display_options['filters']['uid_current']['value'] = '0';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user-sections';
$handler->display->display_options['menu']['type'] = 'normal';
$handler->display->display_options['menu']['title'] = 'User sections';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['name'] = 'main-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['user_sections'] = array(
  t('Master'),
  t('User sections'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('term from field_working_in'),
  t('field_want_to_work_with'),
  t('Name'),
  t('All'),
  t('Page'),
);


It was because I hadn't called the save method on the $custom_entity object.

Credit and thanks to Andy


How would I insert one item into the user-edit page with templates?

Although you could add a button into the template, this is done better with the forms api using a custom module. You can use hook_form_FORM_ID_alter to alter the user_profile_form and only make the small change you want while leaving the rest of the form untouched.

As an example, you could add a button "My cool action" to the use profile form with the following code. You just need to replace MODULE with the actual name of the module you put it in.

function MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['newaction'] = array(
        '#type' => 'submit',
        '#value' => 'My cool action'
    );
    $form['actions']['newaction']['#submit'][] = 'my_newaction_callback';
}

function my_newaction_callback($form, $form_state)
{
    // this function is called when your button is pressed
    // do whatever you want here.
}

Update #2

You could place the button in the middle or top of the page using the following code and figuring out which weight places it where you want. Try a weight of 0 to have it near the middle.

$form['newaction'] = array(
    '#type' => 'submit',
    '#value' => 'My cool action',
    '#weight' => -3,
    '#submit' => ['my_newaction_callback']
);


If you're looking for a custom-code centric path. Both D7 & D8 provide a hook_views_pre_execute() hook. It will trigger prior to any view query execution.

You can hook into this function, inspect $view object for the particular view you're wanting to extend your PHP execution, then call the PHP function of your choice.


Drupal validation for nested field element

Its working now, code as follows

form_set_error('field_coaching_programme][und][0][field_organisation_delivered_by', 'Organisation delivered by field is required.');


$form_state->setValue() doesn't save value

If it is a custom variable, you should use $form_state->set('property_name', 'value') (instead of "$form_state->setValue(...)").

Example:

public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Update custom variable (in PHP "null + 1" equals one)
    $form_state->set('my_variable', $form_state->get('my_variable') + 1);

    // Below is only required when your "buildForm(...)" depends on the variable
    $form_state->setRebuild();
}


"IMCE Uploader" module is preventing some file types from being uploaded within IMCE

I am thinking that perhaps your allowed file types has changed in your IMCE profile, or IMCE Uploader has created a new profile for you and is using it by default. Check admin/config/media/imce/ and make sure the profile you are using allows those file types.


How can I make Drupal/MySql accept special characters in ANSI (without changing the file's encoding)?

Found it. I just needed to encode the values with:

$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);


Maybe you want to consider the Forena module (disclosure: I'm a co-maintainer of it) ... Here is a quote from that page:

... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

My answer to "How to retrieve data directly from a Drupal database" contains like a 1 minute summary to explain the typical (about 3) steps for creating:

a connection to an external database (typically by an admin).
a custom SQL query (typically by an admin).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).

These steps (without any PHP coding involved ...) are like the equivalent to writing the PHP coding as included in the question there.
For an online demo (prior to installing/testing Forena), refer to these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.

Forena Documentation, which you also get in your own site after installing the module). It contains topics such as (incomplete list):

Module installation and administration, a kind of getting started guide.
WYSIWYG Report Writing, using a report editor to facilitate the creation of reports.
Site Building, topics about integrations of Forena with other Drupal modules.
Forena hooks, to use it in other (custom) modules.


Adding CSS class to fields (Content Types)

Try out Field Formatter CSS Class module.

  allows you to set any text/list/option/taxonomy field to render as CSS
  class on the node. This enables the node author to select predefined
  CSS styling per node.


How can I set the site root page to a landing page instead of user login?

Under /admin/config/system/site-information simply set a default front page which can be a node /node/123 a Views page /my-view or any other custom page /foobar/landing-page.

If you leave this empty it falls back to /user/login (which when you are logged in redirects to your user page).

To have the "Promoted to front page" setting in nodes respected set the default front page under /admin/config/system/site-information to /node. This is the path to the front page View you can edit yourself. This view by default displays node teasers and respects the "Promoted to front page" and "Sticky at top of lists" flags. You can have multiple nodes at the same time to be promoted and/or sticky.


Update UI lists modules/themes that are already updated

This was caused by the Update Status Advanced Settings (update_advanced) module.

I didn't know this module was installed or what it was, so here's how I traced it back:

modules/update/update.compare.inc is where the core update module checks versions of each module and theme, beginning with update_calculate_project_data() - this creates a $project array that contains current/recommended versions, plus a numeric 'status' key.

'status' is a constant, set in modules/update/update.module, with values including:

define('UPDATE_CURRENT', 5); // project is up to date
define('UPDATE_NOT_CHECKED', -1); // Project's status cannot be checked.

I used Xdebug on update_calculate_project_data(), specifically tracking the modules that were stuck on the update screen.

They all had a status of UPDATE_CURRENT initially (as expected/desired), but that changed to UPDATE_NOT_CHECKED after the call to the hook in line 363:

drupal_alter('update_status', $projects);

Searching the code base, found this hook is implemented in sites/all/modules/update_advanced/update_advanced.module:50 by update_advanced_update_status_alter()

If you've got this module, the settings page is /admin/reports/updates/settings; you can instruct it to not warn you about specific modules.

The side effect is that by changing the status to anything other than UPDATE_CURRENT, a module/theme will always be listed in the Update UI (modules/update/update.manager.inc:94), including if the module is "current" really.


How do I check whether the patch for SA-CORE-2018-002 is applied?

As you see in top of the patch, the patch changes the bootstrap.php file, so you can check that file has been changed, and it contains the correct code.

FAQ about SA-CORE-2018-002
 describes why the patch is a security patch.


Accidentally deleted uploaded files, now I can't remove missing files from node

You should upload via FTP a file with the same filename and path as the deleted file. The file content doesn't matter.

Then edit the node and delete the file from the node editor.


Much easier way:

Add "Global: View result counter" Field
Exclude it from Display
In Slideshow setting: choose that field as the Pager Type


When using custom twig expressions to rewrite view title, the breadcrumb shows the twig expression without replacing it

I had a similar issue where I needed my view title to be {{ field_first_name }} {{ field_last_name }}. The head title tag and page title were correct, but the twig variable's value wasn't being rendered for the breadcrumb.

I ended up writing a tiny module in which I get the title then set the title to the title. Somehow, doing this in post_render makes the twig get rendered correctly in the breadcrumb. Hopefully someone will come along and tell us why this works or why it was needed.

?php
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_render().
 */
function peopleview_views_post_render(ViewExecutable $view) {
 if ($view->id() == 'people') {
  $title = $view->getTitle();
  // Set the view title.
  $view->setTitle($title);
  // Set the route title.
  $route = \Drupal::routeMatch()->getCurrentRouteMatch()->getRouteObject();
  $route->setDefault('_title', $title);
 }
}


How do I display bare, stripped content with no menus, footers, etc?

Main layout of a page is done in the page.tpl.php file. You have to override that templates for your bare pages in order to not output anything you don't want to see on the page. The correct way to override the used templates for a particular situation is to use suggestions.

From the Drupal 6 Template Suggestions, you can see that the suggestions to override this templates are summarized as page-[front|internal/path].tpl.php. So, out of the box, you only have to option to provide a bare template for either the front page of the site or all pages starting with a given path. There is no suggestion that allow you to override the page.tpl.php template for node pages of a specific content type.

But if you look at the page.tpl.php documentation, you see that the template has access to a $node object: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345). Using this information, you can use the template preprocessing in your theme to add an additional page.tpl.php suggestion.

function THEME_preprocess_page(&$variables) {
  if (!empty($variables['node']) {
    $node =& $variables['node'];
    $op = arg(2);
    if (empty($op) || $op == 'view') {
      $variables['template_files'][] =  'page-'. str_replace('_', '-', $node->type);;
    }
  }
}

This should add the page-<content type>.tpl.php template suggestion for node pages. You can then create the page-barepage.tpl.php file with your simplified markup.

Keep in mind that this will not prevent Drupal from processing and rendering any blocks for the page, it will only prevent them from being outputted in the page.


Create custom front page without adding content

In your case, yes you can create settings form, where admin will load background images, logo and enter description. But why you want use picture module? You can define new variables in hook preprocess_page for front page. Where in variable you put url to background image, url to logo, descriptions. After in front page template file, set url background to our block, logo and place descriptions.
Finally add styles to block class or id in css file for align background at the block. For this you can use something like this:

.your-class {
    background: transparent url("path/to/background.jpg") no-repeat scroll 50% 50% / cover;
    width: 100%;
}

background url you add in template. I write path to url in code for quick example, you can place this code in some div, add correct url and see result.


Make all the fields in a form not required

If you're ok with the risks that this might well pose to the integrity of your content you could probably use a simple recursive script like the following in a form alter function:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'myform_name') {
    $form['#after_build'][] = '_MYMODULE_remove_required';
  }
}

function _MYMODULE_remove_required(&$element) {
  $element['#required'] = FALSE;

  foreach (element_children($element) as $key) {
    _MYMODULE_remove_required($element[$key]);
  }
}


Difference between "site:current-user:field-foo" and "account:field-foo" in setting a Rules condition?

As I mentioned in the comments the variables you have available to you in a rule depend on the context it's in.

[site:current-user] is a global token available to any rule and will always return an object relating to the currently logged in user.

The [account] token is there because you're responding to the "After saving a new user account" event; that event passes an object relating to the user object that has just been saved (for obvious reasons).

I guess the main distinction is that the former will always give the currently logged in user, while the latter could be a different user object altogether (if, for example, an administrator had created the account).


how do you restrict directory path to role?

This depends on what that path is? Drupal has many kinds of paths and default permissions out of the box. If this was a Book hierarchy default permissions exist for books. The same for Taxonomy terms and other types of content. If this was a Views based path, you could configure Access rules in your view.

Without any 3rd party module support I would look at hook_menu if you are defining these paths yourself or hook_menu_alter if they are provided by another module.

Drupal Roles are not a reliable way to deem access to content -- I would alter the access callback for this path to use user_access permission values and create a custom permission such as view my custom site area and give that permission to  desired roles. Then I would an access arguments of view my custom site area so the user_access check works on those paths.

The Workbench Access module can do what you're asking if you define the Access rules using the Menu Scheme and not Taxonomies, but this module only works for Nodes last I checked.

  Workbench Access provide the hierarchical permissions across
  "Sections" of your web site. You can use menus, taxonomy, or create
  your own hierarchical structure for controlling access to a piece of
  content.


How to write a service module for Drupal 7 and Services 3.x?

In addition to the link mentioned, here's some code from a module I wrote that uses webservices. Under "structure" the service should be enabled and an endpoint defined. You also set the allowed return types there.

So if you define 'api' as endpoint and want a json array, you would do a request like yoursite.com/api/servicename/arg1/arg2.json. You define the service name in  hook_services_resources.

<?php

// $Id$
/* * **********************************************************************************************
 * @file
 * Based on the RESTful API shell module http://drupal.org/node/1034540
 */

/* * *************************************************************************************************
 * Include necessary files
 */
require_once (drupal_get_path('module', 'graph_data_api') . '/model/highchart_graph.php');

/* * *************************************************************************************************
 * Implementation of hook_help().
 * @see http://api.drupal.org/api/function/hook_help/6
 */

function graph_data_api_help($path, $arg) {
  $msg = t('
Provides a API for graph data for use with Highcharts.
');
  switch ($path) {
    case 'admin/help#graph_data_api':
      return $msg;
    case 'admin/modules#description':
      return $msg;
  }
}

/* * *************************************************************************************************
 * Implementation of hook_disable()
 * @see http://api.drupal.org/api/function/hook_disable/6
 */

function graph_data_api_disable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_disable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_enable()
 * @see http://api.drupal.org/api/function/hook_enable/6
 */

function graph_data_api_enable() {
  cache_clear_all('services:methods', 'cache');
  //eco_debug( '*** graph_data_api_enable() called!' );
}

/* * *************************************************************************************************
 * Implementation of hook_perm().
 * @see http://api.drupal.org/api/function/hook_perm/6
 */

function graph_data_api_permission() {
  return array(
      'request graph data' => array(
          'title' => t('Request graph data'),
          'description' => t('Allows user to use the graph api for Highchart graphs'),
      ),
  );
}

/* * *************************************************************************************************
 * Access callback
 * For now only view/retrieve is implemented and if the user is logged in, he gets access
 */

function _graph_data_api_graphdata_access($op) {
  global $user;
  $access = FALSE;

  switch ($op) {
    case 'view':
      if ($user->uid) {
        $access = TRUE;
      }
      break;
  }

  return $access;
}

/* * *************************************************************************************************
 * Implementation of hook_services_resources().
 * For now only retrieve with a GET request is implemented
 */

function graph_data_api_services_resources() {
  return array(
      'graphdata' => array(
          'retrieve' => array('help' => 'Retrieves graphdata',
              'callback' => '_graph_data_api_graphdata_retrieve',
              'access callback' => '_graph_data_api_graphdata_access',
              'access arguments' => array('view'),
              'access arguments append' => FALSE,
              'args' => array(
                  array('name' => 'parameters',
                      'type' => 'string',
                      'description' => 'The parameters that define requested data',
                      'source' => array('path' => '0'), // first argument in the url
                      'optional' => FALSE,
                  ),
              ),
          ),
      ),
  );
}

/* * *************************************************************************************************
 * Callback for the retrieve resource
 */

function _graph_data_api_graphdata_retrieve($arg) {

  $data = 'hello world';
  return $data;
}


How to name views-exposed-form.tpl.php per views display

For Drupal 7, you can use views-exposed-form--view_name--display_name.tpl.php (Replace underscores with dashes in view name and display name.)

It worked for me that way.


How do I mimic Pathauto transliterated output for an alias in my custom PHP code?

If you want to filter your string the way pathauto does it, you can use pathauto_cleanstring():

module_load_include('inc', 'pathauto', 'pathauto');
$node_title .= pathauto_cleanstring($node->title);


Using code field to display field from referenced entity

Use views and a contextual filter with the entity reference relationship you have created. Use EVA to get the block as field in Display Suite.

Display Facility nodes, choose the right format (I'd go for Unformatted List). Create the relationship in the right panel choosing two references, one that points from Facility to User, then one the points from User to Telephone using the first relationship.

Use contextual filters, provide default value Content ID from URL, validation criteria Facility content type.

Add a field "Title" using the second relationship. Now you have a block that you can publish on your page. If you need it as field in DS, use EVA to create it.


For Drupal 7, is there a hook debug mode equivalent to the theme debug mode?

You could create a custom module and use hook_module_implements_alter which takes two arguements - $implementations and $hook.

Try this:

function MODULE_module_implements_alter(&$implements, $hook) {
  if ($hook == 'form_alter') {
    print_r($implementations);
  }
}

This will print out a list of all the implementations, in order, for hook_form_alter.