Agree with the above and I would also add several suggestions:
 - use Taxonomy and Taxonomy Access Control modules to control access to
   content and who can update which service node
 - use Computed Field module that would take a value from related content to change a value (price) of the service/order depending on who did the work and what was the final price

Also, maybe this problem should be approached from a different angle? Maybe the service "product" should still be sold through e-commerce but instead of being "sold" would be "ordered" first, service performed and only then the final price updated, sold and ready for payment? Possibly that would require adding extra step in the checkout or allowing people to "order service" (Service would be a content type that people could assign to themselves as the "buyer") and only when performed and price was assigned, the Service would go through regular e-commerce checkout process with payment mechanism.


Can you change the view item output amount depending on user role?

I'd clone the view, the public one I'll name (temporarily) Public and change the access permission so anonymous users can view it.  The original one I'll name (again temporarily) Private and change the access to the authenticated user role.

Now you have two view displays, Public & Private.  Public display setting can be 2 and Private can be set to unlimited.


Cannot import multiple nodes in feeds module using csv files

You file shows 20 rows. From your description, I bet that the GUID has been the same for each import, and you have actually created one node 20 times. (Created once then updated 19 times.) You need to define a unique field in each record, with a corresponding unique field in your node (eg guid). Then feeds will map that field to determine which nodes to create (no nodes with matching unique field) or to update (node has a matching field).

Try using the Title field as unique instead of guid.


How do I programmatically set the preferred language for a user?

Seems D8 doesn't have a setPreferredLangcode method yet. So, the preferred approach IMHO would be to use the default set method of D8 Entity API as below
$user = \Drupal\user\Entity\User::load('uid');
$user->set('preferred_langcode', 'en or whatever langcode we want');
$user->save();


How do i take a specific node and turn it into a block

I would suggest using views for this.

Create a "Content" view and choose your content type in the "Show" dropdown
Uncheck "Create a page" and check "Create a block"
Choose "Unformatted list" and "Full posts"
Limit the block to 1 "items per page"
Click the Continue & Edit button
Add a contextual filter for Content: NID
Provide a default argument of Fixed value and enter the Node ID of the node you want to display within the block

Optionally, you can choose to create a fields based view instead of full posts which would allow you a little more control over the layout of the nodes content within the block.

If you are set on not using ANY modules to do this then you'll want to look into https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view_MODULE_DELTA_alter/7 which would allow you to override a blocks output in your themes template.php.

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_BLOCKDELTA_alter(&$data, $block) {
  $data['content'] = drupal_render(node_view(node_load($nid)));
}


Did you check:

Template (*.tpl.php file) override. I am not sure if preview shows template overrides.
Template.php for altering hooks
Contrib modules for altering hooks


Can you do branching multistep forms in ctools?

Yes, branching logic can be done.

If your validation/submit handler for step 1 sets $form_state['clicked_button']['#next'] = '2c, your next step will be 2c.

There are a few gotchas, which may or may not surface depending how your forms are intended to be used, whether they allow stepping backwards, etc.

All your steps should at least be in $form_info['forms'] so the wizard knows how to load them.

Note however, that if step 2c is not in $form_info['order'], the default "trail" generated by the wizard will not have any of the steps highlighted as it can't figure out where 2c fits in. Likewise, the next/previous steps around 2c may not be the ones you intended if 2c is not listed in the normal flow order.

The wizard basically pre-populates #next on your buttons based on '$form_info['order'], and then pushes that value into $form_state['redirect'] in its own submit handler, so you have complete control of which step is next. You could manually override $form_state['redirect'], but the wizard should be able to manage it for you.

If your step progression is basically linear but you only want to "skip ahead" based on the selection in step 1, this works fine as you can simply add all steps to $form_info['order'] in your page callback (or where you defines $form_info) and doing the next/back logic in your validation/submit handlers. The user will see all steps listed in the "trail" but may skip some depending on your conditional logic. (The back button also has #next set to say what it goes back to.)

If your step progression is truly branching and a fixed order including all steps would not make sense, I would recommend to hide the trail and re-implement it yourself using the logic which determines which steps go in which order.


top items rendered as  and remain clickable (give page refresh)

How are you getting those to save?
It should be route:<nolink>. Test that it works on a regular menu before trying the additional module to avoid confusion about what might be happening.


Why Manage_fields and Manage_display tab are not shown in content type?

There is unchecked permission of field. After checked it shows the tabs. Make sure two things to solve this problem.
1. Enable Field UI (field_ui) module
2. Make sure the field in permission is checked

  admin > people > permissions


How to update header text in hook_views_pre_render

Well the important thing is to narrow down the particular view display you want to affect. Then you can look at the header text later. I have the following similiar code ... you should be able to use views_pre_render fine, I don't use that here:

function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'migration_audits') {
    $drupal_nids = array();
    if (count($view->result)) {
      foreach ($view->result as $i => $node) {
        $drupal_nids []= $node->nid;
      }
    }
   $sql = " ... ";
   $result = db_query($sql, array(':drupal_nids' => $drupal_nids));
    $output = '';
    foreach ($result as $course) {
      #dpm($course);
      $title = html_entity_decode($course->course_title, ENT_COMPAT, 'UTF-8');
      $instructors = html_entity_decode($course->instructor, ENT_COMPAT, 'UTF-8');
      $output .= "
$course->quarter $course->year - $title Instructors:&nbsp;$instructors
";
    }

    $my_values = "
$output
";
    $view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values;
    $view->display['page']->handler->handlers['header']['area_1']->options['empty'] = 0;
  }
}

You can also do like $view->display[$view->current_display] usually as a safe none hard coded approach. Note that the global header regions are given names such as area_1, area_2 etc as a convention by Views. I also tell Views the area is now not empty.


By the time that a print $name is available, you are already in a template or other late stage theme item, correct?  This means the parts have already been passed through render methods to add all that html.

When I had a project that created pdf reports for download and printing, removing these items was important.  I added a helper function to my site module. (every one of my sites receives a site_[name].module, but you could add this to your template.php if you want to keep this all in the theme)

define('UNWANTED_REPORT_TAGS', 'span/h1/h2/h3/h4/div/strong');
/*
 * helper function for removing html from report contents
 * Strip only selcted tags in THEME_preprocess_node function below
 * strip defined constant tags if none given
 * Growth order of O(n) where n is the number of tags, so defaults to O(7)
 */
function module_strip_only($str, $tags = NULL, $keep = TRUE) {
  if ($tags == NULL) {
    // load the defaults
    $tags = explode('/', UNWANTED_REPORT_TAGS);
  }
  if (!is_array($tags)) {
    // we were passed a string, check format and parse
    $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
    if (end($tags) == '') {
      array_pop($tags);
    }
  }
  foreach ($tags as $tag) {
    // tag by tag, strip our given string
    if( $keep ) {
      $str = preg_replace('#</?' . $tag . '[^>]*>#is', '', $str);
    } else {
      // we want the usual text, drop tags and what they wrap
      $cleaning = TRUE;
      while( $cleaning ) {
        // regex probably doesnt work here
        $clipFrom = strpos( $str, '<' . $tag );
        $clipTo = strpos( $str, '</' . $tag , $clipFrom );
        $clipTo = strpos( $str, '>' , $clipTo ); // find end of closing tag
        $str = substr($str, 0, $clipFrom) . substr( $str, $clipTo );
        if( substr_count ( $str, '<'. $tag) < 1 ) {
          $cleaning = FALSE;
        }
      }
    }
  }
  return $str;
}

The function will need an appropriate name for you, of course.  Then in your template file your line would be <?php print html_strip_only($name); ?>

If you just want to strip all <> sets from the string, you can do that like this.  <?php print preg_replace('</?[^>]*>', '', $name); ?> and I am dont think that / needs escaped, but if it does then it would be \/.  The online test tools want it escaped.

$pattern = '/<\\/?[^>]*>/';
$replacement = '';
$subject = '
Updated: 1/14/2016

 Related businesses
';
echo preg_replace($pattern, $replacement, $subject, -1 );


Proper way to package translation files with a custom module?

potx itself isn't directly available as a Drupal 8 module, but it doesn't need to.

It also works as a drush extension and can be run on Drupal 8 code. Haven't tried it if providing a translations folder still works, but I think so.

So, still works pretty much the same as in Drupal 7.


Problem file to import not found or unreadable ../../variables/_colors.scss

Change gem 'sass-globbing' to gem 'sass-globbing', '1.1.0' in your Gemfile and then run bundle install


Is there an hook to modify programmatically the thumbnail shown from the video module?

you could just modify the template to show a different thumbnail for anonymous users. You can use the Theme Developer module to find the right template to modify.


Link url paths change from within the 'user' area

Modify your href from

and

to

and

Notice the slash. That means the path is relative to your base url instead of being relative to your current path.


How we can get custom field type which will bring custom data from custom table to use as a drop down

You might want to look at http://materializecss.com/badges.html#dropdown The have a pretty straight forward way of creating a dropdown menu, including code examples.

If it's for a certain Form ID you can use hook_form_FORM_ID_alter to specify which ID and alter it's HTML inside $form_state. If you don't know it's structure you can var_dump($form_state); first instead so you know what to alter.

P.S. also add the CSS of course: drupal_add_css(drupal_get_path('theme', 'custom') .'https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.css', 'theme', 'screen,projection', FALSE);


How to eliminate direct access to files in private directory?

