Insert a view into a block or a node using a shortcode

Your problem seems to be one of passing in context.

A better option is to install either the Display Suite Module, or Page Manger with Panels. It is great for passing context and creating custom views outputs on your node .With both of these options you have far more control, and if you invest in learning the ins and outs of at least one of them you will not be sorry.

I will walk you through using Display Suite:

Install CTools' Views content panes. Create a base view that lists whatever you need listed, then add a Content Pane (from CTools) to the view. Add a relationship to the term in question, and then any and all contextual filters that would be needed. Lastly, under PANE SETTINGS in views, click on Argument input, select From context for each of the contextual filters, and slect the required context for each of them.

Install Display Suite. In the display of your node type, select a layout (one column should be fine) to activate display suite to render that view mode. Create a new dynamic field. Drag it to wherever you want it displayed. Click on the gear next to it, and at the top would be a Edit content link. Click that, and select View panes, then the view you just created. It will then ask for you to select the context for each of your views contextual filters. Node being viewed is what you select.

Now when you view the node it pulls in that view with the required contextual filters and displays its output as a field.


This guide can be used as a work around http://echodittolabs.org/blog/2011/04/setting-js-callbacks-drupal-json-and-some-jquery-sauce-jcarousel-controls

We are looking for a generalized solution to this here http://drupal.org/node/1148204


How to display an HTML table after the form submission on the same page as the form?

If you're saving your data in $_SESSION vars, I think the easiest way would be to check for the existence of your session data when you build up the form. Then you can show the table at the top of the form if the user has already submitted data, and the normal part of the input form directly underneath. A basic example:

function my_form($form, &$form_state) {
  if (isset($_SESSION['my_var'])) {
    $form['table'] = array(
      '#markup' => 'Your table markup based on session data here'
    );
  }

  $form['input'] = array(
    '#type' => 'textfield',
    '#title' => 'Title'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit'
  );
}

function my_form_submit($form, &$form_state) {
  $_SESSION['my_var'][] = $form_state['values']['input'];

  $form_state['rebuild'] = TRUE;
}

You'll probably need to put some sort of mechanism to clear that session var at some point, if you want users to be able to reset their submission.

A more complete example with functionality to remove items:

function MYMODULE_form($form, &$form_state) {
  // If we have some session data set, build a table
  if (isset($_SESSION['MYMODULE_data'])) {
    $header = array('Food', 'Calories');
    $options = array();
    $total = 0;
    foreach ($_SESSION['MYMODULE_data'] as $item) {
      $options[$item['identifier']] = array(
        $item['food'],
        $item['calories']
      );

      // Keep a running total
      $total += $item['calories'];
    }

    // Add the total row
    $options[] = array('Total calories', $total);

    $form['existing_data'] = array(
      '#type' => 'tableselect',
      '#options' => $options,
      '#header' => $header
    );

    $form['remove_item'] = array(
      '#type' => 'submit',
      '#value' => 'Remove Selected',
      '#submit' => 'MYMODULE_form_remove_item'
    );
  }

  $form['food'] = array(
    '#type' => 'textfield',
    '#title' => 'Food'
  );

  $form['calories'] = array(
    '#type' => 'textfield',
    '#title' => 'Calories'
  );

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

  return $form;
}

function MYMODULE_form_remove_item($form, &$form_state) {
  $remove = array_filter($form_state['values']['existing_data']);
  foreach ($remove as $key) {
    unset($_SESSION['MYMODULE_data'][$key]);
  }
  $form_state['rebuild'] = TRUE;
}

function my_form_submit($form, &$form_state) {
  // this example will just use the food name as the identifier
  $_SESSION['MYMODULE_data'][] = array(
    'identifier' => $form_state['values']['food'],
    'food' => $form_state['values']['food'],
    'calories' => $form_state['values']['calories']
  );

  $form_state['rebuild'] = TRUE;
}

I haven't tested that but it should give you a good starting point even if there are a few bugs.


The default resources of Services are all fairly broken, because they rely on simulating an actual form submission (blah!). I recommend using those provided by Services Entity instead.


Change no results behavior of the result of a link generated from a view

OK!  So after hours of research and playing around in my views, I figured out that the problem was I was having the individual links go to the Taxonomy page for that term.  I turned that off and re-wrote the results of each link to be the term: Name instead of that term's url alias.  I got rid of all my URL aliases for the terms.  I also added a second view that used the term and node relationship and a term: Name contextual filter, and added the custom no results behavior I wanted on that view.

In the end my URLs are not as clean since spaces and ampersands are converted to html escape characters, like "%26", but at least I have a no results behavior I want.


Yes you can do this.

I often use zen as a base theme and have some common things that are always in the sites we're building, so we have a common sub-theme theme of zen, and then each site has a sub-theme of the common sub-theme.
For things like this it is great to use this kind of setup.

So you have:
Zen > Zen sub-theme > Zen sub-sub-theme

In the sub-sub-theme the base theme would be the sub-theme.

For more detailed information on how it all works, see the Creating a sub-theme page.


JSONP requests not working in REST server

Try POST method instead of GET. Drupal won't allow authentication through GET method due to security reason.


Can I translate nodes and provide access to their translated content without the use of a site-wide language switcher?

A simple solution in such cases would be to remove the language switcher and provide for translated content only modal links:

French version

You could add the links to the node, in a template or preprocess hook. Or create a block (View or custom block plugin), which lists the available translations of the current node as modal links.

How to build such links see How to open a popup form from a view link?


How to output just the Name and Status in drush listing modules

Using Drush 8 or Drush 9:

drush pm-list --fields=Name,Status

If you want to consume the output from another script, you might also want to consider:

drush pm-list --format=json

In that instance, all fields will appear in the output; however, since the output will be in json, it is easy to parse and then use only the fields of interest.


Invalidate Internal Page Cache on cookie change

The Internal Page Cache doesn't support cache contexts. It is a simple reverse proxy designed to serve static database content and the only Drupal specific feature it has is to invalidate cache tags. For more dynamic use cases you have to uninstall this module.

The Dynamic Page Cache will then be the frontend cache for anonymous traffic. It is not as fast as the Internal Page Cache, though, so if it doesn't provide the performance you need consider a third-party reverse proxy which is able to handle cookies dynamically.


How can i add or set more email tokens in my drupal 6 site

i guess you want more tokens in the users settings page admin/user/settings (D6), according the format of your token (!username)

This page is a bit special because it is a core feature.
cf User settings

Token module provides more tokens like [my-token] but this cannot be applied in the admin/user/settings

If you want more tokens on the users settings, i suggest to use a custom rule (fire on user's creation) with the rules module


How to implement a follow author (or user) function?

Minimal solution

The Notifications module currently only has an Alfa version for D7 (which is this question is about), which dates from Dec 2011.

Therefor, use the Flag module as an alternative. So that users can "flag" authors they want to "follow". You'd want to use a flag related to entity "users", which is a non-global flag. Probably defined with a label like "Follow Author" (to 'flag' an author) and "Unfollow Author" (to undo a previously flagged Author).

Combine this with using the Rules module to send eMails whenever content gets updated by some author. Whereas the eMails are sent to all users who "flagged" that author (= the users who indicated they wanted to "follow" that author). If you'd only want to send such eMails for a subset of content that's being updated (eg only for selected content types), then it's just a matter of adding an appropriate extra "condition" to your rule.

Improved solution

Optionally you may also want to consider the Message module for more options in the area of sending some type of notifications. For this, you need a flag like described above (say with machine name follow).

On top of that you need a Message type and a custom Rule, both are detailed below. And you probably also want to add a custom View of those messages.

Message type

Below is an export of "a" Message type that you could use to get started (by simply importing it in your own site). It defines the message to be created when a user is flagged and it actually works together with the custom rule below. This message type has machine name user_following, and uses a replacement token like @following_user (adapt both to fit your needs, eg change @following_user to @user_who_flagged if you prefer):

{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

This Message type (compare to a Content type ...) will be used to create Messages (compare to Nodes) that will look as in this example:

  Hillary.Trump started following Donald.Clinton

To avoid confusion, note that [message:user:name] in the message type sample above is the user to which the Message is targeted, not the flagging user!

Custom Rule

Here is a rule (in Rules Export format) which creates a message when a user is flagged:

{ "rules_somebody_started_following_you" : {
    "LABEL" : "Somebody started following you",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "user" ],
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_follow" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "user_following",
            "param_user" : [ "flagged-user" ]
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "entity-created:arguments:following-user" ],
          "value" : "[site:current-user]"
        }
      }
    ]
  }
}

Some more details about this rule:

Its purpose is to deliver a message (using the Message module) to a user being flagged (using the Flag module).
It is triggered after a user is flagged with the flag with machine name follow.
It creates a Message with machine name user_following.
It makes a variable with machine name following_user available as a replacement token for the message to be created ... so that the "flagging user" (= [site:current-user] when the flagging happens) can also be included in the message to be created.

Custom view

With the above rule and message type, you'll have "messages" that get created ... "So what?" you may think. Well, since all this is entity API based, you can create a custom view (using Views) to visualize these messages, e.g. shown via a path like /user/nid/messages. Whereas the only limitation for such Views is your own imagination (you could even create the Charts about those Messages (eg by originating user, by date, etc).

Additional info

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework. Possibly also the similar set of 8 video tutorials about the Flag module.

For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation. And/or checkout the video introduction "Your Drupal site can talk" (if you want you can fast forward to about 03:30 where it really starts).

Note: this approach can be used also for any type of users (not just for "authors").