The issue is that the other man that gets the link should get an Access denied right? (The rest seems to work.) This is not how if works unfortunately. Private files are only private if the user is explicitly denied access to them (as happens to women and anonymous users). Since any man is allowed access to that file (he can view it under certain circumstances), the system will serve him that file.

Files are served from this part of system_menu():

$items['system/files'] = array(
  'title' => 'File download',
  'page callback' => 'file_download',
  'page arguments' => array('private'),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);

Then file_download():

function file_download() {
  // Merge remainder of arguments from GET['q'], into relative file path.
  $args = func_get_args();
  $scheme = array_shift($args);
  $target = implode('/', $args);
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
    $headers = file_download_headers($uri);
    if (count($headers)) {
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

As you can see, Drupal serves an access denied in case there are no headers. So, you should make sure that file_download_headers() does not return any headers.

You can achieve this by implementing hook_file_download() in a custom module and have it return the value of -1 as described in it's documentation. This will however always deny the user access to the file. So within hook_file_download you will have to find some way to conditionally allow the user access to the file. It is entirely up to you how you want to implement this, but a suggestion is:

Lookup the file object, by loading it from the file_managed table by its path.
Lookup the node(s) that have this image attached.
Lookup if the current user visited the node within x minutes by querying the history table. If not, return -1.

This gives a general idea of how Drupal serves these files and what you can do to restrict access. If you run into any problems implementing this, feel free to open a new question and reference this one.

And on a sidenote, if you are trying to prevent user from leaking photo's. If I find a pretty girl, I can also save the image and email it to a friend. If you block that I send a screenshot. In these case he does not even need an account. People will always find a way to circumvent limitations. Is it worth the effort to block this?


image_style_create_derivative not resizing the image

image_style_create_derivative needs the style passed as array..,
so _ first you need to load the style or fake the array

  applying all image effects defined in $style['effects']

see: image_style_create_derivative

i usually use image_style_url like this (if taken from field), otherwise just pass the source.

        $field = field_view_field('node', $node, $field_name, reset($image), $arr_display);
        if ($img_style) {
          $uri = image_style_url($img_style, $field[0]['#item']['uri']);
        }
        else {
          $uri = file_create_url($field[0]['#item']['uri']);
        }


How do I localize menu items added to the Main menu by a views page?

If I understand your question correctly:

Go to Structure > Menu > List links
Assign the correct language to the link and then you can add a translation for the term.

One of your languages is to be set as the source language for translation. As far as I know a language neutral entity (menu, node, whatever) can not have a translated counterpart, because there is no source language for translation available.

Hope this helps.


New Drupal installation not working beyond front page (not accessing database)

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem, The remedy in that case is to delete the cookie in the browser where you have the problem, and try again. Otherwise read on for other typical reasons (options) ...

Option 1 - RewriteRule and RewriteBase

Check if you can use an URL containing ?q=user or ?q=admin. Refer to my answer to the question "7.26 /admin, /user not found on Localhost" (which is about RewriteRule) for more details on that.

In that answer there is a link to the question about "drupal /?q=user is working but /user not working", for which the accepted answer of that question provides more details about tuning RewriteBase in your .htaccess.

Option 2 - Admin option 'Clean URLs'

I you can use the ?q=adminURL, then try to navigate to /index.php?q=admin/config/search/clean-urls to check the current status of clean urls (if it is enabled or disabled). Make sure "clean urls" is enabled.

Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.

Option 3 - base_url

Make sure the value of "base_url" is set correctly (in your settings.php).

Option 4 - .htaccess file

Verify if the .htaccess file is present in the directory where Drupal resides (and/or that it is not incomplete or corrupt). If it is missing, then upload it. If needed copy it again from the "Drupal" archive file (.zip or .tar) from Drupal.org again, and just use that new .htaccess file.


How to let users choose to hide fields in their profile?

Create a checkbox field just below the field you want to hide on user profile page.
Now override the settings in template file.

Please follow the link allow users to choose whether certain profile fields are visible or hidden for detailed steps.

Also you can try out Profile2 Privacy module.

  This module extends Profile 2 by allowing administrators to create
  privacy levels as predefined groups or sets of profile fields on a per
  role basis. Users can then select from among the privacy levels to
  apply access control to their profile.


Not an answer per say; more of a critique of some of your assumptions with variables.

  If I'll use the variable api then on each block view I need to load
  the variables separately i.e. 5 variables load( ~5 database fetch
  queries)(if block no results is enabled) and 1 variable load(~1
  query)(if block no results is disabled for that block)

In actuality all variables get loaded on EVERY pageload with a single query, including cache_page hits (think anonymous users) unless your doing something special ($conf['page_cache_without_database'] = TRUE;, varnish, or boost). variable_initialize() get's called very early; dig though drupal_bootstrap() a little bit to see. So a variable get doesn't cost you a db query, but it's not a good idea to abuse the variables db table because the more data that's in there (KB), the slower Drupal gets.

Actual answer:
My personal preference is to use cache_get_multiple() if your looking at 100s of items to get; unfortunately it looks like _block_render_blocks() makes this hard to do; the function that calls hook_block_view_alter(). So in this case a cache_get would be the easiest way to go. Another option is a cache loader; all in one cid (harder to manage writes) or get all cid's for the enabled blocks block_page_build() or $blocks = drupal_static('block_list'); with drupal_static(). What's ideal depends on many factors, biggest one being how large (KB) is the cached data; if its small a loader & drupal_static() might be the fastest option. If you have a large amount of data then doing individual cache_get() call might be better due to the lower memory usage and not loading unused data. See https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7 for more details on caching.

Also be aware of cores built in block caching. Use it if at all possible. See https://www.drupal.org/project/blockcache_alter for ideas and usage.


Actually darol100 is right. Since images are not on your server you cannot compress them. But you are able to cache them localy with image cache.

See this article here
https://www.drupal.org/node/251009


How to print taxonomy terms field in node templates?

Yes, this will be used in all nodes with that field ! You could add a contenttype specific node.html.twig (see next point), or if you only want to add classes, do it in template_preprocess_node(&$variables), add classes to $variables['content']['field_tags'][x]['attributes']['class'][] = 'my-style', you can check there for the contenttype.
What are you rendering ? If you render the node's field, you'll only get the assigned terms ?! For custom node-specific theming you could use something like this in

node--type-your_contenttype.html.twig:

   {% for item in content.field_tags %}
      {% if item['#title'] %}
        {{ item['#title']  }}
      {% endif %}
    {% endfor %}

Also {{ item['#options'].entity.url() }} or {{ path('entity.taxonomy_term.canonical', {'taxonomy_term': item['#options'].entity.tid}) }} could be used to retrieve the URL.

Regarding your icons

Use tid or parent and name it like icon-34. Access it in twig like: item['#options'].entity.parent or item['#options'].entity.tid.

  But I would recommend the use of a preprocess function to add a
  key-value pair to each item array where you set the name. For example
  from a field you added to your taxonomy. You could then access it in twig like {{ item.key }}


A better way to do it is replacing the asset ID field with an entity reference field which refers to the other content type (Asset) and use view relations to get the relation. In short, create a relation between the content types, and you will be able to use view relations.

For advanced uses, you can take a look to the Relation module, which I don't recommend, in your case.


You can do this with the Rules module, which includes a Rules Scheduler submodule.  (Node One tutorial on Rules Scheduler)
You can use Fivestar for voting.  To hide the votes, you should be able to use Views.

These are very general suggestions but it sounds like you're in the very early stages of your planning; if you have specific questions, you're welcome to post those later.  Basically, you should be able to use existing, well-tested modules for what you're trying to do, although you may need to customize them from time to time to match your specific use case.  It's generally not worth your time to write modules from scratch, except as a learning exercise.


I suggest you use drupal_is_front_page() to check it is on front page or not. You can achieve it using code similar to the following.

function myrtheme_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/search-icon.png');
  if (drupal_is_front_page()) {
    $form['actions']['submit']['#attributes']['class'][] = 'fpage-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'fpage-search-box';
  }
  else {
    $form['actions']['submit']['#attributes']['class'][] = 'other-page-search-icon';
    $form['search_block_form']['#attributes']['class'][] = 'other-page-search-box';
  }
}


The best way to handle this is to implement hook_form_FORM_ID_alter for the user sign up and edit forms and append your own validator to check for spaces in the username field.

As for the length of a username, the minimum is 1 character and the maximum is 60 - as per the db schema.


How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?

seems like you use D6 since you mentioned Commons. I've only used Heartbeat in D7. Click on the "heartbeat streams" settings and you have an option for "Choose message types you want to deny from display". There you can select the ones you do NOT want to record. Repeat that for each of the streams.

Also, checkout the "heartbeat templates" for "add_node" and "edit_node", there is an option "Disable the message - Defines whether this message template is disabled from logging and viewing."


People Permission: View own unpublished content do not work

Drupal 7

  In Drupal 7, users are not allowed to view any unpublished content by
  default, not even content created by themselves. By enabling 'View own
  unpublished content', you grant users access to their own unpublished
  content.

  The only way to allow users access to all unpublished content in
  Drupal 7 (without using a contributed module), is to enable the
  permission 'Bypass content access control'. Use this permission with
  extreme caution as it has far more consequences than just allowing
  access to unpublished content. In combination with Organic Groups for
  example, this permission allows access to private group content
  regardless of whether the user is a group member.

https://drupal.org/node/1106606

On that page are some contributed modules to set permissions you need...


You can override tpl files defined in modules inside your active theme (under the templates directory). But Drupal will look for a file name using the defined theme key name and not the defined template file.

In your case, you should create a module-output.tpl.php file within your theme. Maybe a good practice to name your template file the same as your theme definition.


How to create a task which run at cron time and send emails to users?

Here is how I did without using any custom modules.

I implemented hook_cron like that:

function HOOK_cron() {
    // search for expiration date interval
    $result = db_query("SELECT my_date, uid, company_name, nid
            FROM my_table
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            LEFT JOIN ...
            WHERE my_date BETWEEN DATE(NOW( ) + INTERVAL 6 DAY ) AND DATE( NOW( ) + INTERVAL 20 DAY)")->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $product) {
        $module = 'MY_MODULE';
        $key = 'MY_KEY';

        $from = 'my_email@test.com';

        $user_account = user_load($product['uid']);
        $product_detail = node_load($product['nid']);

        $to_user_mail = $user_account->mail;

        // build the email
        $message = drupal_mail($module, $key, $to_user_mail, LANGUAGE_NONE, array(), $from, FALSE);

        //$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
        $message['headers']['Cc'] = 'cc_email@test.com';
        $message['headers']['Reply-To'] = 'reply_to_email@test.com';

        $message['subject'] = 'THE SUBJECT';

        $message['body'] = array();
        $message['body'][] = 'Dear ' . $user_account->name;
        $message['body'][] = '...';
        $message['body'][] = 'Regards,';
        $message['body'][] = 'YOUR NAME';

        // retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // format the message body.
        $message = $system->format($message);

        // send e-mail
        $message['result'] = $system->mail($message);
    }
}


Nodes appearing but when clicked "page not found"

I had this problem, it only affected certain nodes. When investigated in db all values corresponded between node and node revisions tables so I initially assumed it wasn't related to values in those tables.
Checked url_alias table and all seemed well there too, site is multilingual so checked the variables table for discrepancies between multilingual paths auto values for custom content types and all was also well. Rebuilding the menu router didn't help either. I already tried resetting all node access permissions as suggested here. Honestly I was just about out of ideas, then thankfully I came across this post :D
The problem had come from where i had imported some node content from a custom module i wrote to ingest nodes from xml (which worked fine) but since the import was done the user account which had done the import had been removed. This meant all the multilingual imported nodes were still linked to that, now non-existent user account's uid.
A simple sql query in phpmyadmin set all my nodes to be owned by admin (uid:1)

UPDATE node set uid = 1;
UPDATE node_revisions set uid = 1;

This fixed my perplexing issue. I propose a patch so that if a user account is removed Drupal optionally checks all nodes belonging to that user and updates them to uid: 1 so nodes added by a deleted user account aren't suddenly inaccessible to the rest of the site including uid 1 (admin).
This was frustrating as a sensible sort would naturally assume that uid 1 will always have view/edit access to any node content on the site regardless of if it is, disabled, enabled or added by some mugwump.
I wish you good Drupaling!


Creating commerce product display in rules with PHP results in error

On further investigation it seems that the product created by Rules (in the previous action) is not assigning a product_id in the first place. Therefore there is nothing to assign to the 'product display'.

(I still don't understand why this is happening but rather than change this question completely I will post a new question.)


Enabling a contributed module under certain path only

Well yes you can ... but you shouldn't you may want to think of the code quality of the custom module, because it should only be responsible for the exact functionality you require.

I say you can because yes:

//Enable.
$modules = ['custom_scarry_module'];
module_enable($modules, TRUE);

// Disable.
if (module_exists('custom_scarry_module')) {
  module_disable(['custom_scarry_module']);
}

But again perhaps rethink the "why" aka what Jaypan said.


This is done by the color module which is a part of Drupal core.

  The Color module allows users with the Administer site configuration permission to quickly and easily change the color scheme of themes that have been built to be compatible with it. In order for the color module to work, a theme must be specifically designed to use the color changing features.

Here's a great guide to integrate to the color module in Drupal 8.

Integrating the color module into your drupal 8 theme


How do I add an SQL query with  hook_views_query_alter()?

Using hook_query_views_alter is something you should do with care as it can very easily come back and bite you when you least expect it. Trust me, I have tried this on some occasions.

hook_query_views_alter is powerful as you can create any query you want, but it should be used like the name suggests, as an alteration. It's not meant to be used by creating a view with an arbitrary query and then completely create the actual query from scratch in the alter hook. This will lead to many confusing moments, like why does the view display something different than what I set up, and why doesn't it change when I change it.

The query from the View looks something like this:

SELECT nid, title, created FROM {node}
WHERE type IN ('provider') AND status = 0

Compared to

 SELECT content_id, COUNT(*) as count FROM {votingapi_vote}
 WHERE value_type = '%s'  AND value = 1
 GROUP BY content_id;

There are two ways to solve your problem, without having to sort to nasty hacks in the hook_views_query_alter function that will be hard to maintain, and probably will give you or the next developer problems down the road.

Use the node table and create a JOIN

The voting api has Views integration but doesn't support that you query the table with views, using it as the base table. It does however support that you create a join (relationship). Most likely you are voting on nodes. If that is the case you can create a base view from nodes and add in the votes as a relationship. See below SS of how to add the relationship and the fields needed.

SS http://tardis1.tinygrab.com/grabs/99f4a5fef7b5f963fa6a64f0be8ad451af21915caf.jpg
Add info to views about voting tables

With hook_views_data_alter, you can add the needed info about the voting tables to be able to query them directly. Views documentation has great examples of how this is done. Then you could create a view that queries the votes and via the Views interface create a query similar to what you posted.


How can I include some functions globally?

The Drupal 8 way to define helper methods is to put them in a class as static methods.

Example from core:

namespace Drupal\Component\Utility;
/**
 * Provides helper methods for byte conversions.
 */
class Bytes {

  const KILOBYTE = 1024;

  /**
   * Parses a given byte size.
   *
   * @param mixed $size
   *   An integer or string size expressed as a number of bytes with optional SI
   *   or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
   *
   * @return int
   *   An integer representation of the size in bytes.
   */
  public static function toInt($size) {
    // Remove the non-unit characters from the size.
    $unit = preg_replace('/[^bkmgtpezy]/i', '', $size);
    // Remove the non-numeric characters from the size.
    $size = preg_replace('/[^0-9\.]/', '', $size);
    if ($unit) {
      // Find the position of the unit in the ordered string which is the power
      // of magnitude to multiply a kilobyte by.
      return round($size * pow(self::KILOBYTE, stripos('bkmgtpezy', $unit[0])));
    }
    else {
      return round($size);
    }
  }

}

and use it in code:

$upload_max = Bytes::toInt(ini_get('upload_max_filesize'));


Take a look at the CDN module it helps you serve files from a different domain.
I'm using it myself on a drupal 6 site, and it works great.


How to make a thumbnail slideshow when hover over album cover?

Here are my suggestions. You will need to load both preview and  slideshow, and hide slideshow with css/jQuery. Then with jQuery show whole slideshow on hover.

Or, you could use jQuery load() or other jQuery ajax methods to load slideshow dinamically on-hover, If the page has lots of content.

In any case, you will need to include some custom jQuery scripts in your page.tpl.php (checking if $is_front is true, to include some javascript via drupal_add_js for example). This is type of approach i use.

For slideshows, you can use jQuery scripts (i use http://css-tricks.com/anythingslider-jquery-plugin/ and http://bxslider.com/ ).

If you are fond to php programming you can use content types and EntityFieldQuery to load elements in that slideshows.

If not, you could try and search for existing drupal modules to show slideshows like http://drupal.org/project/nivo_slider


Connecting to multiple databases of different type for form submission

In Drupal 6 you cannot use more than one database engine with Drupal's functions. If you are using MySQL as Drupal storage, to connect to PostgreSQL you need to directly call PDO:

try {
  $dbh = new PDO('pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass');
} catch (PDOException $e) {
  watchdog("your module name",
           "PDO error: %error",
           array("%error" => $e->getMessage() ),
           WATCHDOG_ERROR);
}

Then use your handler just as you would in any non-Drupal PHP code, preferably with prepared statements.


I think the easier and simpler solution would be to create a custom block from your custom module using hook_block_info and hook_block_view.
By using these hooks, your block will be listed in the block administration page - admin/structure/block.

<?php
    /*
     * Implementation of hook_block_info()
    */
    function mymodule_block_info() {
        $blocks['yourblock'] = array(
        'info' => t('Your Module Name'),
        'cache' => DRUPAL_NO_CACHE
        );
        return $blocks;
    }
    /*
     * Implementation of hook_block_view()
    */
    function mymodule_block_view($delta = '') {
        $block = array(); # Declare array

        switch ($delta) {
            case 'yourblock' :
                // Block View
                $block['subject'] = 'Your Block Title';
                $block['content'] = _mymodule_taxonomy_content();
            }
        }
        return $block;
    }
    /*
     * Create block content as you need
    */
    function _mymodule_taxonomy_content( ) {
        $result = $query = db_select('taxonomy_term_data', 't')
                            ->join('taxonomy_vocabulary', 'v', 't.vid = v.vid')
                            ->condition('v.machine_name', 'your_tag_machine_name')
                            ->orderBy('t.tid')
                            ->execute();
        $content = '';
        foreach ($result as $term) {
            // you now have $term['vid'], $term['name'], etc. here
            // loop and build conditions here to suit your need
            // Item 1
            // Item 2 & 3  [linked accordingly: taxonomy/term/2+3]
            // For example,
            // $content .= l($term['name'], 'taxonomy/term/'.$term['vid']);
            // This is up to you.
        }

        return $content;
    }


Additional Information pop up box next to a variation in drupal commerce

I was surprised that there wasn't a module that did this so I've created one.

It is only a sandbox project at the moment as I'm still waiting to get approved to create full projects.

Sandbox page

It can however be downloaded from here. You will then need to extract the .tar.gz to a .tar, and then extract that to a folder called "2240445-cbcb2b4" and then rename that folder to field_info_popup (Phew!).

I've tested it with all the core field types and seems to work fine but if you do find any bugs then they can be posted here.


Why is hook_update not fully taken into account?

It seems I was looking at the wrong place.
Once hook_update_8101 executed, I should have updated myEntityListBuilder.php to be consistent.
The other forms (canonical, add-form, edit-form) were effectively updated.


View with terms and if the're flagged or not on userpage

Views only has 2 means to restrict access to Views: via a role or via a permission. Neither can help here so you'll have to use some other means to restrict the route path.

One way to go about this is to use the Views Access Callback module which was built for the purpose of dynamically checking access to a View. Once enabled, any module can implement hook_views_access_callbacks() to define a custom callback that can be used for permission checks.

It should be pretty easy to define a simple callback that inspects the current path to see if it belongs to the current user:

/**
 * Implementation of hook_views_access_callbacks().
 */
function MYMODULE_views_access_callbacks() {
  return array(
    'MYMODULE_access_account_subpages' => t('Access Account Subpages'),
  );
}

/**
 * Check that the user is the owner of the subpage.
 */
function MYMODULE_access_account_subpages($account = NULL) {
  global $user;
  return (arg(0) == 'user' && $user->uid == arg(1));
}


How do I know when another contributed module deletes a block?

There is no hook fired in delete of block, as you can see in the list of block hooks here block.api.php.

There is a topic in Drupal forum here.

I think the best way to handle this is by hook_form_alter something like.

/**
 * Implements hook_form_alter().
 */
function YourModule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'block_custom_block_delete') {
    // You get all information here of the concerned block in $form.
  }
}


Views Data Export not showing data export display option in view

I had installed the Views Excel Export module first. I had to uninstall both modules and then reinstall them in the correct order: Views data export first and then Views Excel Export. This solved the issue for me!


First thing to do to see if the login is functioning is use drush uli, which will create a login link for user 1. If that works, after logging in, set your password to test123. Logout, then try to log in with that.

You can also set the password with drush, trying to edit the md5 hash etc is not reliable.

https://drushcommands.com/drush-8x/user/user-password/

This doesn't have anything to do with the files directory.

Another thing to do is check your settings file just to ensure you are talking to the right database. Also check the database to see if the user you are logging in as is not blocked (status).

If you had previously set cookie domain in the settings file, verify that the value is correct.


How to generate images for profile picture in Drupal 7?

I could achieve that by the Identicon module.

This module generates and displays identicon images in place of the user picture for users who do not have a picture.
The generated identicons are pixel style images. The number of pixel blocks that the images contain can be configured. You can choose whether the generation is based on the user's email address or the user id. If the generation is email-based, users will get a new image if they change their email address. On the other hand, they get the same image even if they cancel their account, and register again using the same email. If the generation is user id based, changing the email address will not change the identicon, but if the user account is cancelled, the user will not get the same image when they re-register.

Checkout the similar modules Gravatar and User Pic Kit