Can the Feeds module work with get parameters?

By default, the Feeds importer is set to file upload, but you can set it up to fetch data using an HTTP request.

On the settings page for your importer, click the Change link next to Fetcher in the left menu.
Select the radio button for HTTP Fetcher and hit the Save button
Visit /import and click on the link for your importer.

There will be a field there where you can enter the URL you want it to retrieve data from.


You have an error in your block that causes a fatal error or exception.

Right click and open the place block in a new window and/or check your error logs.


You can simply achieve that by using the Superfish module.

  Superfish integrates jQuery Superfish plugin with your Drupal menus.

Image from Superfish module page

There is another module called Nice Menus

  Nice Menus enables drop-down/right/left expandable menus. It uses only CSS for most browsers, with minimal Javascript for IE6. (Version 2 uses the Superfish jQuery plugin for all browsers, with an option to disable JS, and falls back to CSS-only for browsers that can handle it.)


This might be what you are looking for (https://drupal.org/node/1988848)


How do you do download the files folder from the Acquia cloud service?

You can read up on some drush specific tasks that you can do in this Elevated Third blog post

Acquia supplies drush commands and aliases that tie into Acquia Cloud API calls. So you can actually simply use the alias and the rsync drush command:

drush rsync --progress @sitename.env:%files @localenv:%files

You can also create and download Acquia database backups with the ac-database-instance-backup and ac-database-instance-backup-download commands.

Also, if you want an "all-in-one" solution, the newer versions of Acquia DevDesktop tie directly to your Acquia cloud account and can get database and file syncs automatically.


Notification + Subscription: Can this combination recipe be used to create notification system similar to Facebook's?

you can use my module for this Total Subscription.

  Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.


How do I get a field value in a template?

A simpler way to do this is to use mytheme_preprocess_image().

Here is an example:

/**
 * Implements hook_preprocess_image().
 */
function MYTHEME_preprocess_image(&$variables) {
  if ($variables['style_name'] == 'content_embed') {
    $variables['attributes']['class'][] = 'custom_class';
  }

  $variables['attributes']['data-custom-attr'] = 'value';
}

Variables can be used to construct new values that get injected before rendered. The above would add custom_class to a rendered images class attribute if a specific image style is being used in this instance, and all images would receive the second attribute. Rendering the image will already give you the src and alt attributes for you, so which attributes are you really trying to add?

Reaching into render arrays in the template just leads to a ton of cruft and hard to maintain code because it's really not the place for that.

If you don't want any divs or wrapping HTML in your field, you can just add this to the field twig template:

{% for item in items %}
  {{ item.content }}
{% endfor %}

This would only render the field item (in this case image), which should leave you with only the image tag on the page and no containers.


There is no need to programmatically alter it, as there is a configuration form that allows you to change it, the README.txt says

The image style used for the background image can be changed by going
to "admin/config/system/entity_background_image"

There is also a link to it in configuration


Need help with PHP: Show an image field when video field is empty

Trust on Views empty field settings :-)

Hide the image and the test field. Configure the video field empty setting telling that should show the image field: use the right token, something like this:

[field_image]

Then configure the image field empty setting with the text field.

So, if there's no vídeo Views will try to show the image field. When rednering the image field Vies will show the image if it's present, or the text field if image is also empty.


Drupal and mobile - integration across multiple applications

You need something like next, right?

User upload image from mobile application
User can see it in site

If it's right - it's not need new database, all can be maked with one. As one method - you can create special node type and one of next things:

Create custom module, that create new nodes (in my opinion - it's better)
Submit node creation form from application


How to partial search in taxonomy terms and entity references with Views Exposed Filter?

Use relationships to expose the exact field, for instance use taxonomy relationship and then instead of the taxonomy field expose taxonomy term name with the relationship selected. Do the same for entity reference.


Use the google-webfonts-helper or a similar tool to download all possible font formats (only *.woff won't be enough regarding cross-browser compatibility).
Store the font files somewhere in your theme, maybe in a subfolder called /fonts.
Use @font-face in your CSS to load the fonts as described in this brilliant CSS-Tricks article: Using @font-face

@font-face {
  font-family: 'MyWebFont';
  src: url('../fonts/webfont.eot'); /* IE9 Compat Modes */
  src: url('../fonts/webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('../fonts/webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('../fonts/webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('../fonts/webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('../fonts/webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', SomeFallbackFont, sans-serif;
}


Does request_uri() have to be filtered or escaped?

The short answer is yes, you need to sanitise the variable yourself.

All request_uri() does is pass the raw input from $_SERVER['REQUEST_URI'] (or from a different source if the server is not Apache). Apache/PHP does nothing by default to sanitise the $_SERVER variables on your behalf so they should be considered unsafe.

There's an excellent answer to Which $_SERVER variables are safe on StackOverflow that goes into a lot more detail, and actually notes that REQUEST_URI "may contain tainted data".


Steps to Create a copy of a Drupal 7 website using cpanel?

Here are the steps I would take in cloning the site. First, Create the subdomain. Then copy all the files from the live site to the subdomain. Then I would back up the database. Create a new database and import the backup into that. Assign the user from the first database to the second one. Then change the settings.php file to read from the second database. Also, if you have a base url set in settings.php you would need to change that as well. Hope that helps.


The Field CRUD API could be a better approach instead of handmade DB calls.

If you must: Field creats two DB tables for every field they are called field_data_field_fieldname and field_revision_fieldname. The contents depends on the field type.


display status report even though the module is disabled

That's not possible.

For hooks to be executed, your module must be enabled. From the docs:

  To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Emphasis mine.

Allowing modules to run code even when they're not enabled would be a massive security risk, and could cause all sorts of other unforeseen problems.


How to set domain based search using search_api_solr?

You could take a look at Search API Domain Access sandbox project:
https://www.drupal.org/sandbox/raf/2244229

I did a work around based on that code that worked for me:

<?php
/**
 * Implements hook_entity_property_info_alter().
 *
 * Adds an entity property for the domain access of the node.
 *
 * @TODO this is just a workaround @see https://www.drupal.org/sandbox/raf/2244229
 */
function my_module_entity_property_info_alter(&$info) {
  $properties = &$info['node']['properties'];
  $properties['my_module_domain_access'] = array(
    'label' => t('My Domain Access Information'),
    'description' => t('The domains to which the node is published.'),
    'type' => 'list<integer>',
    'getter callback' => 'my_module_get_domain_info',
  );
}

/**
 * Custom getter callback for the domains in
 *
 * @param $data
 * @param array $options
 * @param $name
 * @param $type
 * @param $info
 * @return null
 */
function my_module_get_domain_info($data, array $options, $name, $type, $info) {
  return (!empty($data->domains) ? $data->domains : NULL);
}

/**
 * Implements hook_search_api_query_alter().
 *
 * Adds a filter for the current domain.
 */
function my_module_search_api_query_alter(SearchApiQueryInterface $query) {
  $domain = domain_get_domain();
  $query->condition('my_module_domain_access', $domain['domain_id']);
}

Now, you will be able to choose the field for indexing under "admin/config/search/search_api/index/your_index/fields" and in query time this code will filter out data based on current domain, not many more things.

Hope it helps, but notice that this code it is not fully tested (nodes that have been published in more than one domain... etc).


How do I limit or require the number of tags in a taxonomy reference field?

The module field_validation has an option for Number of selections which could be what you need without custom coding. For 7, there's a full release and for 8, there's an alpha.


Not exactly sure what you want here. But i think i understood that you have 3 profile types defined in profile2 and want to expose these to anonymous users, so that they can sign up?

If this is indeed the case, then i would reccomend you to take a look at the profile2 registration path module

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

This module allows you to setup a direct menu path to a user registration form that shows the profile types you select


How can I can I add functionality to my module so that the templates can be overwritten?

You need to declare your templates by implementing hook_theme(), and when needing them in your module uses a render array rendered with the RendererInterface::render() method on the renderer service.

Theme, or other modules, will then be able to declare override for your templates like they do for any others.

The theme system overview in Drupal documentation gives more details on this process.


Content type errors - "The Byline text" error

I found the issue. Event though I had unchecked 'Display author and date information.' under 'Display settings', I still needed to empty the text fields or at least remove the tokens from them.


I'm not very clear what you're asking, so I might be on the wrong track. However a basic search returns a set of nodes that match in a particular order; the normal culprits are Apache Solr and Elastic Search, but there are others. For a large site definitely don't use the builtin search, and do investigate using 'search api' if you're not already.

Once you have a set of nodes, it's up to you how to display them. Including the taxonomy terms associated with each node is part of the display logic, rather than the search itself, and should be relatively easy. Have a look at Display Suite for better control of search views if you need it, though it may well be more appropriate to write a custom node render hook.

If you are more interested in something like a tag cloud of terms that the currently matched nodes reference, that is more difficult but I would look at the tag cloud module, with some custom glue logic to link them.

Hope this helps...


Diferences between "mysqldump" and "backup and migrate module"

My hosting is a non dedicated version, so, I don't install drush.
But I found a good solution. In config BAM (/admin/config/system/backup_migrate) have an tab "Schedules". In this option u can add backup schedule. Excellent solution, because winscp script (my script backup hosting) will get .mysql.gz generated in BAM private folder automatically. Additionally, about file size backup, BAM really exclude some data tables. This option is personalizable in "/admin/config/system/backup_migrate/profile/list/edit/default", "DEFAULT DATABASE BACKUP OPTIONS" option "Exclude the data from the following tables".


User permission to edit only nodes with taxonomy term

Taxonomy Access Control Lite module should help you.

  This node_access module governs access to nodes based on the taxonomy
  terms applied to the nodes. A simple scheme based on taxonomy, roles
  and users controls which content is visible.


How do you add "Rating Field" to a content type?

Do it yourself version:

You also can add a custom field, integers, with min 1 and max 5 values.
After this you only need to theme the display of the field, in a twig template maybe.

For achieving the star effect, there are plenty of solutions for that on google (css / js perspective).

One of them is to use field type List (integer) and in options use this values (so there will be select/radios with stars shown, but stored as a integer):

1|★
2|★★
3|★★★
4|★★★★
5|★★★★★


You can find all info with examples here: http://drupal.org/node/715276

<?php
function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface &$query, &$caller) {
  $query->addParam('fl', 'some_field_image');
  $query->addParam('fl', 'some_field_date');
  //Remove sorts
  $query->remove_available_sort('sort_label');
  $query->remove_available_sort('bundle');
  $query->remove_available_sort('sort_name');
  //Rename sorts
  $query->remove_available_sort('score');
  $query->set_available_sort('score', array('title' => t('Relevance'), 'default' => 'desc'));
  $query->remove_available_sort('ds_created');
  $query->set_available_sort('ds_created', array('title' => t('Latest'), 'default' => 'desc'));
 }
?>


Content dependent on the IP of the viewing user

I think that this depend that you are looking for. See this information if you want to hide a block according certain conditions http://drupal.org/node/134425 (you can custom your php using $_SERVER['REMOTE_ADDR'] to get IP address)

If you want to show or hide whole sidebar, I think that you can make this in template.php (in your theme), adding with php your IP condition, and according the result of condition, set (and/or unset) regions. See this for more/related information http://drupal.org/node/539488


Some thing you can try doing is try printing the entire query string like,

$query = "DELETE a FROM {term_node} a LEFT JOIN {term_data} b ON a.tid = b.tid WHERE a.nid = ".$nid." AND b.vid = ".$vid;
print $query; //printing the query

Notice that I have used the variables instead of place holders %d. This might not be relevant but has helped me many times while debugging queries.

On the link you mentioned http://drupal.org/node/1079620, have you tried #5 ? if not give that a try, it should work IMO.


How to access the filepath of an image from a view on a content type

You can use file_create_url($uri) which will generate an absolute URL (including $base_url which contains your server domain name).

print file_create_url('public://someimage.jpg'); will generate something like http://localhost/sites/default/files/someimage.jpg if your website is installed in localhost and your files are located in the default directory.


What is the proper way to set up Drupal 7 on load balanced servers so that CSS and JS files are in sync?

Drupal's core aggregation does not work on a cluster because it creates the aggregates  during the page rendering. Once the page is stored into the cache another server of the pool will read from the cache so it will not render the page again meaning that the CSS or JS aggregation will not be done locally.

To solve this problem, I created a NFS share between the servers just for the "css" and "js" folders. It was running ok for a while but under heavy load Drupal was sometimes generating empty files (2 servers creating the file at the same time). So even keeping in sync the servers is clearly not a solution.

But just as Beebee said, you can use the Advanced CSS/JS Aggregation module. This one is clever enough to be able to rebuild an aggregate just from the URL, because it stores in the database a mapping of the files that are part of the aggregate.

Advagg is also able to handle groups of aggregated files. This can reduce your bandwidth usage if your visitors navigate across different pages because the common files can be merged into a separate aggregate and the delta files merged into another aggregate.


May be you're better of creating a vocabulary for your categories. This way you can filter for vocabulary terms in views.


What is the proper way of using existing fields?

Should I create "Written by" field (term-reference to Authors) for each content-type or create the field for one content-type and use it in other content types?

If you need to collect the same information for different content types, you should use a single field. Your "Written by" field sounds like the perfect case for that. If you had different vocabularies for your authors, say "Book author", "Article author", etc, you'd want (and need) to use separate fields for each.

  What are advantages/disadvantages of either methods?

One advantage is that you can query all content types by the one field. So if you find yourself wanting to view all content written by a single author, or even all content written by all authors, it will be easy to create a view to do that. But that's only useful if you need it, obviously. I suppose the main point is that the use case of the field itself will actually dictate the relative advantages/disadvantages of either method.

Also, whenever you create a field, you create two database tables (one for current data, one for revision data). There are, shall we say, "mixed" feelings about whether this method of storage is the best idea from a performance standpoint, and some people prefer to keep the number of tables down.  When you attach an existing field to another content type, the same database table is used for all of them, so that box gets ticked. Again though, this only makes sense when your data can be separated.

  What happens if I delete a reused-field from one content-type? Does it get deleted in all others?

The field will only be deleted once it has been detached from all content types. Data that belongs to the content type from which you detached the field will be moved into a deleted data table, and purged during cron runs.

On to case 2, and just ask ask yourself this...

Keeping in mind that you can have different labels for each content type's instance of the same field, will that give you enough of a visual (or data-led) cue to let you know the differences between the data?

If so, use a single date field to gain the advantages mentioned above. If not, then it makes more sense to your data design to have separate fields.

It all comes down to what's appropriate for your particular website, but hopefully the above will give you some sort of way forward.


I got it to work by adding a relationship to a taxonomy field that exposed the taxonomy name. Then on the Contextual Filter I followed what the links said in regard to Specify validation criteria. But since I still can't find the Filter Value Type option, I just set the Case option to Capitalize each word and in the More section I checked the Transform spaces to dashes in URL option.

This allowed the value in the URL (which was a URL alias) to match my Taxonomy term field.

I don't know if there's an easier way to accomplish this and I'd still like to know why I couldn't find the Filter Value Type option, but at least it's working.


Have you looked at the Spark distribution?

Rather than placing the preview next to the form as you propose, the Quick Edit module (in-place editor) allows you to edit certain fields while they're still in their original context. The Responsive Theme Preview might also be useful to you.


It seems that you may forgot to move the vendor directory to the new location. Also you may need to run composer dump-autoload to update the autoloader with your new vendor's path. Though may be obvious to many, you need to clear the Drupal cache, in this case I prefer do a truncate over the cache bins (assuming you're using the default cache backend).

Update

Also worth checking the autoload.php file in your Drupal root, this file includes the actual autoloader generated by Composer.


how to restore the calendar view created by the calendar module?

it is very simple.
Go to Home » Administration » Structure » Views and add new view from template.
Yo could see in this section different calendar views.
Regards


Remove password reset fields on user profile

To hide the password fields on the user edit form, put this code in your custom module, which implements hook_form_FORM_ID_alter():

function YOURMODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  hide($form['account']['pass']);
}

You may also want to prevent users from going to user/password page and change their passwords on that page:

function YOURMODULE_menu_alter(&$items) {
  $items['user/password']['access callback'] = 'user_access';
  $items['user/password']['access arguments'] = array('administer users');
}

One more hint, if you want to remove the links on the user login block:

function YOURMODULE_form_user_login_block_alter(&$form, &$form_state, $form_id) {
  $form['links'] = '';
}


You need to convert source date from d-m-Y to Y-m-d

process:
  field_date:
    plugin: format_date
    from_format: 'd-m-Y'
    to_format: 'Y-m-d'
    source: Date

because default field Date use format Y-m-d to store date. and Y-m-d\TH:i:s to store datatime.

Form display just show default pattern (mm-dd-yyyy) of html5 input date


What could be causing duplicate nodes to be posted?

We see this (or somthing similar) quite often. Some users create a new node, add text, hit save. So far so good, but sometimes they see an type error or so and go back with the browser Back button, make the corrections and hit then save again. Usually this creates a new node instead of editing the one they think they edited.


In terms of core function I don't think there's a lot of choice you can have.  You'd have to use the "text" field type and limit to 36 chars.


How do I install the kurti devi 10 font for CKEditor?

Check out @font-your-face module. It lets you to add fonts with UI, and it even have some kind of wysiwyg integration.


How can I add an AJAX callback to a checkbox?

ajax_example_autocheckboxes_callback function is not defined in the above code.

Also please update more info about what you are trying to do.

$form[$term->tid] = array(... 'ajax_example_autocheckboxes_callback' ...); //ajax callback
$form['tree']; //new field.

after the above function call you can get new built_info of $form_state as its rebuilt. So you can alter output of the field.

function ajax_example_autocheckboxes_callback($form, $form_state) {
  dsm($form_state);
  return $form['tree']; // this is a new field.
}

I will update my answer if more information is provided.


Content Types and the db tables they create

You can use views to create the queries for you so you can easily change your views in the back-office without the need of messing with custom code.
Or if you want to write the views yourself use the EntityFieldQuery class to create custom views without writing joins yourself because this is defenitivly not the way to do it.
You can load the full node object programmaticly by using node_load() and filter the fields you need. This loads the full node object so this can slow down the system when loading lots of nodes using node_load_multiple().
And finally if you think this isn't straightforward enough consider writing your own entity where you can add all fields inside your custom table(s) and get the entity data with simple queries.
When using the views module you can add your entity to the views data by using hook_views_data. There is also the possibility of adding fields to your entity so this opens a lot of opportunities if really needed. It's a bit of extra work to install, especially the first time u use entities so you have to see if the budget allows room for testing and debugging.
An introduction to entities


Use the scheduler module. This module allows nodes to be published and unpublished on specified dates.


How can I create a view on a profile page that shows content related to the user we are viewing

Check out the EVA (Entity Views Attachment) module. This allows you to create views, which you can use as a field on any entity (node, profile, user or whatever) you like.

After you created the view, go to "Manage Display" of your content type and move the field in the right position.


Does using Drupal.ajax() offer any benefits over jQuery.ajax()?

There isn't really any difference in this context; at the lowest level both will use a standard XHR, so I reckon there's a good chance the bottleneck is the server-side building of the View.

You can test that by profiling, or in a pinch, returning a static string from the AJAX callback temporarily and stress testing the server. If you don't see the bottleneck, you know that building the View is the expensive bit.

If you're able to build up a query for the node data, and render the HTML manually, you should definitely see a performance improvement. A that point, though, you might want to question if using Views is the right thing in the first place :)


Wrong number of Cart items in Foundation theme topbar

You don't want to put this code directly into your tpl, as it will indeed cache. What you want to do is create a region in your template and then add your cart block to that region in the UI. You will also have to set that block to load via ajax or ESI so that it works properly with Authcache. You will see those settings if you go to configure the block.

Ideally you don't ever want to include any code that "does stuff" in your tpl files, as it can get cached. This is more obvious in Drupal 8 thanks to twig making this harder, but it is very easy to do incorrectly in Drupal 7.

You can be even more efficient if you change your code to save the cart quantity as a session variable or cookie and only calculate it when the cart changes, thus saving you from performance heavy order loads on every page. This is outside of the scope of your initial question though, but I thought I would mention it.


Yes, WAMP is not a good environment for Drupal 8. Use a different OS in a virtual machine. Either a Linux VM built from scratch or by a tool like Drupal VM, or a docker based tool like DDEV, Docksal, and Lando.

Which one to choose would be opinion based. Consider not only performance, but also that debugging is most effective, when the dev environment is as close to production as possible.


Improvements in Drupal Gardens way: How do I place an input filter selector in CKEditor?

This is the code responsible for those modifications.

(function ($) {

Drupal.gardens_misc = Drupal.gardens_misc || {};

Drupal.behaviors.gardens_misc = {
  attach: function(context, settings) {
    if (typeof CKEDITOR != 'undefined') {
      // Bind events to handle enabling and disabling of the WYSIWYG.
      CKEDITOR.on('instanceReady', Drupal.behaviors.gardens_misc.instanceLoaded);
    }

    $('.wysiwyg', context).closest('.text-format-wrapper').once('wysiwyg-tabs', function() {
      var $tabs = $('

').insertBefore($(this).find('.form-textarea-wrapper'));
      $('
' + Drupal.t('WYSIWYG') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
      $('
' + Drupal.t('HTML') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
    });
  },
  instanceLoaded: function(event) {
    var $wrapper = $(event.editor.container.$).closest('.text-format-wrapper');
    var $original = $wrapper.find('.wysiwyg');
    var $clone = $original.clone().val($original.val());
    $clone.bind('change', function(event) {
      $original.val($clone.val()).change();
    });
    $wrapper.find('.cke_toolbox').removeAttr('onmousedown').prepend($clone);
    $wrapper.find('.wysiwyg-tab.enable').addClass('wysiwyg-active');
    $wrapper.find('.wysiwyg-tab.disable').removeClass('wysiwyg-active');
  },
  tabToggle: function (event) {
    if (!$(this).hasClass('wysiwyg-active')) {
      $(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
    }
  }
};

/**
 * Overides the default attach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
  var $field = $('#' + params.field);
  var $original = $('#' + params.trigger);
  var $clone = $original.clone().val($original.val());
  var $container = $('

');
  $container.append($clone).insertBefore($field);
  $clone.bind('change', function(event) {
    $original.val($clone.val()).change();
  });

  // @todo: Need to display the allowed tags here
  var tags = Drupal.settings.wysiwyg_formats[$original.val()];
  $('' + Drupal.t('Allowed tags: ') + '' + tags + '').appendTo($container);

  // Original behavior
  if (params.resizable) {
    var $wrapper = $field.closest('.form-textarea-wrapper');
    $wrapper.addClass('resizable');
    if (Drupal.behaviors.textarea.attach) {
      Drupal.behaviors.textarea.attach();
    }
  }

  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.enable').removeClass('wysiwyg-active');
  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.disable').addClass('wysiwyg-active');
};

/**
 * Overides the default detach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.detach.none = function(context, params) {
  $('#' + params.field).siblings('.wysiwyg-none-header').remove();

  // Original behavior
  if (typeof params != 'undefined') {
    var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
    $wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
      .find('.grippie').remove();
  }
};

})(jQuery);;

Save the above in its own file e.g. drupalgardens_wysiwyg.js, then either add the script to the .info file of your theme/module or add the file on the relevant page(s) using drupal_add_js or via the #attached property of a form/render array.

To get this to work on a non-DrupalGardens site, I had to comment out the two lines below the @todo comment around line 53. You may need to further tweak the code depending on how you have your wysiwyg profiles configured.


Permissions checkboxes have disappeared on the Admin page for administrator users

Oh my, I just discovered what it is and I feel really ridiculous... I'm using the admin menu module, and in the configuration, under "System tweaks", there is an option "Collapse module groups on the Permissions page". It is checked. The checkboxes weren't hidden after all. The groups were just collapsed... Maybe I just need a break and another cup of tea.


How to make a image url active in Views Table

I assume that this is a file field and that you chose URL to File as the field formatter. You would then need to scroll down and expand Rewrite results, tick the box for Output this field as a link, and in the box for Link path you need to enter the views token replacement for your field name, which you can find by expanding the section below titled Replacement patterns—in your case it is likely to be [field_scan]

Once you enter that, you should have what you are calling "active link" which in more precise terms would be called an hyperlink or anchor tag.


Supressing "Undefined variable: variables in module_block_view()" without hiding the notice

The problem is with $block['content'] = theme('myblock1', $variables); and $block['content'] = theme('myblock2', $variables);: mymodule_block_view() doesn't define any $variables variable; just define it or use an array directly.

Since in mymodule_theme() you don't define any variable for your theme functions, just replace your mymodule_block_view() with the following one.

function mymodule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'myblock1':
      $block['content'] = theme('myblock1', array());
      break;

    case 'myblock2':
      $block['content'] = theme('myblock2', array());
      break;
  }

  return $block;
}

To make the question more complete: Drupal doesn't define any global $variables nor do hook_block_view() implementations receive any $variables as parameter. Therefore, $variables could just be a local variables for your function. That is why you are getting that error: You are using a variable without to first declare it.

Notice that if $variables were a global variable, you should still declare it as global $variables in your function, or use it as $GLOBALS['variables']. (Don't try it since it doesn't work because doesn't define any global variable with that name.)


use block_load to load the same block with parameters?

Based on what you've explained above, a custom module is required (I called mine MODULE) and you will have your hook_block info() which will declare the block:

function MODULE_block_info()
{
    $blocks = array();

    $blocks["userinfo_Block"] = array(
        "info" => t("User Info Block"),
    );

    return $blocks;
}

And hook_block_view() which will define the block. Below I have set the block content to the return value of the function userinfo_Block():

function MODULE_block_view($delta = "")
{
    $block = array();

    switch ($delta)
    {
        case "userinfo_Block":
            $block["content"] = userinfo_Block();
            break;
    }

    return $block;
}

Now, the function that creates the block:

function userinfo_Block()
{
    global $user;
//print out user, remember to check for no user
print_r($user);
}


Update: this answer is probably fine for D8 but not D7.

Using the migrate_plus module, I was able to specify shared configuration for about a dozen different feeds that needed to be given separate taxonomies upon import based on which organization's media I was importing. I created a group with my source and process configuration, then created individual importers for each feed with just the configuration that was specific to that feed. If I wanted to import them all at once I could run drush mi --group=<group_name>, and if I wanted to roll back a single feed I could run drush migrate-rollback <migration_name>. The only tedious part for me was creating a dozen nearly-identical migrations.

So, for example, here's a group definition for an Twitter importer:

id: twitter_importer
source_type: twitter
shared_configuration:
  source:
    plugin: url
    data_fetcher_plugin: http
    data_parser_plugin: json
    authentication:
      plugin: oauth2
      base_uri: 'https://api.twitter.com'
      token_url: /oauth2/token
      grant_type: client_credentials
    fields:
      -
        name: id
        selector: id_str
      -
        name: text
        selector: text
      -
        name: timestamp
        selector: created_at
    ids:
      id:
        type: string
  process:
    title:
      plugin: substr
      source: caption
      start: 0
      length: 254
    type:
      plugin: default_value
      default_value: twitter_feed_item
    # etc. etc.

Then a few migrations like this:

id: tw_dept_a
dependencies:
  - migrate
  - migrate_plus
migration_group: twitter_importer
source:
  # this changes from migration to migration
  urls: 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tmountjr&count=10'
process:
  field_source:
    # this also changes; works because the group's shared config specifies the plugin
    default_value: tmountjr
destination:
  plugin: 'entity:node'

It's annoying setting it all up on the frontend but after the third one you get pretty quick at copy/pasting the template and replacing one or two variables.

So I guess to answer your question:

  How can I create individual migration groups - one for each XLM file, without having to write a new migration class for each file?

I'm not sure you can get around that...but you can abstract a lot of the repeated configuration out of each individual file using shared configurations. You can maybe further refine the process by having a template file with placeholder variables, duplicating the file, and using sed on the new file to replace filenames:

cp migration_template.yml migrate_plus.migration.migrate_xml1.yml
sed -i "s/filenameplaceholder/file1\.xml/g" migrate_plus.migration.migrate_xml1.yml


How do you update a user role to be an admin role via Drush sql-query?

I do not see a reason to execute a sql query, when this can be as simple as

drush user-add-role "administrator" --uid=2524

To see more options with command type

drush help user-add-role


How can I get rid of Contribute 8.x-5.0-beta3 module?

Always you have to first uninstall the module, then remove the codebase from filesystem.

Composer have nothing to do with installing or uninstalling of modules in drupal. Composer is responsible for downloading the needed files, or removing if not longer in use.

If you first remove the files from the filesystem, you cannot uninstall it properly, because drupal not knows what to do.
Therefore you see such errors about missing things.

What can you do now to get rid of this error if such happen:

Go one step back & put missing files back to filesystem.

If you use git, checkout your last composer.lock before this error, than type composer install to get the old module files back.
Or use your backup or your ftp-program to bring the module files back.

Now you can uninstall the module as you like, perhaps using the gui or with drush (typing drush pmu modulename). This step is important, because it removes all things installed by this module. If you skip this, you will get such errors.
Now delete unwanted module files again:

checkout your newest state of composer.lock (without that module)
and type composer install and composer will remove the unwanted files

Don't forget to clear the cache. (drush cr)


Personally instead if all Vocabularies are part of same "Tree" they should be in one "vocabulary" and current items should be displayed as parent terms -> children terms tree structure

1. regarding first bullet point

https://www.drupal.org/project/taxonomy_menu <- allows adding
taxonomy items to any menu of your choice
https://www.drupal.org/project/taxonomy_menu_block <- creates a block
in sidebar with list of your terms of selected vocabulary with
options such as "Count" that is updated on cron run
taxonomy_manager <-  I use to mess around with the order of things or
importing lots of terms it really speeds up the process if you would
need to move taxonomies from different vocabularies into one :)
Google it as I cannot post more then 2 links :)

2. regarding second bullet point

For that you would need to create "Taxonomy view" instead of content view and set it up so that the categories would be displayed for example: (cant post example as not enough rep)


In Views, how do I get a link directly to an image file (not the node containing the image file)?

An option that doesn't require installing a new module:

Create a Relationship to the image for which you want to create a link
Add a field File:Path
Exclude from display
Rewrite Results - output this field as a link
Add the replacement pattern to your global text


How can I allow users to opt out of receiving e-mails with one-time login links?

What I would do is define your own token.

Start off with copying login_one_time_token_info() and login_one_time_tokens() into a custom module, change the hook names and rename the token to something like login-one-time-optional or whatever you prefer :)

Then, change the implementation of the hook_tokens() implementation so that you check the field on the $account and use either the existing function or url('user/login', array('absolute' => TRUE)). Keep in mind that existing users users might not have any data saved in that field, so add a default value, you might want to put something like this in a helper function:

if ($items = field_get_items('user', $account, 'your_settings_field')) {
  return (bool) $items[0]['value'];
}
else {
  // Default to use the one time login link.
  return TRUE;
}


How to create a glossary page in Drupal 7?

Option 1: Install https://www.drupal.org/project/views module. Go to Structure > Views, then enable the 'Glossary' view. View module provide 'Glossary' view by default.

Option 2: Also you can achieve your requirements by installing https://www.drupal.org/project/views_glossary module.


Mapping regular SQL to Drupal's Database API - using 'exists'?

I think you'll need to use a where() for the condition in the subquery, PDO will most likely quote the 'tid' and mess it up.

$sub_query->where('bt.biblio_type = b.tid');

You can cast a SelectQuery to a string to view it's SQL equivalent at any time, it helps a lot with debugging the more complex queries.

print (string) $query;


search results page in custom layout using Display Suite

In configuration search setting I "Active search modules" set display suite search and set Default search module as "display suite".


What do I have to do to get hook_form_alter picked up?

It turns out this was something related to MultiDev, a Pantheon-specific feature.  By cloning back and forth between the main dev branch and my multidev branch, I was able to get the custom hook_form_alter() to work.


So first of all you want a page callback to handle the deleting. You either want to use confirm_form() or add a token to the link to avoid CSRF. node.module does the former, so I'd go with core. You can also use that as a reference: node_menu() (look for $items['node/%node/delete']), node_delete_confirm(), node_delete_confirm_submit().

Regarding the actual deleting, this page has some instructions. Please update the Q if you have specific issues.

Here's an example, not tested:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items['MYMODULE/%/delete'] = array(
    'title' => 'Delete',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_delete_confirm', 1),
    'access arguments' => array('PERMISSION_TO_CHECK'),
  );

  return $items;
}

/**
 * Form function returning a delete thingy confirmation form.
 */
function MYMODULE_delete_confirm($form, &$form_state, $id) {
  $form['#MYMODULE']['id'] = $id;

  $name = MYMODULE_get_name_from_id($id);

  return confirm_form($form,
    t("Are you sure you want to delete %name?", array('%name' => $name)),
    '<front>',
    t("This action cannot be undone."),
    t("Delete"),
    t("Cancel")
  );
}

/**
 * Submit handler for MYMODULE_delete_confirm.
 */
function MYMODULE_delete_confirm_submit($form, &$form_state) {
  if (isset($form['#MYMODULE']['id'])) {
    $id = $form['#MYMODULE']['id'];
    db_delete('MYMODULE_thingy')
      ->condition('id', $id)
      ->execute();
  }
}

/**
 * Loads the name of the thingy from its id.
 */
function MYMODULE_get_name_from_id($id) {
  return 'thingy ' . $id;
}


How to setup view to filter based on second URL parameter?

Content Views don't have access to Taxonomy term name information out of the box, you only have term ID available. So even if you add the Taxonomy term field as the contextual filter and set the Validator = Taxonomy Term Name you're not telling it what to use, you're basically making a mistake trying to use that validator.

You can test this if you enter the term ID into the Preview instead of the name, or set the Action to take if filter value does not validate to Display a Summary and see what you get as output ;)

Add term name info through Relationship

To introduce the term name information into your content views you have to:

add a Relationship to the term: Taxonomy term referenced from field_topic. Require it if you only want to list nodes that have a topic assigned.

Now you will see a new Category of fields when adding Contextual filters: Taxonomy term
Add the Contextual filter Name from Taxonomy term Category, it will use the Relationship from previous step by default, and configure it:
When filter value is not available
Display all results for the specified field
When the filter value is available or a default is provided
 Specify validation criteria
Taxonomy term name
[Case settings, other relevant config as you see fit]

You will now see all results when visiting the main path, and if you visit the path with topic name appended the list will be filtered to show only nodes with that topic.

In case you have terms with the same name accross vocabularies

There is a bug that kicks in sometimes  when using term name as the Validator, if you have different terms with the same term name: TermName views argument_validator is not working as expected.

The patch from that issue is working, as reported by the question author usernameabc, so it can be used until a new version is released that includes it.


cron error Fatal error: Call to undefined function filter_xss()

Can you make sure the filter module is enable.

I think this problem is because you have a function call to filter_xss() before the filter module load.

Is your Drupal is stand install or this problem exist after install other module?


No, you don't have to specify a folder, file field will use 'sites/default/files' by default. In the file field settings there is a textfield to set a subfolder if needed.


Show new content count on the taxonomy term list view

Solution A: Use Views Field View

Using the Views Field View module it is possible to embed the results of one view into another view.

First create a view for nodes without a page/block (you only need the master display) and name it New content count by term. Add a context filter Content: Has taxonomy term ID. Ensure that only the Nid is listed in the fields section, add the filters Content: Published (Yes) and Content: Has new content, then enable aggregation, choose Count from the Aggregation settings of the Nid field and finally remove any pagers.

Now you may embed the New content count by term view into your principal view (taxonomy terms) by adding a "Global: View"-field (provided by the Views Field View module). In order to specify the tid-parameter of the embedded view, make sure that the Term id is also exposed as a field in the principal view. If you do not want to show it to the end user, just choose Exclude from display in the field settings. After the output of the tid field can be used as a parameter (token [tid]) for the embedded view.

Solution B: Use hook_views_query_alter

There is a function in the forum module responsible of returning the number of new posts on a topic (term) on behalf of a given user (_forum_topics_unread). Use this query as a starting point for your own implementation of hook_views_query_alter.

I recommend to go for solution A and only try to implement B when performance is degraded beyond acceptable limits.


Translate taxonomy term programmatically

In D8 you can translate entities with addTranslation().

This is an example for a taxonomy term:

$term->addTranslation($langcode, [
  'name' => 'translated term',
])->save();

You can provide values for all translatable fields in the array.


Drupal 7: Can't Update node using php script

Make sure you're logged into the site as a user with permissions to update the specified content type, because that session will carry over to your bootstrapped script. If you're logged out, you're essentially attempting to update the node as an anonymous user in your script, and permissions will come into play.

Try adding...

global $user;
print_r($user);

...to your script and see what, if anything, that outputs.


Countdown Timer Field cannot find Countdown Timer Library - even though it's there

The permissions were wrong after unzipping. They should have been:

 drwxr-xr-x 4 www-data www-data

which can be accomplished by:

 chmod 755 -R jquery-countdown/


Changing vertical alignment of teasers to horizontal

I think you'll have to investigate a bit further into your site structure generally. ;)

Assuming that you have content types of articles and basic pages on your frontpage, you could try something like this in your CSS:

.node-promoted {
float: left;
margin-right: 20px;
max-width: 280px;

}

"node-promoted" is the class one of several classes of teasers of articles and/or basic pages promoted to frontpage. You can use the almighty Firebug-Addon for FF to find this out ...


How can I remove javascript from everywhere but the front page?

You need to update. Below are the update :

if (!drupal_is_front_page()) {
      unset($javascript['path/to/script.js']);
    }

function drupal_is_front_page

Reference Link : Click Here


Only Solr supports that functionality. What you need is:

Create a server in Search API, call it, for example, "solr_server".
Create two indexes, one for nodes another for taxonomies. Make sure both indexes belong to "solr_server"
In views (make sure that search_api_views module is enabled), select 'solr_server' from Show dropdown list.
Now you can add fields from every index, that belongs to "solr_server".

Hope this helps.


One filter criteria for two different displays of the same view?

Seems like you want to display two different views with a common shared exposed filter in the same page (or as you said "same path"), instead of making two displays of the same view:

After created your view and your primary "view block", add the needed filter to that block, make sure that the filter is valid for all pages.
Then create an Attachment (you can find it in view configuration page Add>Attachment), and attach its to the block in
Attachment settings by chosing "Attach to:Block" and set a preferred
display position of that attachment (Attachment position)
Configure your Attachment with your needed format and fields, making
sure that these configurations are for "this Attachment
only"(*override)
Finally Set to Yes the "Inherit exposed
filters:" in Attachment settings
Et voilà enjoy your block+attachment with the same shared filter!

If you want to share the same filter in more than one views globally in the entire site, you can take a look to modules like Views Global Filter


how to implement hook_menu so that it recognizes URL like ?q=myterm, as sent by jQuery autocomplete?

hook_menu() don't handle query parameters. It accepts only wildcards.
You can get your query parameters in in your menu callback function and build your own logic by getting parameters as $_GET['q'] or drupal_get_query_parameters()


Ah, I just figured out from core/misc/dialog/dialog.ajax.js that I need wrapper with class form-actions.

  Send email


Display all associated tags from content page

If you are using D7 then check this lovely module for displaying child terms after rendering. Taxonomy display child terms.

You can look into Taxonomy Display module too.


You can use this -

$term = taxonomy_term_load($tid);
$field_image = field_get_items('taxonomy_term', $term, 'field_image');
if ($field_image) {
  $headerimg = field_view_value('taxonomy_term', $term, 'field_image', $field_image[0], array('type' => 'image'));
}
print render($headerimg);

In your file template.php use the theme_preprocess_page function like this :

function mytheme_preprocess_page(&$vars) {
  $term = menu_get_object('taxonomy_term', 2);
  if ($term) {
    $field_header_image = field_get_items('taxonomy_term', $term, 'field_header_image');
    if ($field_header_image) {
      $vars['headerimg'] = field_view_value('taxonomy_term', $term, 'field_header_image', $field_header_image[0], array('type' => 'image'));
    }
  }
}

Then in you page.tpl.php you can print render($headerimg);


Non need to edit template in this case.
Just edit title field and uncheck "Link this field to the original piece of content" option.


Create a funtion to retrive term depth

//Gets the depth of the term id
function MYMODULE_term_depth($tid) {
  $parent = db_query("SELECT parent FROM {taxonomy_term_hierarchy} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
  if($parent == 0) {
    return 1;
  }else  {
    return 1+MYMODULE_term_depth($parent);
  }
}

And Print the views based on depth

$depth = MYMODULE_term_depth($tid)
if ($depth == 0) {
  print views_embed_view('views_0');
}
elseif ($depth == 1) {
  print views_embed_view('views_1');
}
elseif ($depth == 2) {
  print views_embed_view('views_2');
}
else {
  print views_embed_view('views_default');
}

pass the view machine name to views_embed_view


How do I display articles in sticky footer?

if you number of archive and data in this block all always this (not need generate dynamic)  you can  create them  with 2 static block that their link  redirect user to a page that data was generated by views,(views page ).

and if you block data is not static and you want they generate dynamically I suggest you use views block(this mean a view with block display).

I think this link can help you it describe how to create a block that show month name and when click on each month  related data  according to the that month fetch by view.


Profile2 Registration Path loose registration field after translate URL alias

Profile2 Registration Path module does not support multilingual URL aliases. Profile2 fields are added to reg form based on the alias that you set up on profile2 edit form. That is why your profile2 fields are not displayed on dutch version of reg form. Your best choice is to remove translated alias and set your original regpath alias to something that sounds good in both languages. Or you can improve the module by adding multilingual alias support (though it may require some reworking in module's logic).


How to read-modify-write a multivalue entity-reference field

foreach (entity->get($field) as $k => $item) {
    $target_id = $item->target_id;
    if ($target_id == $old_value->id()) {
      $changed = TRUE;
      $item->target_id = $new_value;
    }
  }

  if ($changed) {
    $entity->save();
  }

That's it. You don't need to set any values, they are objects, your loop already updates them. You also don't need to loop over it by reference.

I just simplified it a bit because you can access target_id as a property through __set() and __get(), which has the advantage that you directly get the value and don't need to call getValue() on it.

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more information for example.


Get variable from controller in twig using template

I’m not sure why you’re expecting test to be an object, you declared it as a string.

Assuming the value of “2017” from your example is what you’re trying to get the variable is just:

{{ test }}


Download Count can produce file download statistics.

Additionally, because Download Count has Rules integration, you can create a Rule that will send an e-mail when a file is downloaded.


Imagefield Marker is a new D7 module for image annotations.


There is data for this field in the database. The field settings can no longer be changed.

That message is misleading, it will actually not limit the ability to increase the cardinality. The only limitation is that it won't allow you to set the cardinality to a value lower than the highest amount of items you currently have.


Views table output change row into column

Use views template, In advanced section, there is an option for theming - Theme:Information. Choose template from there or simply use views-view-table--yourviewname.tpl.php.

debug your rows here and add css classes to customize the output as per you want.

Take below code as a reference.

<?php
/**
 * @file
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $header: An array of header labels keyed by field id.
 * - $caption: The caption for this table. May be empty.
 * - $header_classes: An array of header classes keyed by field id.
 * - $fields: An array of CSS IDs to use for each field id.
 * - $classes: A class or classes to apply to the table, based on settings.
 * - $row_classes: An array of classes to apply to each row, indexed by row
 *   number. This matches the index in $rows.
 * - $rows: An array of row items. Each row is an array of content.
 *   $rows are keyed by row number, fields within rows are keyed by field ID.
 * - $field_classes: An array of classes to apply to each field, indexed by
 *   field id, then row number. This matches the index in $rows.
 * @ingroup views_templates
 */
$i = 0;
$cnt = count($rows);
?>

<?php foreach ($rows as $row_count => $row): ?>

        <div class="member-wrapper" id="<?php print $row_count; ?>">
            <?php
            $url = $row['field_profile_image'];
            ?>

<?php endforeach; ?>


jQuery expander module will work for you.

You will have to select expander from formater options in views field configuration.


Programmatically created content type don't have a delete link

You could always take the dull axe approach and use a page_alter, eg, something along the lines of

function YOURMODULE_page_alter(&$page) {

  if ($_GET['q']=='admin/structure/types') {

    $page['content']['system_main']['node_table']['#rows'][]=array(
      'Foo (Machine name: foo)
Here is my description of foo
',
      array('data' => l(t('edit'), 'admin/structure/types/manage/foo')),
      array('data' => l(t('manage fields'), 'admin/structure/types/manage/foo/fields')),
      array('data' => l(t('manage display'), 'admin/structure/types/manage/foo/display')),
      array('data' => l(t('delete'), 'admin/structure/types/manage/foo/delete')),
    );

  }

}

which will create a row for type foo.

Per additions to the question:  since the row is showing up but just without the delete link, you can go in and create it similarly, eg,

$page['content']['system_main']['node_table']['#rows'][NUM][4]=array('data' => l('delete', 'admin/structure/types/manage/foo/delete'));

where NUM is the row number where your content type is found. You might also want to check out Adding an operation to Content Types and the page_alter() there on a possible way you might be able to easily figure out NUM.

Another addition:

Could you just do this in your module:

$info = array(
    'type' => $type,
    'name' => $name,
    'base' => 'node_content',
    'custom' => TRUE, // fake it out to think it was made via the UI...
);
$content_type = node_type_set_defaults($info);

A cursory glance through the code and node_type_set_defaults() suggests that the only thing this does is allow this delete link to be presented in this very form.


Override of commerce-order-receipt.html.twig template not working?

Figured out what was the problem. I had to select my theme for sending emails on
Configure the Mail System admin page.
/admin/config/system/mailsystem
Other way some other theme is used.


Notifications for anonymous users on nodes

I would probably solve this with the following Rules-based setup:

1) Create a custom entity for anonymous posters with only a text field for email and an entity reference field for the node they created. Here's a pretty good writeup on creating custom entities:
http://www.istos.it/blog/drupal-entities/drupal-entities-part-3-programming-hello-drupal-entity

And here's Drupal.org: http://drupal.org/node/1026420

2) Create a rule for "Node->After saving new content" that checks if the poster was anonymous and if so, creates a new anonymous posters entity with the user's email + reference to the created node.

3) Create a rule for "Comment->After saving a new comment" that does a "Fetch entity by property" action and after a anonymous poster entity, sends an email out to them.

The only trick you need to figure out is how to play with rules upon fetching entities and accessing their fields. You need to create some rules component so achieve this whole flow since in order to access the field in the entity, you need to verify the type of the entity and this happens in "conditions", which can't be done after "actions" which is where the "fetch entity by property" magic happens.

So you'll basically have to create a Rules Component that does what needs to be done with the fetched entity.

This is definitely not the only way to achieve what you need to accomplish, but since I'm a strong believer in the endless powers of Rules, I like solving things with it. :)


Node registration form - redirect after submit

To redirect user to a particular page after the form is submitted you can use $form_state['redirect']

eg:

//Implementation of hook_form_alter()
function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    switch($form_id) {
        case 'form_id_of_the_form_to_alter':
            $form['#submit'][] = 'custommade_custom_submit';
    }
}
//Custom submit handler
function custommade_custom_submit($form, &$form_state) {
    $form_state['rebuild'] = TRUE;
    $form_state['redirect'] = 'whatever/link/to/redirect';
}

Hope this helps.


Finally I used a dynamic array

$tabImage[]["target_id"]

and inserted it

'field_indesign_rendition' => $tabImage,


How to programmatically add a field to a view depending on another field and reorder fields then

You may want to try the views_post_execute hook.

Otherwise there is a reduced list of hooks used for views rendering at the bottom of the Views Hooks API page.

It is a little hidden but I have used it many times and you may find a solution to your issue there.


How to add checkbox to subscribe newsletter in webform

If you want to add a checkbox field using the Webform module...

Choose the "Select options" type, enter the value and label, then choose the "Multiple"  setting (even if you just want one checkbox to appear), and make sure "Listbox" option is not on.


How to compare nodes of different types but same fields?

I would create a custom field handler. This gives you full PHP power about how the link of the "find flats" button will look like.

Writing your own handlers for views maybe looks difficult at the beginning. Once you understand it you will use it a lot. Here I found a how to about how to do that (it's for views 2). You'll find a lot of real world examples in all modules that do support views. Look for code like MYMODULE_views_handlers .


I find what exactly I want.

Administration theme module is great for using admin theme selected URL path.


Translate label of Comment Body with String Override

Yes there is you should try out
Localization client

This would help you out, and translate the content in t()


How to add dev modules to a distribution without getting security updates warnings?

Article Common Drush Make errors and their solutions has a solution for you. It seems that you should provide both branch and revision, if you want to clone exact revision and still have other info filled properly.

projects[ctools][type] = module
projects[ctools][download][type] = git
projects[ctools][download][revision] = 747151e
projects[ctools][download][branch] = 7.x-1.x

  Although you're specifying both a revision and a branch, drush make is smart enough to use the more specific thing (the revision) when cloning. It just uses the branch information for other metadata (updating the .info files in the things it checked out, and for displaying the contents of the distribution on the release node).

Emphasis mine.


Exclude taxonomy term from select list on node add page

You need to implement hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) inside a custom module.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x

Inside the form parameter you should be able to unset the specific option that you don't want to be displayed.


Checkboxes Defaulting to Selected When Not Desired

I think you have to set the value in each checkbox, so probably this would be it :

foreach ($license_result as $license) {
  $licenses[$license->code] = htmlspecialchars($license->name);
  $licensevalues[$license->code] = 0;
}
$selected_licenses = array();
return array(
  'selected_licenses' => array(
    '#type' => 'checkboxes',
    '#title' => t('Licenses to Display'),
    '#description' => t('Select which licenses the student should be able to select'),
    '#options' => $licenses,
    '#default_value' => $licensevalues,
  ),
);


drupal_static() uses a FUNCTION variable,what does it mean?

__FUNCTION__ is one of the so-called Magic Constants of PHP.

All it does is return a string with the name of the function that the constant is contained in.

For example:

function my_strangely_named_function() {
  print __FUNCTION__;
}

The above will print 'my_strangely_named_function'.

Drupal uses this constant with its static cache so that each cache is identifiable from any other function, and as such can be identifiably cleared.

To use an abridged version of your code:

function drupal_set_page_content($content = NULL) {
  $content_block = &drupal_static(__FUNCTION__, NULL);
}

Any other function in the Drupal lifecycle can call:

drupal_static_reset('drupal_set_page_content');

And that will clear the cache for that specific function, so that next time it's called the data is built up as if from new.

That's just the basic use of the static cache pattern, you can find more information and examples on the documentation page for drupal_static() itself.


Which tokens can I use in a rule to email all suppliers mentioned in an entity reference field?

Assuming your question is about D7, you could try to create a view (using the Views module) of those suppliers that you want to send an eMail to.

After you succeeded in creating such view, you can process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions (in the rule you already have in place related to your Rules Event about "completing the checkout process":

load the VBO list of those suppliers.
add a loop to perform a Rules Action "send an eMail", for each supplier contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


While it probably will do no harm, there is not much point in using both.

Regcheck is a small and super simple module that will add an invible (to humans) checkbox on your registration form. Bots will check this, and when the bot submits the form, it can be rejected.

Honeypot is a larger and more complex beast that do several thing to block 'bots. One of these thing is to let you add an invisible (honeypot) field to any form - including the registration form.  From the Honeypot docs:

  Honeypot form protection means that an invisible field is added to a form. If this invisible field is filled out (bots will usually put in a value), then the form will return an error. Normal users (read: human beings) won't ever see the field, so they won't fill it out.

If you install both, your registration form will have two invisble (to humans) fields.  There is little harm in that (having both installed will consume slightly more resources), but not much benefit either .

So I suggest you install Regcheck if you want a simple solution with minimal configuration just to stop 'bots from registering, and Honeypot if you want a more comprehensive anti-spam solution.

However, if you're looking for a solution that stops bots before they hit the registration form submit button, neither Regcheck nor Honeypot will help.  Both work by automatically dismissing registrations after they've been submitted.

If you want to block bots from trying to register, you can't do this by Drupal alone, but need to use webserver access rules.

There are projects, such as Project Honeypot (no relation to the Honeypot module) and Fail2ban  that will do this for you.

To set up a Drupal site to use the Project Honeypot blacklist of IP-addresses, there is also a Drupal module, http:BL.  AFAIK, there is no Drupal module for Fail2ban, but since it work directly with the the server, you don't need one.


I have an idea. This can be done by "Webform". Use a form as user profile, and set limit 1 form per user in "Form settings". Then use "Permission per webform" to make this form access webform results for all user. To display in search, it can simply be done by Views.

Update: another idea I found is to use "View profiles permissions". This module provides permission to view user profiles depending on what roles the profile requested to be viewed.


WYSIWYG and TinyMCE stripping out float: left

My solution:

I downloaded a new module called WYSWIWYG Filter. On my Text Format, I turned off the Limit allowed HTML tags option and instead enabled the WYSIWYG Filter option. Then below in the WYSIWYG Filter settings, I configured the allowed HTML elements like so:

a[!href|target<_blank|title],
div[align<center?justify?left?right],
p[align<center?justify?left?right],
br,span,em,strong,cite,code,blockquote,ul,ol,li,dl,dt,dd,
img[!src|alt|title|style|width|height|typeof],
@[style|title]

And I checked all the boxes to allow margins, padding, floating, etc.


Can we use Panels for Responsive web design?

Two new ways of doing responsive design in Panels include Adaptivetheme 3.x and the Panoply distribution.


Creating custom button that gets a certain views block on the database

All you need to use modal form which uses ctool suites. Install exapmple and dependant module. Try create link or button just same as ajax form.


I usually add a contextual filter for "user: uid", specify a default of "userid from the URL" and then set a validation criteria for "user" and "Allow both numeric UIDs and string usernames".
That way you can use both the uid and the username.

You'll probably have your "last post block" show up on the profile edit page because it's at "user/%/edit".
I changed my user profile pages to "member/USERNAME" using the pathauto module.


Postpaid license billing type does not work with Commerce Stripe

This is just to let every one interested know, that Aviindub was kind enough to reply to my post on https://www.drupal.org/node/2634778#comment-10669204, after which I have re-installed everything from scratch once again, but in little bit different order, and postpaid orders started to recur too.


Theme reply comments differently from node comments (Drupal 7)

You will have to use the surrounding classes to target the direct comments. Consider a site with the following structure (this is actually based on drupal.org):

...

    ... Node content ...

Comments

      ... Comment content ...

        ... Comment reply ...

...

Node comments can be targeted with the CSS selector .comment-wrapper > .comment. (only target first level childs).

Replies can be targeted with .indented .comment (target all level childs of indented comments).

So have a look at your site's structure and try a similar approach.


How do I prevent my content's title from appearing in the  tag of my RSS feed?

I haven't tried to reproduce this on my end, but I found a Drupal.org thread with advice that may be relevant:

https://www.drupal.org/project/drupal/issues/2946812#comment-12501714

  using 'Show: content' looks like a bad idea to begin with.

  I can get some nice clean output:

  Choose 'Show: Fields' (so not 'Force using fields', just plain fields output)
  Close the dialog without setting the required fields (just click the X in the top right corner)
  Add some fields (title, body, a url, node id)
  Go to Row style options (so click on the 'Settings' link behind 'Show: Fields'
  Fill out the required fields with the fields you've added
  Add more fields if you need them to fill out the required settings

If you build the description this way, you should easily be able to omit the title field. Good luck!


Ah, I was missing the ['#url'] part of the array. In order to get the url from the link field I called:

{{ content.field_link.0['#url'].getUri() }}

I do miss the ability to copy-paste from dpm().


Is it possible to move product category description alignment in drupal

This can be also done through the admin dashboard. Follow the below steps:

Go to admin/structure/types.
Select your content/Product type and manage Display according to your requirement.


How to extract an nid from and EntityFieldQuery


Drupal 8 - how to run multisite using one database

First, read this page on Drupal 8 multisite, https://www.drupal.org/node/2297419.

It should give you a good idea of what you have to do in order to get multisite working and also explain some of the things you should consider. Following are generic steps, there are many things you can customize using settings.php.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

Multi-site requires the existence of the sites.php file in the sites directory. This file does not exist by default.
Add your sites to a $sites array in this file, instructions are mentioned here https://www.drupal.org/node/2297419
Create a site directory inside sites/, the path should be sites/site1.
Each new site directory must have a settings.php file in order for Drupal to recognize it.
Visit the URL of site1, site1.yourdomain.com to install it.


Translate simple code snippet - Get taxonomy term id

I never used "page--taxonomy.tpl.php", but based upon what you want to do, I guess your looking for taxonomy-term.tpl.php.

In Drupal 7, you have a $term variable, from which you can get the tid. Below is some D7 code I've used for a similar purpose, that I adapted a bit to yours. Note that the argument to Views must be in an array.

$view = views_get_view('taxonomypages');
$view->execute_display('panel_pane_1', array($term->tid));
$output = $view->render();

But I do not recommend you proceed down this path. Instead use Panels, and pass the argument to a View that way. Yes, it will require a bit more configuration, but it will also be much more sustainable, easier to maintain, and keep less logic in the template files.

Relevant panels tutorials here.


Suggestions for sending email to third party merchant when checkout is completed

You can use a rule for that.

Use the action "Send a mail to an arbitrary mail address"

Set the recipients with php, like this (it's more powerful than tokens) :

<?php print _get_custom_emails_list( $node->field_custom );?>

Add this custom function in your custom module

<?php
// Your custom function
function _get_custom_emails_list( $field_custom ){
  // your query here.....
  return 'test@test.me, test2@test.me'
}
?>


The option exists in Drupal Console's drupal generate:theme; it's done by specifying the --base-theme option in the command. The option's value adds the base theme key with option's value into the generated theme's .info.yml file (which make the new theme a sub theme).


What does rc stand for? when to use alpha, beta and dev instead?

See Drupal.org for release naming conventions and
further explantion.

Summary:

rc = Release Candidate, deemed suitable by the author for production sites.

rc: A release candidate should only be created when the all critical bug type issues are reported fixed in the project's issue queue. This tag should only be used when the developer believes that the project is ready for use on a production site. There is no official best practice for how long a project should be a release candidate before creating a official .0 release, but it is suggested that it should be out for at least a month with status set to "needs review".  If something (e.g. a new critical bug is reported) makes it necessary to create a new release during this period, a new release candidate should be created and this should remain for at least a month with status set to "needs review".

It is OK to tag a module "rc" with feature requests issues outstanding.  Module authors are not required to fulfill every feature request users of the module post to the issue queue.

Here is a description of the other allowed release tags:

unstable: The project is not in a stable state.  There are probably numerous unfixed bugs, including security issues. The API may change without notice.  The database schema may change without hook_update_N beeing implemented. Usage and API may not be documented. Installing a new unstable release entails uninstalling the project, thereby losing all data.  Only for those who want a early preview of the project.  Not yet suitable for shared development.

alpha: Most reported errors are resolved, but there may still be serious outstanding known issues, including security issues. Project is not thoroughly tested, so there may also be many unknown bugs. There is a README.txt/README.md that documents the project and its API (if any). The API and DB schema may be ustable, but all changes to these are reported in the release notes, and hook_update_N is implemented to preserve data through schema changes, but no other upgrade/update path. Not suitable for production sites. Target audience is developers who wants to participate in testing, debugging and development of the project.

beta: All critical data loss and security bugs are resolved.  If the module offers an API, it should be considered frozen, so that those using the the API can start upgrading their projects.  If it is an upgrade or update of a project, an upgrade/update path should be offered, and it should be possible for existing users to upgrade/update to the new version without loss of data.  All documentation should be up to date. Target audience is developers who wants to participate in testing, debugging and development of the project, and developers of other projects that interfaces the project. Not generally suitable for production sites, but may be used on some production sites if the site administrator knows the project well, and knows to handle any remaining issues.

The strings "dev" and "stable" are not valid as part of a release tag, but untagged development releases are assumed to be "dev" and are given descriptions such as "7.x-1.x-dev" by the Drupal.org release packing system to indicate that they are untagged development releases.

All release tags must end with a number.  The numbers are just to distinguish releases of the same class.  The first is numbered "1" (as in "alpha1"), the next "2", and so on.

PS. The strings denoting releases (such as "7.x-1.0-alpha4") are known a "release tags" in git parlance, not "names".  And you never use the drupal minor version as part of a tag, you use "x" instead.


jdrupal entity_index success function not called

According to its source code, success should be part of the options

options.success = function(result) {
    console.log(result);
}
entity_index('contact', query, options);


The way to hide the node/%/view tab is to implement hook_menu_alter(), and change the menu defined from the Node module, which uses the following definitions.

  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),

    // The page callback also invokes drupal_set_title() in case
    // the menu router's title is overridden by a menu link.
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  $items['node/%node/view'] = array(
    'title' => 'View',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['node/%node/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'node_page_edit',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('update', 1),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'node.pages.inc',
  );

In particular, you need to change the menu type for node/%node/view from MENU_DEFAULT_LOCAL_TASK to MENU_CALLBACK, and change the type for node/%node/edit from MENU_LOCAL_TASK to MENU_DEFAULT_LOCAL_TASK.

MENU_CALLBACK keeps the menu item still accessible for those users who have the permission to see it, but the menu item would not be visible as tab or link.

As for using hook_local_task_alter(), I don't see Drupal core modules that alter the tabs added from other modules, but looking at blog_local_task_alter(), I notice the following code.

  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }
  // Provide a helper action link to the author on the 'blog/%' page.
  elseif ($root_path == 'blog/%' && $router_item['page_arguments'][0]->uid == $user->uid) {
    $data['actions']['output']['blog'] = array(
      '#theme' => 'menu_local_action',
    );
    if (user_access('create blog content')) {
      $data['actions']['output']['blog']['#link']['title'] = t('Post new blog entry.');
      $data['actions']['output']['blog']['#link']['href'] = 'node/add/blog';
    }
    else {
      $data['actions']['output']['blog']['#link']['title'] = t('You are not allowed to post a new blog entry.');
    }
  }

In your case, you should check that $root_path is equal to node/%; in that way you would avoid to do something when the page being shown is the front page. (If node/% doesn't work, then node/%node should.)

I still think that hook_local_tasks_alter() should not be used in this case, as it seems to me that hook_local_tasks_alter() is thought to be used when altering the tabs depends from the page being viewed, as blog_local_task_alter() shows.


Dynamic view with a field matching a role of User in Drupal 7

Add field_role in view and hide it.

Now create a custom php filter using Views PHP Filter

Get the current user role and compare it with field_role value. Following is the sample code.

<?php
  global $user
  $account = $user->uid;
  $roles = $account->roles;
  $field_role = $data[field_role]
  //$data is available in php views filter
  if(find user_role in field_role) {
    return false;
  else {
    return true;
  }
?>


How to programmatically uncheck 'Generate automatic URL alias' option for all nodes

Figured I'd help out -- took me a while to find it.

Pathauto doesn't implement hook_node_load, so you won't see it there.  My case was I needed to remove an alias in an update hook, and make sure that checkbox is unchecked.

So that's what I did

  $node = node_load(17);
  $node->path['pathauto'] = FALSE;
  node_save($node);
  pathauto_node_delete($node);
  node_load($node->nid);


how to prevent warnings from displaying to anonymous users

First you should turn down the error_reporting options on your production server. This will erase most of PHP's warnings and notifications.

Also you can configure drupal to only log the errors. To do that go to Administration > Configuration > Development > Logging and errors or directly to the path /admin/config/development/logging and set "Error messages to display" to none. Drupal then still logs errors but doesn't display them to users.

If you still need finer control over messages surely the module disable_messages can help you.


If you want to update your global installations of any package under composer, you can just do this:

composer global update

You don't need to navigate to .composer/vendor/drush/drush

However: There are a couple of things:

1) Your global composer.json file might have a version constraint.

Check out drush's packagist page: https://packagist.org/packages/drush/drush

That will show you the available release versions of drush.

Edit ~/.composer/composer.json so that the version constraint for drush/drush is higher than the one you have. Probably something like "~8".

Do composer global update.

2) It's best practice to install drush per project.

The reasons why are a little complex and might not answer the question here, so I'll just link to an article: https://pantheon.io/blog/composer-vs-drush-make-which-should-you-use


Could it be a permission issue?
Maybe set the "skip_permission_check" at true, as said in documentation here:
https://www.drupal.org/node/1748148#flagging


How do I get a javascript library to work inside the CKEditor module?

Using the code supplied in this associated question, I was able to get the javascript nav-pills to work in the CKEditor instance for Drupal 7. Unfortunately, it will only function in Firefox for PC. In addition, I had to add the following code to the ckeditor.config.js file as well as manually add the script to the admin theme's html.tpl.php file - this seems redundant but it will only work if both files have it.

CKEDITOR.on('instanceReady', function(ev) {
var jqScript = document.createElement('script');
var bsScript = document.createElement('script');

jqScript.src = 'http://code.jquery.com/jquery-2.0.2.js';
bsScript.src = 'http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js';

var editorHead = ev.editor.document.$.head;
editorHead.appendChild(jqScript);
editorHead.appendChild(bsScript);

jqScript.onload = function() { editorHead.appendChild(bsScript); };
});


Just create "promoted to the front page" nodes and keep node as your front page. The "add content" button you wanted is the node/add page. This has always worked with Drupal stretching back many years.