I just tried this module today when I saw your post, if you don't want the 'read more' to appear on a full content node display you could create a new display template and add the php path/read more html link on the template you created then choose it from the render mode of node in block settings.

But I'm a little curious, why did you not use views block instead? it's a lot easier, you could just put the read more link on the footer.


Need to use taxonomy term as url argument to filter a view but the term is attached to a node ref field

Configure the Taxonomy: Term argument to use one of the relationships that you have set up. I do not know why you have an additional Node: Nid argument. According to your description, it is not necessary. Remove it unless you have some other requirement that makes this argument necessary.

Setting up the view in a way that does not match the requirements should not result in a blank page. The usual techniques for debugging PHP applications can be applied to figure out what went wrong: Printing out variable values or (if you have Xdebug or the like installed) step-by-step execution.


Where to start on fixing a locations module not accurately displaying on a gmap with views

As we can see, pin is rendered at the good coordinates. So the bug is in the Country to coordinates relationship data. You need to look in your database and find a table with this data. Probably, to avoid name collisions, table will be prefixed with module name.

When you have it, just update it with coordinates of capital cities, for example from Wikipedia.


$path = drupal_get_path('module', 'fivestar');
  drupal_add_js($path . '/js/fivestar.js');
  drupal_add_css($path . '/css/fivestar.css');

  $rating = votingapi_select_single_result_value(array(
        'entity_id' => YOURENTITY_ID,
        'entity_type' => 'YOURENTITY_TYPE',
        'tag' => 'vote',
        'function' => 'average',
   ));
   $form['votes'] = array(
      '#markup' =>  theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')),
   );


Ho to add mixed multiple fields in a node

Have you looked into Field Collection module ?

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

It allows to combine multiple fields and treated as a single field.
Here is the doc.
Hope it helps.


Conditionally enable/disable #autocomplete from client side js

Ok I managed to achieve this after digging into misc/autocomplete.js

To disable the autocomplete you can do the following:

$('#edit-search').unbind('keydown keyup blur');
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete-aria-live').remove();
$('#[AUTOCOMPLETE-ELEMENT-ID]-autocomplete').removeClass('autocomplete-processed');

To enable the it again:

Drupal.behaviors.autocomplete.attach(document);

My js ended up as:..

// update search box text when search type is changed
$(SI_SEARCH.radio).change(function() {
  // get search type
  SI_SEARCH.search_type = $(this).val().trim();
  switch(SI_SEARCH.search_type) {
    case 'course' :
      // re-attach autocomplete
      Drupal.behaviors.autocomplete.attach(document);
      break;
    case 'university' :
      // disable autocomplete
      $(SI_SEARCH.search_form).next().removeClass('autocomplete-processed');
      $(SI_SEARCH.search_form).unbind('keydown keyup blur');
      $('#edit-search-autocomplete-aria-live').remove();
      break;
  }
})


How can I configure the User Protect module to avoid editing/deleting users with "edit users" permissions?

I had to do it one day and I did like that. But in my case the permission is edit user 1. The code simply remove the user from the list. Feel free to change as you want.

<?php
function mymodule_menu_alter(&$items) {
  $items['admin/user/permissions']['access callback'] = 'mymodule_user_access';
}

function mymodule_user_access($string, $account = NULL, $reset = FALSE) {
  if ($string == 'administer permissions' && user_access('edit user 1')) {
    return TRUE;
  } else {
    return FALSE;
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'mymodule_user_profile_form_validate';
}

function mymodule_user_profile_form_validate(&$form, &$form_state) {
  $account = $form_state['values']['_account'];
  if(!user_access('edit user 1') && $account->uid == 1) {
    form_set_error('category', t('You does not have right to edit this user.'));
  }
}

function mymodule_perm() {
  return array(
    'edit user 1',
  );
}

function mymodule_theme() {
  return array(
    'mymodule_user_admin_account' => array(
      'arguments' => array('form' => NULL),
    ),
  );
}

function mymodule_theme_registry_alter(&$theme_registry) {
  unset($theme_registry['user_admin_account']['file']);
  $theme_registry['user_admin_account']['function'] = 'theme_mymodule_user_admin_account';
  $theme_registry['user_admin_account']['include files'] = array();
  $theme_registry['user_admin_account']['theme path'] = drupal_get_path('module', 'mymodule');
  $theme_registry['user_admin_account']['theme paths'][] = drupal_get_path('module', 'mymodule');
}

function theme_mymodule_user_admin_account($form) {
  // Overview table:
  $header = array(
    theme('table_select_header_cell'),
    array('data' => t('Username'), 'field' => 'u.name'),
    array('data' => t('Status'), 'field' => 'u.status'),
    t('Roles'),
    array('data' => t('Member for'), 'field' => 'u.created', 'sort' => 'desc'),
    array('data' => t('Last access'), 'field' => 'u.access'),
    t('Operations')
  );

  $output = drupal_render($form['options']);
  if (isset($form['name']) && is_array($form['name'])) {
    foreach (element_children($form['name']) as $key) {
      if(!user_access('edit user 1') && $key == 1) {
        unset($form['accounts'][$key]);
        unset($form['name'][$key]);
        unset($form['status'][$key]);
        unset($form['roles'][$key]);
        unset($form['member_for'][$key]);
        unset($form['last_access'][$key]);
        unset($form['operations'][$key]);
      }

      $rows[] = array(
        drupal_render($form['accounts'][$key]),
        drupal_render($form['name'][$key]),
        drupal_render($form['status'][$key]),
        drupal_render($form['roles'][$key]),
        drupal_render($form['member_for'][$key]),
        drupal_render($form['last_access'][$key]),
        drupal_render($form['operations'][$key]),
      );
    }
  }
  else {
    $rows[] = array(array('data' => t('No users available.'), 'colspan' => '7'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}


You can use hook_commerce_checkout_router() to skip Commerce Checkout pages.

See the advanced example here: Skipping a Commerce Checkout page in the checkout workflow

/**
 * Implements hook_commerce_checkout_router().
 *
 * Skip the registration checkout page unless required.
 */
function MYMODULE_commerce_checkout_router($order, $checkout_page) {
  global $user;

  if ($checkout_page['page_id'] == 'registration' && $user->uid) {
    $registration_required = FALSE;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      if ($line_item->line_item_label == 'Conference Attendee') {
        $registration_required = TRUE;
        break;
      }
    }
    if (!$registration_required) {
      $order = commerce_order_status_update($order, 'checkout_' . $checkout_page['next_page'], FALSE, TRUE, t('Conference Registration was skipped - not required for these products.'));
      drupal_goto('checkout/' . $order->order_id . '/' . $checkout_page['next_page']);
    }
  }
}


Drupal, how to display only specific content

If you have used Blog modules to create you blog content type, you would be able to use the default View from blog.

Otherwise you can create your own view and add Filter Criteria: Type.
You can do this using the module Views You can give the path blog to the view.

  You need Views if

  You like the default front page view, but you find you want to sort    it differently.
  You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain    type.
  You like the idea of the 'article' module, but it doesn't display    articles the way you like.
  You want a way to display a block with the 5 most recent posts of    some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


How to make exposed filters more readable in the URL?

There's no easy way to do that .. views better_exposed_filters is quite nice, but does not provide clean urls. Drupal 7 had query_parameters_to_url, for Drupal 8 they link to a sandbox! project ... This may be a starting point for you.
There may be a simpler approach here: Redirect based on query string using a redirect event subscriber:
<?php
    static function getSubscribedEvents()
    {
        $events[KernelEvents::REQUEST][] = array('Redirect', 20);
        return $events;
    }

So you could provide at least clean urls to "somewhere".


How do I make the custom module "Configure" option appear on the module list?

It's done in the module's ".info" file, using the "configure" key.

name = Example module
description = Gives an example of a module.
core = 7.x
package = Views
dependencies[] = views
dependencies[] = panels
files[] = example.test
configure = admin/config/content/example


Why this code cannot delete the rows that i want?

The DeleteQuery class doesn't have orderBy or range functions, so I would imagine you would need to write your own DELETE with SELECT subquery. An example from Stack Overflow


Firefox/IE not displaying CSS with Drupal website

It's more like a CSS issue. Your CSS has to be more organize and standard cross browsers. Try not to use "!important", because you don't want to over-use it as you will end up causing headaches down when maintaining the site.

Here are some example you can fix.
Under file "blocks.css" line 303.

.pane-block-4, .pane-block-5, .pane-upcoming-events, .pane-block-6 {
  width: 31.25% !important;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

Since there are 3 classes on each "div"(panel-pane pane-block pane-block-4), you should use something like this instead

#mini-panel-front_blocks .panel-pan {
  width: 31.25%;
  min-height: 500px;
  float: left;
  overflow: hidden;
  position: relative;
}

Hope this help


Site not working after the database update

Add "doctrine/common":">2.8" under conflict in your composer file and then run composer update.

"conflict": {
    "drupal/drupal": "*",
    "doctrine/common":">2.8"
},

See issue: https://www.drupal.org/project/drupal/issues/2986725


Using Drupal Commons, how can I create a node of a specific content type on group creation?

Here's the solution:

Obviously you need to download and install Rules, then:

Add an event:

After saving new content of type Group

2
. Add conditions:

Any conditions you want here..

3.Add Actions:

a) Create a new entity

Parameter: Entity type: Node, Content type: ContentTypeYouWantToCreate, Title: YourTitle, Author: TheAuthor
Provides variables: Created entity (entity_created)

b) Save entity

Parameter: Entity: [entity-created], Force saving immediately: true

c) Add entity to group

Parameter: Entity: [entity-created], Group: [node]

your content type should now be created when you create a new group - it will also be added to the newly created group.

Done!


The first thing you will want to do is disable (and uninstall) the feature module.  That doesn't always remove everything the module initially created.  Once that feature module is uninstalled however you can go in and manually delete the content type and anything else that was left on the site.

Some additional detail can be found at this other question.  It provides an example of how the feature module can add an uninstall hook to unlock the content type. Looking at the query used in that example you should be able to run the query manually and unlock the offending content type.


Deploying content updates from staging server to live server

UUID and UUID Features allows you to export a Node to a Feature, which could be just what you're after, means no need to mess with the database.


How to delete all nodes of a given content type?

There is a module for that (TM).

See Bulk Delete.

That will use the Batch API to delete the nodes to avoid timeout or memory issues when deleting thousands of nodes with a single call to node_delete_multiple().

Bulk Delete is an abandoned module.  See for alternatives:

Views Bulk Operations
Delete All


How to I change the blogger's name button from all lower case to proper case in Omega 3.1 subtheme?

You could always use mb-convert-case, or you could just target it with css and use text-transform: capitalize.


Is this the proper way to alter a path defined in code by another module?

No, that's not the right way. You are actually looking for aliases. They are provided by the Path module that is integrated in core.

It's possible to do it the way you propose, but it comes with possible side effects and is a little to much for what you want.


the javascript for dragging and dropping not loading - drupal 7

I solved this by installing http://www.drupal.org/project/speedy

it minifies core javascript files


I'm not sure if i can help you out with out a screenshot cause i'm also new to Drupal. But my guess is the filters work in a different way from what you think. It might be something like this...

  Type1 AND (TAX2 OR xxx OR yyy .. etc.)

Hope this helps. Cheers!


Updating the CKeditor library in Drupal after Version 7.14?

Yes.

Libraries should not be store in module directories for the reason that it makes it harder to update things.

Best practice is to install the Libraries API module and put the library in sites/all/libraries (or an equivalent libraries directory if you're using an install profile or something).

CKEditor and a lot of other modules integrate with the libraries API module.

The CDN option that is referred to in your quoted text is different though. In that case you don't need to have the CKEditor plugin anywhere in your website files.
Instead the module will use a copy of the library from the CDN.

It's possible there could be performance implications from not using a local version but I haven't actually tested that.


Ask users what menu they want while drupal is being installed

Yes it's possible, using hook_install_tasks().

You can use this hook to create a form that is displayed to your users during the installation process; it can be a standard Drupal form and you can add as many items of content/menu links as you want in the submission function.

Bear in mind the hook and forms your implement will need to go in the .profile file, not the .install file, or they won't work.


How to teach PhpStorm to recognise drupal {table} SQL syntax?

In PhpStorm Preferences > Tools > Database > User Parameters:

Check "Enable in string literals with SQL injection"
Add \{\w+\} to Parameter Patterns.

You may also want to modify the line with %\w+ to be allowed for language php for placeholders like %d. See screenshot and also JetBrain's PhpStorm blog post: Database Language Injection Configuration.


About drupal_realpath() and PDF Formatter

To get the web-accessible URL for a local file, you should use file_create_url().

$html = shell_exec('pdftohtml -q -stdout '.escapeshellarg(file_create_url($item['uri'])));

Using it would probably not work, anyway: I think that pdftohtml first tries to access the local file to see if it is a PDF file, and it outputs what you see when the file is an image. I doubt that pdftohtml uses <img /> for every file that is not a PDF file or that is not able to access.
In your case, file_create_url('public://imgtest.jpg') would return $base_url/sites/default/files/imgtest.jpg where $base_url is the content of the global $base_url, which includes the http:// or https:// part. While that would be perfect to be used for the <img /> tag, it could not be used as filename, since pdftohtml is not probably able to handle a filename starting with http:// or https://. (In other words, it expects the filename of a local file.)

It is probably easier to check if the file is an image, and output the <img> tag using the output of file_create_url() as image URL in that case, or the output from pdftohtml when it is not an image.


Cannot use object of type stdClass as array error in node save

Assuming this is Drupal 7 field_locationmap is an array so your assignment should look something like this:

$location->field_locationmap['und'][0]['geom']['lat']

Also make sure that['geom']['lat'] is the correct structure for that value (i.e it is an array with two keys)
P.S. Consider using $location->language instead of 'und' in case you support multiple languages.


Update to Search API 1.18 causes HTML to be displayed as plaintext

check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. < and & respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup.
filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.

In other words, filter_xss() takes care of security, while not plain-texting HTML.

I propose you to patch the Search API function with 'filter_xss' as a callback instead of 'check_plain', create an issue on drupal.org and explan that case.


Change Text of Create an Account in Login Block

The above mentioned problem can be easily solved by using hook_form_alter hook_form_alterhook_form_alter(&$form, &$form_state, $form_id) . You can use that function in our template.php of your custom theme .

In template.php write..

function custom_theme_form_alter(&$form, &$form_state, $form_id){
  if( $form['form_id']['#value'] === 'user_register_form'){// For registration form on 'user/register' page
    $form['actions']['submit']['#prefix'] = '
';
    $form['actions']['submit']['#value'] = '--your text--';
    $form['actions']['submit']['#suffix'] = '
';
  }
  if( $form['#id'] === 'user-login-form' ){  // For login block that comes with drupal core blocks and can be assigned to any region.
    $form['links']['#markup'] = '

--your text--

Request new password

';
  }
}

This will change your text from 'Create a new account' to your custom text. And don't forget to clear the cache :).

Reply on this thread if you still find some problem.


Entity Reference get nodes based on tags

It can't be done with Entity Reference out of the box, your only option is to install another module or write some custom code (you would need to create a custom widget that searched additional fields on the entity if you went down the custom code route).

One possibility, which seems to be in keeping with your approach, is the Entity Reference View Widget module.  This module allows you to search on any field.  There is a little bit of additional setup since you have to create a view containing your Article nodes, but it means that you can specify your taxonomy as a field that can be filtered.


Alter main menu button text and URL path depending on OG Role

You can do this using the access callback of the items array in hook_menu_alter. The implementation of the user menu gives a good example.
To make it work with Organic groups, you could declare an access callback function using og_is_member or og_user_access:

function MY_MODULE_menu_alter(&$items) {
  $items['MY/PATH'] = array(
    'access callback' => 'MY_MODULE_custom_menu_access_callback',
    // Assuming your group is a node and the menu appears on the nodes
    // page (/node/[nid]), then array(1) would pass the node ID to your
    // function, which in this case acts as a group ID.
    'access arguments' => array(1),
    // etc...
  );
    return $items;
}
function MY_MODULE_custom_menu_access_callback($gid) {
  return og_is_member('node', $gid);
}

Where MY/PATH would be the path to the entity type representing the group. If you are using a node as a group, this would be node/%. As 'access arguments' we use the arg function. 0 would be node and 1 would be the node ID of the node.


Remember webform textfield for next entry

This is the use case of the Webform Field Repeat module:

  The Webform Field Repeat module enables the webform to remember
  selected field entries from current submission for up to an hour. It
  uses the $_SESSION to do so. If the session is active, the form will
  be populated with selected entries from remembered submission when
  opened again.

  The fields can be selected on Webform >> Form settings for each
  individual webform. Once the fields has been selected the end users
  will see a check box at the bottom of the form that they can check to
  have the form populated when they open the form for a new submission.
  This module depends on Webform module.


Try to installed missed library by the following comment on the root of your drupal website :

composer require drupal/image_effects:^2


Using webform-form-[nid].tpl.php to change default template

Have you made a clear cache in admin/config/development/performance?

Or have you looked if in the template there is a error in the code? To verify this you can try to copy all code of "webform-form.tpl.php" in your "webform-form-23.tpl.php" and at the top of the code, before the first TEST!!! , refresh the cache and look if TEST!!! is displayed. If you display TEST!!! in your previous code there is an error.


Yes you can do that.

Go to the views listing page (admin/structure/views).
In the Operations column of the view you want to reset, click the Revert operation.
Confirm by clicking the Revert button.


It would be best to create a page/block (basically just a different views display) to achieve that.

The constraints that you have i.e. Previous and Related can only find a practical application if your videos belong to the same category.

If I am getting the question right what you are better off doing is creating another block which displays all videos irrespective of the categories.


I found an answer to my question. Its all in the view settings.

First, I changed the format from unsorted list of items/groups to Geolocation - CommonMap and modified its settings. This is to display all groups in a single map(A simple solution that I should have noticed at first).

Second, I added all fields needed to be displayed in a group in the map.

Lastly, I added desired filter(this is to search for a group).


How can i authenticate a user without using Drupal functions?

If you look in the includes/password.inc file in your drupal 7 installation, you can see how drupal 7 hashes up the password and then code that up separately or just include that file in your other script.  A quick tutorial on this can also be found here.


How can I programmatically place blocks?

I was able to accomplish what I wanted using theme config, as described in How to assign blocks to particular regions on theme install? . This solution works for me, because my site will only ever use one (custom) theme, and I don't mind configuring all blocks this way.

I created a config file (this one is for a language switcher, provided by language module) and put it in MYTHEME/config/install/block.block.MYTHEME_BLOCKNAME.yml. It's just what you would export from configuration management, without uuid.

langcode: en
status: true
dependencies:
  module:
    - language
  theme:
    - MYTHEME
id: MYTHEME_BLOCKNAME
theme: MYTHEME
region: header
weight: -6
provider: null
plugin: 'language_block:language_interface'
settings:
  id: 'language_block:language_interface'
  label: 'Language switcher'
  provider: language
  label_display: '0'
visibility: {  }


Personally, I would store the file as it was uploaded, and then render it as a PDF for users when they download it.  Your spec may say PDF now, but you want to have the flexibility should things change in the future.

Is this a good idea?  That is a tough question, and really depends on the exact scenario.  Personally, I would push back on this requirement.  Format conversion can tax system resources, and I don't think you can really constrain the .doc and .xls formats enough, like you can with images, to be something reasonable.

Tools?  The Printer, email and PDF versions module has a list of of the PHP-based PDF modules:

dompdf
mPDF
TCPDF
wkhtmltopdf

I am unaware if any of these will support .doc or .xls formats.  I have used Ghostscript to convert images to PDF, and I am pretty sure it has some support for .doc.  I am unaware of any Drupal-ready solution for this, though.

As for security implications, the scenario "makes my spidey sense tingle", but I can't point to anything in particular.  I don't think you would have any problems with any of the malicious payloads in .doc and .xls files that normally affect Windows machines.  However, if you go with a solution like GS, you will have to use a popen() or something similar, so you run the risk of an exploit there.


Add conditional stylesheet CSS for internet explorer only

I Found the solution in the comments on the drupal documentation for drupal_add_css():

drupal_add_css(
  path_to_theme() . '/less/ie.less',
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

Using this resulted in the LESS file being compiled by the LESS pre-processor, and the style was included within <!--[if lte IE 9]> comment tags.


How to set field value in custom webform submit handler?

Only now did I realize there is not only a submitForm method but also a presave method. I therefore changed my code as follows which is woking fine for me:
class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($webform_submission);
  }

  /**
   * @param $webform_submission
   *
   * Manipulate data.
   *
   */
  private function submitMyFieldData($webform_submission) {
    $data = $webform_submission->getData();

    // to get a value from a form field
    $form_value = $data['my_field_machinename'];

    // to set the value of a form field
    $data['my_field_machinename'] = $form_value + 1;

    $webform_submission->setData($data);

  }


Are there two identical .htaccess files in a Drupal installation?

There are actually 1+n .htaccess files in any given Drupal directory, where n is the number of working sites:

In the Drupal root
One for each site's files directory

The contents of the files directory .htaccess file is the following:

SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
Options None
Options +FollowSymLinks

This was done as part of a security update to Drupal 4.6.x and 4.7.x, and has been there ever since. The relevant security advisory, SA-2006-006, explains why:

  Certain -- alas, typical -- configurations of Apache allows execution of carefully named arbitrary scripts in the files directory. Drupal now will attempt to automatically create a .htaccess file in your "files" directory to protect you. This line references SA_2006_006 to lead Apache administrators to this announcement.

Thus it's not advised that you replace or remove that file.


How do I generate PDF of HTML in a custom module?

There is quite a bit more involved in integrating Drupal with the mPDF library than the code snippet you show.

As often with Drupal, there is a module for that. It is named PDF using mPDF, and this is what it will do:

  This module is used for Conversion of HTML pages to PDF documents using mPDF PHP Library. It allows you to generate a pdf document of any node.

Make sure you follow the instructions in the README.txt files carefully. You need to place the mPDF library in the right directory, and install the Libraries API, for it to work correctly.


Drupal views filter with latest month with content

Try to create a date filter using the create date and set the granularity to month. The setting for the relative date field should be set to be equal to now.


Call to undefined function t() in an Unit test

You should not be using t() inside classes. The string translation trait should be included instead (if it is not already part of a parent class). Then you will use:

$this->t()

Then you can use the answer I provided here as to how to do unit tests with string translation trait: How to unit test a class which uses a trait?


Node Langauge needs to be undefinde by default

In the "Structure" > "Content types" editing page (/admin/structure/types/manage/article — replace article to your pin content-type), you can switch on (=tick) Set current language as default for new content in the Extended language options sub-section in the Multilingual settings tab (near the bottom-left).  Then when a user visiting your website is in the English mode and creates a new node (pin?), the language of the node will be English.

It is not Language neutral, but that may be what you can accept?


Site keeps redirecting to core/install.php

You've got a problem with your installation. You have two copies of core, as can be seen from the two paths in the error message:

/var/www/html/web/core/includes/bootstrap.inc

/var/www/html/vendor/drupal/core/includes/bootstrap.inc

You should not have a copy of core in your vendor directory. That needs to be removed, though it may also break your site. Make sure to clear the registry drush cr or equivalent after removing that directory.


How to do autocomplete in a Bootstrap modal form?

Drupal's JS is powered by behaviors. If you find yourself in a situation where you need to poke the system into life, you can manually attach the behaviors like so:

Drupal.attachBehaviors();


How can I show the root taxonomy term in a view field in Drupal 7?

In the 'Fields' section of the view add your taxonomy field (Location). Select the Formatter that you want and then in the settings of the field, in the fieldset 'Multiple field settings' change the 'Display' option from 'all' to '1'.

Enjoy


How to give a roll only access to add a certain content type?

The Permission View published content is very important, without the users of that role won't be able to see Published content. What do you mean by "cannot do anything in the system anymore"?

Do you want that Role to be able to create new nodes of that type, but not to be able to View those nodes once they're created?

You should look into the Editorial Workflow, and Content Access module.


How to get a backtrace in Drupal, without problems like out-of-memory when huge objects are in the trace?

I find this useful as a less memory intensive Drupal-friendly way to backtrace PHP as a one-off code snippet to temporarily drop into a troublesome location without installing modules or server-side tools:

  $trace = debug_backtrace();
  $backtrace_lite = array();
  foreach( $trace as $call ) {
    $backtrace_lite[] = $call['function']."    ".$call['file']."    line ".$call['line'];
  }
  debug( $backtrace_lite, "TRACE", true );

It gets the backtrace into Drupal's debugging system, but strips it down to the essentials to avoid failures when massive objects are involved.

For handy reference, the other keys within each row of the debug_backtrace() object are:

class
object
type
args

Note - this answer was first posted in the now-deleted too-broad question How do I debug Drupal?


The error message you have provided indicates that you do not have a reverse PTR record in your DNS for the IP address you are using, specifically in this case for IPv6.  When you look a specific IP address up it should resolve back to a known hostname which identifies it in DNS.  Some mailservers and systems will not accept email from hosts without a valid PTR record.  I would imagine that in your case you have some IPv6 records in place, and that your server is connecting to Google's SMTP servers over IPv6 but that you do not have the correct records in place.  The error message provides a link to https://support.google.com/mail/?p=IPv6AuthError which should tell you more about this error.

You should also make sure that you have correctly setup SPF for the domain that is used as the from address in your emails, you may need to add an SPF record, or update the existing one for the domain so that your webserver is trusted to send email on behalf of your domain.


Increase memory limit doesn't help in Fatal error: Allowed memory size of .../modules/views/views.module on line 416

I've also been beating my head against a wall the last while with Drupal memory issues. Here's my collected knowledge on the topic:

1. Views (can) use a lot of memory

I love me some Views (and Panels and CTools and everything merlinofchaos touches with his mighty, mighty fingers), but it's possible to create configurations with multiple relationships that use a lot of memory. If you disable your Views and the memory issue goes away, it's likely a badly-constructed View causing the issue.

What to do if it is a View, and you really need that View to work? Try putting it into code (Via Bulk Exporter or Features; see below. I've hand-coded Views-like functionality in order to improve performance with very little success) for a start. Another thought is to redo the View a different way -- if ultimately what you're getting at is taxonomy terms, make sure the type of View is a Taxonomy View when creating it; don't create a Content View that uses relationships to get at taxonomy terms.

Could also be worth mentioning here that Panels also supposedly uses a lot of memory -- I haven't really benchmarked it so can't confirm this.

2. Moving stuff from database into code is a very good practice

It took me several Drupal sites to realize this, but keeping everything that's created via a UI in the database (Views and Panels configurations especially) is a Drupal worst practice. Why? It increases load on the database and cannot be version controlled. The first point is particularly problematic in terms of memory usage -- instead of just loading the content from the View from database, the site must also load the view components itself. This is exacerbated by how Drupal uses tables: by abstracting everything to the nth degree, each bit of Drupal's functionality uses a new table, resulting in some requests joining a bajillion tables together. This gives Computer Science people hernias (caveat: link is silly), but can't really be avoided with a piece of software as modular and user-friendly as Drupal is.

The solution? Use Bulk Exporter (Included with CTools) or Features to package up bits of code currently residing in the database as module code.

3. Themes can also eat memory

Does your theme have a lot of template files (I.e., files in themename/templates/)? If so, memory is consumed each time one of those files is loaded. If you're creating templates specifically to suppress bits of Drupal from  being displayed, try either:

Changing permissions so that bit doesn't show up for specific non-admin user roles.
Using CSS to hide elements.

The first choice is obviously what you want to do for stuff affecting security -- you don't want to use CSS to hide an "edit" button for certain users, only to have them then unhide it via Firebug or whatever.

4. Don't go overboard on contrib modules

While sometimes a site needs a lot of contrib modules, don't go overboard. Each enabled (note: enabled. Disabled modules don't use any memory) module uses memory. This is a bit obvious, but worth noting regardless.

5. The VPS is (sometimes) a lie

In my experience, some unscrupulous hosting companies love trying to push Drupal sites to VPS servers -- they're more expensive and it frees up shared hosting space for ever-more WordPress websites. The situation is worsened by the fact that webhosts often don't advertise (Or even willingly tell you if asked) what the upper memory limit is for shared hosting.

Alas, often if a site isn't under heavy traffic and is still crashing, the issue likely has something more to do with Drupal's configuration than anything else. Pushing a user to VPS just muddies the waters and adds more variables to deal with (Is it the webserver config? PHP config? VPS guest config? VPS host config, even?).

6. When all else fails, clone to localhost and beat it with a stick

This is a big reason why people use the dev-staging-production methodology with version control -- when all else fails, you can do a DB dump, git clone the site to a local testing server and then royally mess up the site on the testing server without worrying about actually breaking anything on the production server.

For memory issues, this generally means disabling modules one by one until the one causing the issue is exposed. It can also point to webhost-related issues -- if the site runs perfectly fine on a local install with memory set to something reasonable like 128MB, then you know your webhost is on crack.

tl;dr

My gut is that it's chain_menu_access that's causing the issue. Try disabling that and clearing the cache, see if it works.

I'll also add to this answer as I think of other things to try...


Page Manager Error: The requested page "/xxxx" could not be found

Are you using the stable version of the ctools and panels module, this error doesn't seems to be in the issue queue of the respective modules.

As @David as mentioned the problem could be of selection rule or the access rule.

Have a look at the use tutorial for creating the page with page manager: http://nodeone.se/en/learn-page-manager-part-1-overview

Also check the documentation of the page manager module: https://drupal.org/node/1862908


What are the best practices to manage site mirrors with Drupal?

It always a big deal with Drupal to have a Staging and Production environment. Because you can't just make a simple mirror.

Because you are going to do Site Building in your Staging area, you can't export the database and import it in production, because of user content generation. The inverse its also a problem, as you have done some Site Building.

Of corse you have some tools like Selinium IDE that helps you to save your configuration and that you can use after in production.

The others solution its to move everything, configuration I mean, into files. You've couples of modules that can helps you. First of all, Features that allow you export configurations as feature and you can enable it easily once on production.

For variable and blocks, you've Strongarm and Boxes. Finally the hook_update_N will help you to archive the last goals.

For the code part of your project, I guess nothing is better than versioning, like Subversion or Git (goes for Git as it's use by drupal.org). And for the workflow model I can just advice this one that works pretty well in our organization.


Progress bar in drupal admin area for long running scripts

Grab a copy of Examples and checkout the batch_example module.

It's got several code examples for various scenarios using the batch API, which Drupal uses internally to produce pages with progress bars (like the upgrade check page for example). The module is very well commented, and it should give you everything you need to get started.


How do I add CSS body classes for logged-in and logged-out users?

Ok I think I figured this out as in Drupal 8 it uses TWIG to print the body classes for content types or users we need.

In the html.html.twig

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.hasPermission('administer')  ? 'isAdmin',
    user.getRoles()|join(' role_')
  ]
%}

Then make sure this line is added to the body classes

   <body{{ attributes.addClass(body_classes) }}>

So if the user is logged out we can use the role class to identify them.

   .anonymous { }

Or we can use the :not Css selector
:not

   :not.user-logged-in {}


How to import title, description and image from website

The manual way to do it is to create a custom module that uses drupal_http_request to download the remote URL, then parse through the resulting data to pull out any images, a summary, and the contents of the title tag.

This is a lot harder than it sounds because manually parsing HTML is actually pretty tricky. If you must take this approach, try using simplexml or a library that tries to simplify things for you.

A better approach might be just porting the Drupal 6 module yourself - it's probably less work and you could contribute your code back and possibly get patches from other contributors.


Views Infinite Scroll and back button issue

Try to use GD Infinite Scroll module.

  Provide an administration to use the infinite scroll jQuery plugin :
  auto-pager on custom pages using pager. You can use autoload on scroll
  or a load more button. This module is designed to works on any page
  with pagination (views, search results, heavily customised page, ...)


Post update hook fails to run via Drush, but works via update.php

For anyone else who runs into this, make sure that the post-update hooks are defined in a MODULE_NAME.post_update.php file. It seems as though update.php will happily invoke post-update hooks defined in the MODULE_NAME.install file, while Drush will not.


how to create template suggestion for image like image--NODE-TYPE--VIEW-MODE

In the hook_theme_suggestions_HOOK_alter the $variables contain only informations about the theme of entity in this case theme image:
From documentation:

array $variables: An array of variables passed to the theme hook. Note that this hook is invoked before any preprocessing.

if you look at image_theme you can find all variables passed uri, title ...
So to access node related info you can use route params like the following.
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  $suggestions [] = "image__" . $node->bundle();
}

Note: you can't access to View mode in this hook because it's not in the $variables and also the current view mode is not stored in the node object
Take a look at this issue Make the current view mode available on the node object


How to make image alternative text as required be more web accessibility?

I found one of the solution by using EIM module. I understand this is not the best solution but this module able to enable Alt field required on image field by content type.

---- updated info on Aug. 22nd 2014 @ 11:12pm
The EIM module adds checkboxes for the fields of image editing forms by content type. Including "Alt field required" and "Title field required". See below screenshot for details.


Entity 'changed' column doesn't change upon save

Okey I found the final reason:

ChangedItem.php

  $original = $entity->original;
      $langcode = $entity->language()->getId();
      if (!$entity->isNew() && $original->hasTranslation($langcode)) {
        $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value;
        if ($this->value == $original_value && $entity->hasTranslationChanges()) {
         $this->value = REQUEST_TIME;
        }
      }

The conclusion:

In Drupal 8 if you save the same entity TWICE within 1 second (for whatever reason), you won't able to save your own changed time BUT it will be the REQUEST_TIME instead... wtf? ...


Multiple sites, each is either one page (with multiple editable content) or has multiple pages

If you don't need multiple domains (or sub-domains for that matter) you could probably get away with using a custom module to simply switch themes under a given criteria (URI path, user role, etc).

How do I change a theme based on the URL?


The Search API module shows a two-words taxonomy term as two separated words, in its widget

Based on your screenshots, consider using the "Taxonomy Term" type for the field indexes. This should remedy your issue.

By using Full Text, you're breaking up the taxonomy term names into searchable words. Use either the default taxonomy term value, or try using the "All Parent Terms" field.


How add CVV's custom validation before order review in Ubercart

You can create a custom validation function in your module and name it whatever you like for example 'custom_validation_function'. and in the same module add this validation function to the form's validation list by using form_alter.

function <module_name>_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == '<ubercart_form_id>') {
    $form['#validate'][] = 'custom_validation_function';
  }
}


Replace default words in exposed filters

I have tried to resolve from backend/server side, but without success, so I have reviewed a way using Jquery (client side), while an backend alternative is achieved:

<script>
$("#here-field-name option[value='All']").html("Anytext");
</script>

Also, here is alternatives from backend perspective, maybe are useful for you how to default value to select list CCK with form_alter

I hope information be useful.


Multiple versions of the same menu, based on associated term?

I've done this just recently by implementing a single menu that shows different links depending on the context (in your case the context is a portal). The one menu will have all the links for all portals, and is set to rebuild itself on each context containing the relevant links for that context. You can do this as follows.

Implement hook_node_access_records() and hook_node_grants() to create viewing access records on the nodes that only allows for them to be viewed on the portal to which they belong.
Alter the canonical route for nodes to provide a custom access callback. This access callback will include a check on whether the user has viewing access to the node. This will ensure that nodes only show up in the menu when on the portal to which they belong.
Create a custom cache context for your portal, so that the menu can be set to vary by portal.
Set your menu block to have the portal cache context, so that the menu is rebuilt for each portal, showing the correct menu items for the given portal.

1) Implement node grants

Node grants involve two hooks, hook_node_access_records() and hook_node_grants().

First, hook_node_access_records(). This hook is called upon node save. In it you perform calculations to determine upon which portals the node will be accessible. For your setup, you will set a record for each portal the node can be accessed at. Example:

function hook_node_access_records(NodeInterface $node) {
  $grants = [];

  // A grant needs to be added for each portal on which the node should be accessible.
  $grants[] = [
    // This will always be the same.
    'realm' => 'portal',
    // This will be the identifier of the portal.
    'gid' => 'portal_1,
    'grant_view' => 1
    'grant_update' => 0,
    'grant_delete' => 0,
  ];

  return $grants;
}

How you get the GID (the portal ID) of the node will depend on how your system is set up. It sounds like your portals are set up using taxonomy terms. If that's the case, in hook_node_access_records() you can query that field to get the values from the taxonomy field and set your grants accordingly.

Next is hook_node_grants(). This hook is called anytime a node is accessed. This check will check if the user is on a portal, and add a grant for the current portal.

function hook_node_grants(AccountInterface $account, $op) {
  if ($op == 'view') {
    if ($portal = some_function_that_gets_the_current_portal_id()) {
      $grants = [];
      $grants['portal'] = $portal;
      return $grants;
    }
  }
}

This code will return a grant for the current portal. If the node being accessed also belongs to the current portal (by matching a grant set in hook_node_access_records()), viewing permission will be shown.

2) Alter canonical node paths with a custom access callback.

With the above two hooks implemented, viewing access permissions for the node have been taken care of. However, the route is still accessible, as access permissions on the route only check if the user has 'access content' permission, and doesn't include a check on whether user has permission to access the node the route displays. When building menus, route permissions are checked, not access permissions on the node. So the next permission is to override the route, and provide a custom access callback that also checks whether the user has viewing access on the node. This way, due to the node grants set in steps one and two, when the menu is rebuilt, it will only add items to the menu if the user is on the portal the items belong to.

To do this, first an event subscriber is created to alter the routes:

namespace Drupal\my_module\Routing;

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

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setRequirement('_custom_access', 'Drupal\my_module\Access\PortalNode::access');
    }
  }

}

The above class will alter the entity.node.canonical route, giving it a custom access callback. The next thing to do is create Drupal\my_module\Access\PortalNode::access() and include the check on viewing permissions for the node. This class will look like:

namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class PortalNode implements ContainerInjectionInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a PortalNode instance.
   *
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    AccountProxyInterface $currentUser
  ) {
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
   public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

  /**
   * Custom access callback for node canonical routes.
   *
   * @param \Drupal\node\NodeInterface
   *   The node whose canonical route is being accessed.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   An access result that either provides or denies access.
   */
  public function access(NodeInterface $node) {
    // Allow access if the user has 'access content' permission (the default)
    // as well as viewing permission on the given node.
    return AccessResult::allowedIf(
      $this->currentUser->hasPermission('access content')
      &&
      $node->access('view')
    );
  }

}

Finally, the event subscriber needs to be registered in my_module.service.yml so it is picked up, and the route is altered:

services:
  my_module.route_subscriber:
    class: Drupal\my_module\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

3) Add a custom cache context for portals.

As your menu will need to differ by portal, it must have a cache context set for portal. There may already be a cache context you can use that matches the Drupal functionality behind your portals. You can check existing cache contexts here: https://www.drupal.org/docs/8/api/cache-api/cache-contexts#core-contexts

If the cache context you need does not exist, you'll need to create a custom cache context. Here's an example: https://medium.com/@joshirohit100/cache-context-drupal-8-part-2-10088f67012e

4) Set the menu block to vary by the portal cache context

At this point everything is mostly set up, however, the first time the menu is built, that version of the menu will be shown the same on all portals, as it has not been set to vary by portal cache context. Your system needs to have the menu block vary by portal - ie. variations of the menu must exist for each portal, since each portal will have a different list of links in the menu.

To do this, you'll implement hook_block_alter() in order to add a custom cache context on the menu block. You'll need to get the ID of the menu from your system. Let's assume it's "portal-administration".

/**
 * Implements hook_block_alter().
 */
function my_module_block_alter(array &$definitions) {
  $definitions['system_menu_block:portal-administration']['class'] = 'Drupal\my_module\Plugin\Block\PortalAdministrationMenuBlock';
}

Finally, the class defined in hook_block_alter() is created. It's extends the system default menu class, and adds the portal cache context to the menu block:

namespace Drupal\my_module\Plugin\Block;

use Drupal\system\Plugin\Block\SystemMenuBlock;

class PortalAdministrationMenuBlock extends SystemMenuBlock {

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $cache_contexts = parent::getCacheContexts();
    $cache_contexts[] = 'portal';

    return $cache_contexts;
  }
}


List taxonomy terms in node where the vocabulary is referenced

You should be able to accomplish that with the Views Module:

  You need Views if

  You like the default front page view, but you find you want to sort it differently.
      You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
      You use /tracker, but you want to restrict it to posts of a certain type.
      You like the idea of the 'article' module, but it doesn't display articles the way you like.
      You want a way to display a block with the 5 most recent posts of some particular type.
      You want to provide 'unread forum posts'.
      You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts for
  that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.

Depending on your folder structure, you can use a contextual filter and can create a block, then limit which pages on which it is viewable.


you can use a hook_FORM_ID_alter and then add code like this:

$form['FIELDNAME']['#options'] = array (

   'parent1' => array(
      3 => 'child1',
      4 => 'child2',
      5 => 'child3',
    ),
    'parent2' => array(
      8 => 'child1',
      9 => 'child2',
    ),
);


On the People page (admin/people), first select the blocked users and then from the update options select Cancel the selected user accounts. (Drupal 7)

Another way is using the Views Bulk Operations module.


Validate a file extension using getMimeType

You can use file_validate_extensions() for this


You can do this by adding an offset (you can find this in the pager options in your view), in your example "3". The offset "3" will show all results, but skips the first 3. Make sure that the sort criterea in both views are the same.


Views API custom table not showing fields

In order for Views to work with custom tables, you need to tell Views about your data structure with hook_views_data. The writeup and comments on that page will help you define the guts of the implementation. You basically have to tell views about the table, any relationships (and how), and describe each field in your table and what handler/filter etc it can have.

Aside from that, Data can help wire this automatically, but note that this will require re-defining your table/schema using the Data API.


Views search to find users based on terms

With search API you create an index containing all the info that should be searchable. The easiest thing would probably be to create an index based on the Profile entity and add the reference to the User entity and add the fields you need, like the term reference.

If you only want to let users search on the term reference, you might want to exclude normal search altogether and use facets instead, that would allow users to select terms and get the users displayed. Alternatively you could just use Views alone since Search API in not needed if you don't do fuldtext search.

With or without Search API you can in Views select the fields you want to display, just like any view, and use the template options Views provide to customize the output of the search page.


How to rewrite the output of $content inside a pane template?

Look in your panels module the function template_preprocess_panels_pane() you can use this.

http://www.drupalcontrib.org/api/drupal/contributions%21panels%21panels.module/function/template_preprocess_panels_pane/7

http://www.drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template_preprocess_panels_pane/8


How do I translate the weekday in a date?

Use the below example as a temporal solution, I'm not sure if this is the proper way. The approach is to split the problem.
{{ value_1|date("l")|t }} {{ value_1|date("d/m/Y") }}

Regarding the next link, the proper use of translation on twig is using "t" filter.
How do I translate strings in Twig templates?