Changing Default Text of Fivestar Rating Widget

The String overrides make it easy to change that text or any other text in your Drupal site. Install the module, then visit /admin/config/regional/stringoverrides in your site and you can change the text as shown below.

Then when viewing the vote you'll see:


Create a separate view for each primary menu based on URL aliases in drupal 7

The reason for this problem has to do with how path aliases are handled. When the url is set to a page alias, Drupal translates the url into its actual url taxonomy/term/tid before it seeks the content that is to be displayed, such as your view definition whose path is still an alias.  Since the view path doesn't match the URL, it is not selected to generate content.  If you want a descriptive URL to work with the view path, you cannot use the path aliases.

I have a similar problem where I have converted hundreds of hierarchical taxonomy terms into a menu system with aliases using taxonomy menu. The aliases show up fine when I select a menu item, and set the View definition to Taxonomy/term/% but the views, of course, display the base URL instead of the alias.  I have not explored a work-around yet.  If you find anything, please post it here on your question.


Dynamically change email recipient in webform based on dropdown list

I assume the view you are using creates an option list of key|value pairs of the form nid|Restaurant name. For this answer, I will call your select element restaurant.

Install and activate the Webform node value module. This is a new module, and you will have to apply this patch. (If you are not familiar with patches have a look at Applying Patches.)
Edit your webform, and under Form components create a "Hidden" webform element called send_to_email.
Under E-mails add Component value: send_to_email as the to address.
Under Form settings go to the bottom and open the Set Value From A Node group.

The Path To Node is From webform field.
Since the key returned is nid, set the Path Alias Prefix to node/ so the nodes can be found using node/nid as the path.
The Webform Source Field is restaurant (your select element).
If the field containing the email address of the restaurant is $node->field_email, set the Node Source Field to field_email.
The Webform Target Field is send_to_email.


Override search-result.tpl.php with below code

<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url . '?search_keyword=' . arg(2); ?>"><?php print $title; ?>

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

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>

Then create a view that displays search results using views module and add a contextual filter saying search term, which is returned using PHP Code.

You can read the value in views contextual filter using $_GET['search_keyword'] and return the same.

Once view block is built, enable it in the pages you want !


Fetch user id on behalf of the non-drupal php

If you copy that code/file to another directory, DRUPAL_ROOT will be set to that directory, not that of drupal's... so I'd change up that first define to point to where drupal is and you should be all set.


Passing Settings from page.tpl to Javascript: Uncaught TypeError: Cannot read property

You need two line to add your code. Before one line to add js data settings:

$my_settings = array(
  'message' => $message,
);

drupal_add_js(array('my_settings' => $my_settings), 'setting');

and one line function to add file js

drupal_add_js(drupal_get_path('theme', 'sizin') .'/js/anim.js', 'file');

And better you don't write code in file tpl. You cand add js file, js  settings in hook_preprocess_page(). It's drupal standard and clean tpl file.


D7: Resetting ALL user fields (Boolean) at once

The Rules Once per Day module provides a 'Once per day' rules event that you can use to trigger your boolean flag update.

For bulk updating a list of users, if you have an action that loads a list of users you can then loop through and act on those users with rules.

There are a number of ways you can load a list of users in rules. Some of them are:

The Views Bulk Operations module provides some actions including 'Load a list of entity objects from a VBO view'
The Views Rules module provides the 'Collect view result rows' action.
The Rules Bonus Pack module provides a number of actions, including 'Load a user list with Views'.
You can create a custom action of your own via a custom module. See the rules developer documentation and various blog posts for more details.

I'm not sure of any easier way to loop through all users in the system, but the views approach is fairly straight forward and low maintenance anyway.

Also, you might not always want to loop through all users. for example you might want to exclude administrators or only loop through users where your boolean field is set to 1, to avoid unnecessary processing in the case that not all users have been set to 1 for whatever reason.

The action you use to load the users will create a new variable (eg. 'entity-list') that will be available in future actions. You can then use the 'Add loop' option in the rules actions section to loop through that new variable. That loop will create another new variable for the current item (eg. 'list-item') your are looping over and then you can add actions that act on that variable (eg. data set on list-item:field-user-not-emailed-today).


How to get contextual filter of a view from page.tpl.php?

You can use the arg() function.

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

In your case:
arg(1) = [year]
arg(2) = [month]


Using form elements for various forms in Drupal 7

Your function already accepts the $form variable by reference (function payment_details(&$form)) so you don't have to pass the $form element by reference when calling that function. Just use payment_details($form); in your form builder and you should be fine. Passing by reference is deprecated in recent PHP versions, so that's why you get a warning.


How can I query on a custom content entity base fields?

I was missing data_table in the Entity annotation. By adding that and update the entity it allowed me to query as expected.

 *   base_table = "map_object",
 *   data_table = "map_object_field_data",


Have you checked Home » Administration » Configuration » Media
IN this Public file system path should be "sites/default/files" and Temporary directory should be "/tmp".
And check whether you files folder has read/write permissions and its subfolder's where you are saving image.


I am almost sure it`s generated by your theme with css. So you can use firebug to find this line and delete background and padding of this element.


cout rows of a view for new content and comments

count($view->results) will only give you the number of the results on the current page if using a paged View. Try using $view->total_rows instead, which will give you the total number of rows returned by the View:

return l($view->total_rows, 'new-activity/' . arg(2));


Installing and loading google client php api

Here's an updated answer (the version of the client library I'm using is  "google/apiclient": "1.0.*@beta")

    function hook_libraries_info() {
     $libraries['google-api-php-client'] = array(
     'name' => 'Google API PHP Client',
     'vendor url' => 'http://developers.google.com/api-client-library/php',
     'download url' => 'http://developers.google.com/api-client-library/php',
     'path' => 'src/Google/',
     'version' => '1',
     'files' => array(
      'php' => array(
        'autoload.php'
      )
    )
  );
  return $libraries;
}

Note, the 'autoload.php' file in the files array.  This will automagically load all the classes you might want, and seems to work well for me; rather than manually selecting each file the library includes that I might need.

I load the library and then use it like this:

$library = libraries_load('google-api-php-client');
module_load_include('inc', 'page_speed', 'page_speed_client');

My inc file contains the logic I want for defining a new client and service (see the Google docs) and does a Pagespeed Insight query, and (for now) simply dumps the returned data onto a page.

Final caveat, remember to clear cache if you edit your files array, otherwise the library won't load properly, that caught me out a couple of times.


you can add to the node element in a module and call these in your template.
e.g.

mymodule_node_view()
{
  $node->mylink = 'Link';
}

Then in the node.tpl.php

print $node->mylink;


How to list all nodes referencing a node in a tree view

I have achieved this with Views and Views Field View.

I have added a View, showing Content of type Company and created a
Block with display format HTML List of fields.
Added a relationship Entity Reference: Referenced Entity Content entity referenced from field_reference_company
Added a contextual filter Content: Nid with the relationship
I've just added.
Provided a default value Content ID from URL to the contextual
filter.
Added the fields:

Content: Nid, excluded it from display.
Content: Title
Global: View and selected the view itself with Master Display, set as Contextual filters: [!nid]

That's it.


Is it possible to run a Drupal 7 on 2 domains?

Let's back up and debug this from the top:

Confirm that both sites actually point to the same Drupal installation.

Open up a terminal or command prompt. Ping mysitea.com and mysiteb.com. Confirm that the IP address is the same for both domains.
Create a dummy file test.html in the Drupal root. Confirm that you can access it from both mysitea.com and mysiteb.com.

Confirm both sites actually use the same database

Look in the sites directory. The only two directories should be "default" and "all". If you see mysitea.com or mysiteb.com, it's possible you are using different DBs.

Figure out what Drupal config is causing the error

Confirm that you don't have any domain-related modules installed (domain access).
See if clearing all cookies after switching to the second domain let's you log in. i.e., is the problem that you can't ever log in to one of the domains, or that you just can't log in to them one after another? This could be due to the cookie domain.

Try setting $cookie_domain in settings.php for each site.

EDIT: Now I see that you tagged your post "domain-access", so I'm assuming you are using that module. Why didn't you say that in your post? That's kind of a critical thing to know if your problem is related to accessing a site on two domains ;) I'm pretty sure it's just a misconfiguration or bad permissions related to Domain Access. Try disabling it and see if you can access both sites.


Update existing nodes with fields from XML or CSV

You need to set up feeds and feeds_xpathparser. You could found a good start for configuring all this here : http://www.drupalprogrammer.co.uk/2012/12/use-feeds-module-to-import-xml-data-in.html

Concerning your concern about updating, you can do this by configuring the guid as your external unique id. In the screenshot provided, you can see in my case the xml tag used for unique id is simply <id>.

Then, you just have to configure the node processor so that it will "Update existing node" when it found a duplicate as shown on the screenshot below.


I would change your code to (as @J.Reynolds specified):

  $items['admin/commerce/inventory/%/%/%/%'] = array(
    'title' => 'Inventory',
    'description' => 'View inventory reports for your store.',
    'access arguments' => array('access commerce reports'), // Inherited by children.
    'page callback' => 'inventory_reports_dashboard',
    'page arguments' => array(3,4,5,6),     // page_arguments = threshold amount,  sort direction, hide zero inventory, email report to, save_to_email bool, download_csv
    'file' => 'inventory.dashboard.inc',
    'weight' => 0,
  );


Adding/ Editing list of people with photos

You can do it using Drupal Core itself with out using any module. Just follow below steps to solve the problem.

Login as Super Admin
Go to admin/people/permissions/roles
Add a new role called "Cast Manager"
Give Edit any and Create new "Cast"  Content Type permission to "Cast Manager" role in admin/people/permissions/roles

That's it ! Now, users who have "Cast Manager" role can edit any cast content and manage them !


Get Contacts from social networking sites

I would use Contact Importer in conjunction with OpenInviter.  It could be that you do not have an app for the specific social network to give permissions to allow access to users' data.

While I was configuring HybridAuth, there were options to allow your site to access contacts of users.  This requires you acquire an API key for each social network you want to access, which means creating an app.  If you're still having issues I could set up an app on the social networks you would like to access, then configure hybridauth and see if you can access the contacts through its API.


I haven't been using a vagrant setup for a while, but back when I did, I used aliases similar to the one below:

$aliases['ogm'] = array(
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => '-p 2222 -i /home/ga/.vagrant.d/private_key',
  'root' => '/srv/www/ogm.postfix.local/drupal',
  'uri' => 'http://ogm.postfix.local',
);

Something like this should still work for your DrupalVM sites.

n.b. remote-user is the ssh username.


Issues with theme on moving drupal website to new server

At https://groups.drupal.org/node/104694 having a tilde in the url was successfully solved usign RewriteBase /~user on the .htaccess file.


Quick filter tabs on top of content listing page

View Bulk Operations (VBO) is a module that, through Views, allows you to create a page similar to the page visible in /admin/content/node. As the module allows to replace the content of that page with the content of a view, you can filter the list of the nodes following all the criteria that Views allows you to set.

The features of the module are not just those; the module allows you to select all the nodes listed in the view, and apply to them the action that is selected under "Update." The module is very useful for administrators, and it allows also to change the page that lists all the user registered in a Drupal site with a view with similar functionalities.


Suggestions for adding Advanced Search features to a block (using the dashboard)?

Search form is itself a block; you should add this box to a region. Let the client configure blocks; they can move the block from admin/structure/block.


For logged in user, let them view a list of content they have created (front-end user)

Add the fields you want from your skill content type to fields and then simply add a relationship of User: Author and then  create a filter using field User:current and make sure you use setting logged on user


Any way to do custom action from clicking an #autocomplete_path option

It is not possible: The purpose of the autocomplete callback is to offer suggestions to autocomplete what the user is entering.
Basing on what entered from the user, the callback needs to return the possible values the user could be writing; it is not supposed to redirect the user to a different page, considering that the user has not selected any of the values returned from the autocomplete callback, and that the callback doesn't know which of the returned values the user selected.


How to disable creation of node revisions on programmatic node update?

Right now, this isn't possible with content moderation installed without doing backflips such as replacing the moderation handler for the node entity type.

This is however being worked on! Here are some issues which are relevant to the problem you are having:

Allow 'syncing' content to be updated in content moderation without forcing the creation of a new revision
Allow the ChangedItem to skip updating
Better describe how SynchronizableInterface should be used for content entities

The proposal is essentially two pronged:

Better describe to callers of SynchronizableInterface::setSyncing() when it's appropriate to mark an entity as "syncing".
Encourage implementors of entity lifecycle hooks to reduce disruptive side effects while entities are syncing.

Quoting myself from the issue:

  IMO, the current 'syncing' status for content entities is shaping up
  into a flag to indicate that a save is happening under conditions
  which are outside of a typical user initiated content update and that
  as much as possible, side effects from that save should be limited.
  Examples might be:

  Deploying a workspace.
  Batch updating old revisions.
  Running an update from a migration.

  After defining some of those scenarios it becomes
  easier to rationalise eliminating some of the side effects that have
  been discussed (CM revision handling + changed timestamp).

In your case, you are attempting to resolve integrity in your model by bulk updating existing entities/revisions, it's outside a standard editorial based content change, so in my opinion it fits very clearly within the semantics that are being proposed for content entities and this interface. So with a few of these patches applied your code sample might look like:

  $entity->setSyncing(TRUE);
  $node->save();

And then the changed timestamp wouldn't be updated and content moderation wouldn't force the creation of a new revision.


Using a conditional OR in a view query alter programmatically

You can do this by using orConditionGroup():

$query = \Drupal::entityQuery('map');
  $group = $query->orConditionGroup()
    ->condition('attributes.color', 'red')
    ->condition('attributes.color', 'green');
  $entity_ids = $query
    ->condition('attributes.building_type', 'bikeshed')
    ->condition($group)
    ->execute();

Example from https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3AorConditionGroup/8.2.x


Did You checked if the exposed sort is not "required"? (there should be a checkbox that it's not mandatory field)
Did you checked if the "remember last chosen option" is unchecked?

Did You highlighted any possible option in configuration of this sorting?

EDIT:

I'm talking about this options list in 3. It should not be highlighted to default to ANY

EDIT 2


Using the track_field_changes module, I was able to get the side by side values in a view. Note , I also have revisions turned on for this node type.


Is it possible to post video on Facebook user timeline using Facebook Autopost module?

No. Not without building upon it. While the version of the FB PHP SDK (3.2.3) that the module relies on supports uploading video, there is no support for it in the module.

Looking at the current module, it looks possible to build in support. For example, take the scenario where the module supports uploading an image to the user timeline:

The rule action triggers rules_action_publish_to_facebook_timeline() which retrieves (in facebook_autopost_entity()) a FBAutopostEntityPhoto object which is extended from the FBAutoPostEntity class.
When FBAutoPostEntity::publishEntity() is called to publish the entity, it calls a parent method FBAutopost::publish() which checks a list of types that does include a video type.

Presumably, one could extend another class (e.g. FBAutopostEntityVideo) from FBAutoPostEntity that would add the various details for base classes that would allow it to plug in to the underlying SDK.

To sum it up, the existing module doesn't support however there's some support at lower levels in the code. That comes with the caveat that there might be more overhead to add (e.g. is there more to defining a Video entity than just extending the FBAutoPostEntity class) than what I mentioned here.


Is there a difference in the use of hook_preprocess_HOOK()

If you use:

function theme_name_preprocess_menu(&$variables, $hook) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

The hook is menu, so Drupal will look for menu.html.twig, if you define any var inside this preprocess you only be able to use in menu.html.twig. Look the Hook at your theme suggestions comments, if you see 'block' you will need use theme_name_preprocess_block instead.


Facet API pretty paths in combination with solr search form

There are two ways to avoid this issue which depend on module what you use.

1) If Search API module is used. (It was taken from https://www.drupal.org/node/2625298)

function hook_search_api_query_alter(SearchApiQueryInterface $query) {
    $original_keys = $query->getOriginalKeys();
    if ($original_keys == 'field_facet_filter')) {
        $query->keys(NULL);
    }
}

2) If Apache Solr Search module is use

function hook_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  if ($query->getParam('q') == 'field_facet_filter') {
    $query->removeParam('q');
  }
}


Should we use drupal_exit() after drupal_goto()?

Will the code after drupal_goto() execute ?

No - the last line of drupal_goto() is:

drupal_exit($url);

So the script will already have terminated without returning, and no subsequent code will execute.

You can safely ignore that recommendation.


Is there a function that can output an image?

You can use theme('image').

Supposing that $img contains the PHP object you reported, then the following code can be used to output the image.

$output = theme('image', $img->filepath); // Drupal 6.
$output = theme('image', array('path' => $img->filepath)); // Drupal 7.


Replace default submit handler when using drupal_get_form() in D7

The problem is when the form builder builds the form up again when it's submitted, your function won't be called so it doesn't know about the changes you've made.

hook_form_alter() (and hook_form_FORM_ID_alter()) were written for exactly this purpose, I'd advise using one of those, e.g.

function MYMODULE_form_commerce_coupon_form_alter(&$form, &form_state, $form_id) {
  $form['#submit'] = array('mymodule_coupon_submit');
}

It's worth bearing in mind that other modules' hooks might run after yours and change that array again. To avoid that have a look at How to update a module's weight.


You'll need a relation from the 'settings node' to the taxonomy term, and then from the taxonomy term to all other nodes.

The corresponding relations are called Content: Taxonomy terms on node and Taxonomy term: Content with term (which only becomes visible after adding the first one).

From there you can apply filters to the nodes. The relations you select for the filters distinguish between the base node and all linked nodes.


add class to book navigation block links

Give a try to Block class module: Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent <div class="block ..."> element of a block.


After much work I came up with a workaround. My first thought was to add a Twig filter to views-view-row-rss.html.twig like so <link>{{ link | replace('_', '') }}</link> but the underscore was still being displayed, which told me that either 1. the Twig filter wasn't working or 2. the underscore was being applied later in the render process.

The Twig template's documenation made reference to a template_preprocess_views_view_row_rss() hook I found implemented in /core/modules/views/views.theme.inc so I added the following hook to my custom.theme PHP file:

function ncei_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
   $variables['title'] = $item->title;

   //$variables['link'] = $item->link;
   $variables['link'] = str_replace("_", "", $item->link);

   if (isset($item->description) && is_array($item->description)) {
     $variables['description'] = (string) \Drupal::service('renderer')-
       >render($item->description);
   }

 $variables['item_elements'] = [];
 foreach ($item->elements as $element) {
   if (isset($element['attributes']) && is_array($element['attributes'])) {
     $element['attributes'] = new Attribute($element['attributes']);
   }
   $variables['item_elements'][] = $element;
 }
}

I commented out the original line above for reference, but I'm setting the link variable to the item's link, stripped of all undertscores. This isn't the best solution, and will break if the link actually contains underscores, but it worked as a temporary workaround in the meantime.


Hide Block on Particular Page with Bootstrap

You can use combination of media query  to achieve this.Using media query hide the block under mobile resolutions . For example

@media screen and (min-width: 480px) {
.block-class {
    display: none;
  }
}


How do get a body.onload event executed?

Putting $(document).ready inside of Drupal.behaviors attach is redundant.

The point of attach is that it will run when the document is ready.


Is it possible to use jQuery on filters (B.E.F.) in a view?

The right way to write jQuery in drupal 7:

(function ($) {
  Drupal.behaviors.functionname = {
    attach: function(context, settings) {
      // some code, with $
    }
  };
})(jQuery);


Organic Groups - How to disable "Groups" Tab

I had a similar problem with OG Extras installed, the view and members tab would show even when a site visitor wasn't logged in, I wanted it hidden for non registered users or non-admin users.

To stop it showing I edited the view 'OG Extras group members (User)' made sure I had the Page, not the block of the view selected and changed 'Access:' for the 'tab menu' to Role | administrator, this means that when logged in as an administrator I can see the desired tabs but when logged out the tabs are hidden.


As @lenni rightly says it's a serialized PHP variable. But data is a property of the user entity type so you don't actually need to unserialize it yourself.

When the user object is loaded from the database it's automatically populated with the unserialized version of the data column. So all you need to do to access your 'user tokens' field (if such a field exists, it doesn't appear to from your screenshot) is this:

global $user;
$user_tokens = $user->data['user tokens'];


How do I update without using the parameter --with-dependencies in "composer update --with-dependencies"?

I just use composer update --no-dev from the directory containing the composer.json file and the core directory, and I get all updated.

Loading composer repositories with package information
Updating dependencies
Package operations: 0 installs, 21 updates, 0 removals
  - Updating twig/twig (v1.33.2 => v1.34.3): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/yaml (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-mbstring (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/translation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/validator (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php55 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/serializer (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/routing (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php54 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-foundation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/process (v2.8.21 => v2.8.22): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-iconv (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/event-dispatcher (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/debug (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-kernel (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/dependency-injection (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/console (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-apcu (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/class-loader (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating guzzlehttp/guzzle (6.2.3 => 6.3.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/core (8.3.2 => 8.3.4): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

I put drupal/core in the require section, so it gets updated too.

As for the output of composer outdated, I get the following.

doctrine/annotations            v1.2.7      v1.4.0      Docblock Annotations Parser
egulias/email-validator         1.2.14      2.1.2       A library for validating emails
symfony-cmf/routing             1.4.1       2.0.1       Extends the Symfony2 routing component for dynamic routes and chaining sever...
symfony/class-loader            v2.8.22     v3.3.2      Symfony ClassLoader Component
symfony/console                 v2.8.22     v3.3.2      Symfony Console Component
symfony/debug                   v2.8.22     v3.3.2      Symfony Debug Component
symfony/dependency-injection    v2.8.22     v3.3.2      Symfony DependencyInjection Component
symfony/event-dispatcher        v2.8.22     v3.3.2      Symfony EventDispatcher Component
symfony/http-foundation         v2.8.22     v3.3.2      Symfony HttpFoundation Component
symfony/http-kernel             v2.8.22     v3.3.2      Symfony HttpKernel Component
symfony/process                 v2.8.22     v3.3.2      Symfony Process Component
symfony/routing                 v2.8.22     v3.3.2      Symfony Routing Component
symfony/serializer              v2.8.22     v3.3.2      Symfony Serializer Component
symfony/translation             v2.8.22     v3.3.2      Symfony Translation Component
symfony/validator               v2.8.22     v3.3.2      Symfony Validator Component
symfony/yaml                    v2.8.22     v3.3.2      Symfony Yaml Component
twig/twig                       v1.34.3     v2.4.3      Twig, the flexible, fast, and secure template language for PHP

That is normal, though, since the core/composer.json file has some restrictions for the package versions that don't allow to update to the versions shown from composer outdated. For example, see the following lines in core/composer.json.

"doctrine/annotations": "1.2.*",
"egulias/email-validator": "1.2.*"

1.2.* is telling Composer that any version greater or equal to 1.2.0 and lower than 1.3 are acceptable. doctrine/annotations version 1.4.0 falls outside that range.


How can I limit displayed nodes by term reference from current user?

To control access to your content based on taxonomy terms you need to use modules like Taxonomy Access Control or Permissions by Term. With proper configuration these will prevent users from viewing content they don't share terms with, even if they can guess the content links for example.

You can create Views that lists content based on shared taxonomy terms, but Views don't control access to original nodes pages. If a user can guess the node paths, or you have content listed on Taxonomy pages and the Taxonomy pages aren't access-controled then they will be able to see the content links there and click through.

Using one of those modules you will be able to control access through terms alone, or you may need to create a new user Role for each term, it depends on your details.

Once you solve the Permissions problem you can create Views that would show content that the current user shares terms with.

The easiest way to approach this is not to rely on weight/order at all. You can treat terms like badges: if a user reaches 3rd level, they would be tagged with the first 3 terms, and not only the third term. Drupal doesn't care if you name them "level-1" and "level-2" or "beginner" and "medium". You just have to make sure to add terms to the user once they pass a level, and keep all the terms they "collected" before.

If you go for only the one highest term they have reached you have to take care of the removing the current term when a new one is reached, it introduces complexity that isn't necessary if you're relying on taxonomy terms.

There are still ways to show only the highest term if you want to use it to rank a user.

To create a page showing content that the current user shares terms with you use Relationships to the taxonomy reference field. The details are almost the same as in this QandA: Based on user's country filter content of same country?


How to prevent anonymous users not viewing any webform content

You'll have to look at the content_access module which will allow you to configure default access control on a per node type or per node basis.

Content Access:

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.


Drupal Search- Linking Multiple Entities with Relations as a Single Unit

This turns out to be really easy.  On the Create Index page, just add the Related Entity (User->Node) Option for the relevant relation.  The entities will then all be index together as a single unit and you can do Views and Facets and all sorts of fun things with them.


what is use of $title_prefix and $title_suffix variable inside drupal theme system

I'm not sure how it could be any clearer than on the docs page, but here goes;

$title_prefix is for content that should be displayed directly before the title in a template file (node.tpl.php, block.tpl.php, etc).
$title_suffix is for content that should be displayed directly after the title in a template file.

There really is nothing more to it than that. If you choose not to include these variables in your template file then they simply won't be rendered.

Since any module/theme in the system has the chance to populate/change the values that are in either of these variables it's impossible to say exactly what will not be rendered in your particular case if you choose not to display them.

As an example, (and if I remember rightly), contextual links for blocks/nodes are contained in the $title_prefix variable. So if you don't print $title_prefix in your template, you won't get contextual links for that item.


Test if template files (.tpl.php) are used by theme

Just print the theme hook suggestion variable in any preprocess function in template.php

print_r($variables['theme_hook_suggestions']);

If you use the Devel module then

dpm($variables['theme_hook_suggestions']);


Adding Google Analytics using the module is not difficult. Please check this YouTube Video "Adding Google Analytics" it will walk you on the process of how to set-up your Google Analytics on your Drupal site. In addition it will to provide you the steps on how to set-up this video will give useful information about the different setting.

If you want to make sure that your website contain the Google Analytics you can check the output of your website (as an anonymous) and you should have something similar to this...

Usually takes few minutes to Google Analytics to recognize your website.

<script>
  (function(i, s, o, g, r, a, m) {
    i["GoogleAnalyticsObject"] = r;
    i[r] = i[r] || function() {
      (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date();
    a = s.createElement(o), m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
  })(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
  ga("create", "UA-xxxxx-1", "auto");
  ga("send", "pageview");
</script>


Problem with drupal 7 multisite installation

Documentroot is not proper for the second case.
It should be like this

ServerName www.example1.local
DocumentRoot /var/www/example


What hook can I use for post-save actions?

The correct way of doing this is to respect Drupal's db transaction.
If you want to do any database action in hook_node_insert you must consider that the node is not actually saved yet. which means if it fails and rolled back you end up with orphaned data in your database. So Drupal database API should be used and not direct query execution.

If you want to update the node itself in hook_node_insert, you can't because it's not possible to use node_save since the node is not yet saved in the database and calling it causes exception. One solution is to use register_shutdown_function function and passing nid, you can use node_load to make sure that it's really saved and then do any other action you may want on the new node.

function your_module_node_update($node){
  if($node->type == 'your_node'){
    register_shutdown_function('_your_module_post_insert',$node->nid);
  }
}

function _your_module_post_insert($nid) {
  $node = node_load($nid);
  if ($node) {
      node_save($node);
  }
}

UPDATE: You can also find an easier alternative here https://stackoverflow.com/a/24035797/1726778


How to provide facility to download & upload files to specific type of user in drupal 6

Create two roles namely "customer" and "guest" (if you had not created yet). Now you can use field_permissions to give each role the  permission you want. Add permission to customer role to download it and guest to view it.


How to setup views exposed filter with result between 2 fields values

The Range module allows you to add a numeric range field to a content type and provides Views filters allowing you to select values within or without the range.


Have you reviewed this page?

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_breadcrumb/7

Also, what theme are you using? I would check the base theme to make sure that it isn't preprocessing the breadcrumbs itself. If so, you'll need to make sure you are calling the appropriate function in order to override the breadcrumb settings.


Print array of imagefield fields for node type

You can get a list of all fields for a particular content type using the content_types() function:

$type = content_types($type_name);

if (isset($type['fields'])) {
  $fields = $type['fields'];
}

From there you can just loop through and see what type of field each is, and act on it accordingly.


The simplest thing you can do is provide a new "View Mode" for nodes, so that you can use it with the "Rendered Node" display option for the node reference field.

This would be done in a small custom module using hook_entity_info_alter() like so:

function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['node_reference_product'] = array(
    'label' => 'Node Reference Product',
    'custom settings' => TRUE
  );
}

Once the module is installed you'll have a new view mode under the "Rendered Node" display format options:

Now you can simply use the same node--product.tpl.php template file as normal and just test for the view mode to define what you want to display:

<?php if ($view_mode == 'full') : ?>

  <!-- HTML output for the full view mode -->

<?php elseif ($view_mode == 'teaser') : ?>

  <!-- HTML output for the teaser view mode -->

<?php elseif ($view_mode == 'node_reference_product') : ?>

  <!-- HTML output for your new view mode -->

<?php endif; ?>

Of course you still have access to the view mode in any hook_preprocess_node function so you could put your logic in there instead:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'product_node_reference') {
    $vars['content'] = array('#markup' => 'Some other content');
  }
}

But perhaps the best part of solving your problem this way is that Drupal honours the new view mode in the UI, so for each content type you will now have a new view mode which you can choose options for as normal:

Just like the standard full and teaser view modes you will be able to decide which fields are displayed, and the ordering and format in which they are displayed too. It's entirely possible that after writing that tiny one-function module you won't need to write another line of code to solve the problem.

You'll also have this view mode available system wide for use in, for example, Views/Panels etc.


How do I create a field template or template override for a specific display mode?

Fields

You have to add the theme hook suggestion yourself, first. For fields it's just the same as for nodes. Simply place the following snippet in your theme's template.php or your module's *.module file and replace MYTHEME/MYMODULE with your theme's or module's machine name.

Now copy the /modules/field/theme/field.tpl.php file over to your theme's /templates directory and name it along one of the following patterns:

field--field-name--view-mode.tpl.php
field--field-name--bundle--view-mode.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_field(&$variables) {

  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];
  $bundle = $variables['element']['#bundle'];

  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $bundle . '__' . $view_mode;
}

Commerce Product title

For Commerce' product titles though things are a little bit different, as you don't get the view mode or the referencing entity from within its preprocess hook. But you can simply use your own logic to add your template suggestions. For example a pattern in the URL alias or something like that.

Then copy the /sites/all/modules/contrib/commerce/modules/product/theme/commerce-product-title.tpl.php file over to you theme's /templates directory and rename it along your desired pattern.

commerce-product-title--foo.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_commerce_product_title(&$variables) {

  // The following suggestion only gets added when there's
  // a certain keyword at the third position in the URL alias
  // as in /myproducts/overview/foo/myproduct.
  if (arg(2, drupal_get_path_alias()) === 'foo') {
    $variables['theme_hook_suggestions'][] = $variables['theme_hook_original'] . '__' . 'foo';
  }
}


Use The Views Module To Create A Custom Block

If you're using the Views module you can create a view that will show you what you need.

Create a new view (admin/structure/views/add) and choose 'Content Revisions' as the view type.

Add the 'Node Revision: User' relationship so that you can access the username of the user that made each edit.

Add a 'Node ID' contextual filter to your new view.

When the filter value is not available you should provide a default value.  Choose the Content ID from URL.

Add the field 'User: Name' but be sure to select the relationship you created earlier as in the graphic.  You may also want to add a link to view the revision or see when the revision was created.

You can optionally sort by "Content revision: Updated date" desc to ensure the block is easy to follow.

The last step is to go to 'admin/build/block' and enable the new block for the appropriate content types.

Lastly, one of my favorite resources for views comes from NodeOne's insanely talented Johan Flak. If you're new to views check out http://nodeone.se/sv/node/20

Also, as @indrock said in his comment, you can also see the history of a node's revisions at http://your-site-url/node/%nid/revisions  This is a much simpler solution and I wish I would have seen it before I went views crazy.


How to get a taxonomy custom image field URL value

In Drupal images are File entities, the target_id is the File ID. So...

$fid = $field->getValue()[0]['target_id']; // File ID,

// Note the [0] in the array. We assume there is always going to be 1 image here.
// If your field allows more than 1 image, you will need to loop through each $field->getValue()

$file = \Drupal\file\Entity\File::load($fid); // load File entity object

$file_url = $file->url(); // get the URL.


Apparently you can't hook into the #process phase, but you can still do a #pre_render, from /Drupal/Core/Render/Renderer.php

// If the default values for this element have not been loaded yet, populate
// them.
if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
  $elements += $this->elementInfo->getInfo($elements['#type']);
}

// Make any final changes to the element before it is rendered. This means
// that the $element or the children can be altered or corrected before the
// element is rendered into the final text.
if (isset($elements['#pre_render'])) {
  foreach ($elements['#pre_render'] as $callable) {
    if (is_string($callable) && strpos($callable, '::') === FALSE) {
      $callable = $this->controllerResolver->getControllerFromDefinition($callable);
    }
    $elements = call_user_func($callable, $elements);
  }
}

For example, to hide the element format of the body field of an article:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymodule_form_pre_render_body';
}

function mymodule_form_pre_render_body(array $element) {
  foreach (Element::children($element) as $key) {
    if ($key == 'body') {
      foreach (Element::children($element[$key]['widget']) as $widget) {
        $element[$key]['widget'][$widget]['format']['#access'] = FALSE;
      }
    }
  }

  return $element;
}


How can I display a list of users who have the same taxonomy term

First of all, thank you very much to @leymannx, @GiorgosK and @prkos, because without the three contributions I wouldn't have achieved the desired result.

These are the steps I have followed to display a list of users who have the same taxonomy term in a page with a specific path pattern: people/staff/A/, people/staff/B/...

As @leymannx initially suggested, in my view a wildcard in the path was missing. So, instead of people/staff/, I have changed it to people/staff/%
As @GiorgosK illustrated with his screenshot, I have included a Relationship field_staff_area: Taxonomy term, and then a Contextual filter on Taxonomy term: Name using this relationship.
Finally, as @prkos precisely described, to show the actual term name in the URL I also needed to configure the Contextual as follows:

a. When the filter value is NOT in the URL: Select the option Display all results for the specified field

b. When the filter value IS in the URL or a default is provided: Select the option Specify validation criteria. Then, select Taxonomy term name in the dropdown, and, finally, check the vocabulary we intend to use (Areas in my case).


How to change the SID of webforms to increment from a new starting number

If it's a Drupal 7 site:

Edit the webform.
Go to the "Form settings" subtab of the Webform
tab.
Scroll down and expand the Advanced Settings section.
There's an exposed field for the Next submission number.

If it's a Drupal 8 site:

Edit the webform.
Go to the "settings" subtab of the Webform
Scroll down and expand the Submission Settings section.
There's an exposed field for the Next submission number.


How do I make my homepage slideshow to fit the page width?

Is your website wider than 960px ? ... I have you looked at online CSS tutorials such as Full Screen Background Image Pure CSS Code, or CSS3 cover property for background-images as mentioned here. I think the CSS Only Technique #1 is more what your looking for in your slideshow's inline images.

Anyways, Google will help you alot here. Views Slideshow ships with basic useable CSS, but it's not themed for everyones needs. It's up to you to tweak its CSS as you need. As an example I've previously given here -- taking a Views slideshow and using only css + jquery and changing it to meet client needs.

Sorry I dont know of a module that just does all the themeing for you, views slideshow does do 99% of the work for you by providing a workable slideshow for your site.


How to access weight of a paragraph in twig?

The weight of a paragraph is not stored in the paragraph itself, but in the host field.
So if you need to get the weight of a paragraph from within the paragraph (e.g. from  within hook_preprocess_paragraph()), you have to go upwards to the parent entity and find your the weight there:
function MYMODULE_preprocess_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $parent = $paragraph->getParentEntity();
  // get all paragraph IDs sorted by weight
  $weights = array_map( function($a) {return $a['target_id'];}, $parent->get($paragraph->get('parent_field_name')->value)->getValue());
  // find the weight of my paragraph ID
  $weight = array_search($paragraph->id(), $weights);
  // ...do stuff with $weight... e.g. assign it to a Twig variable
  // $variables['weight'] = $weight;
}

Please note that the weight is easier to get if you use the paragraph host field template instead (see @4k4's comment below the original question):

Use {{ loop.index0 }} in a field template like
field--field-paragraph.html.twig


Show full list of nodes that reference the node being shown

There are a number of ways to get reverse references. Probably the best option is to use the Views module. The reference module allows to create a reverse relationship in the view. You could do something like this:

With the Views module, create a view of nodes with a page display at path 'myview' ;
Set up your view to display only the title of each node ;
In your view add an argument that matches your node id ;
In your view add a reverse relationship that matches the field that is used to reference content. The name to use for the relationship would be something like field_my_reference_field (reverse)

Save the view, now go to 'myview/1' and you will see all the nodes that reference node 1. You could also get this displayed in a block, or as a field using the ViewField module.

If you don't want to use the Views module, then you can use the Nodereferrer module to achieve this. However in that case you can only get the list as a field - you can't get it as page or a block.


It seems that to get it to work, you should at least add yet another Rules Conditions, in which you compare the value of your field-request-status field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different.

For a variation of your question, with way more details on this, refer to the accepted answer (disclosure: it's mine ...) to "How to send an email using Rules when a node's boolean field is changed?".


What's the minimum amount of code needed to have a field show up in Manage Fields?

You have already created the definition of the field, but you also need to create an actual instance of that field to use it.

$instance = array(
    'field_name' => $your_field_name,
    'entity_type' => 'node',
    'label' => $your_field_label,
    'bundle' => 'node',
  );

field_create_instance($instance);

That plus what you have above should be the minimum you need to get a field to appear in your management screen.

See the field_create_instance() docs for more info about available options.


How would I add a class with the same name as the header?

You'll want to consider doing this in PHP, by overriding the theme/output markup for each Table Header, specifically using the theme_table() override function to add a class attribute to each table header argument.

Simplified code sample

$table_headers = array(
      array(
        'class' => array($node->title), // Adds 'class' HTML attribute.
      ),
      // More code goes here to define the table headers...
    );


Render View or Block not Working in Drupal 7

I hope views will never use hypens. May be you typed wrong.

Views always use underscores.

<?php $view = views_embed_view('carousel', 'carousel-block_1'); print $view; ?>

I think it should be

<?php $view = views_embed_view('carousel', 'carousel_block_1'); print $view; ?>

As per your template.php

<?php $view = views_embed_view('downloads', 'downloads_product_downloads'); print $view;     var_dump($view); ?>


A custom route to an entity form will not pass the entity

You can try using _entity_access

my_profile_form:
....
  requirements:
    _role: 'administrator',
    _entity_access: user.update
   user: \d+

See EntityAccessCheck


How do I use the form hook alt to edit fields of inline entity form?

As per IEF's API docs, you've got:

hook_inline_entity_form_entity_form_alter()

  Perform alterations before an entity form is included in the IEF widget.
  hook_inline_entity_form_reference_form_alter()

  Perform alterations before the reference form is included in the IEF widget.

  The reference form is used to add existing entities through an autocomplete field

hook_inline_entity_form_table_fields_alter()

  Alter the fields used to represent an entity in the IEF table.

  The fields can be either Field API fields or properties defined through hook_entity_property_info().

I think the first would be most appropriate here, probably something like (guessing at the array keys here, they might be different):

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['commerce_price']['#title'] = t('New title.');
  }
}


Unable to use Composer (for Drush) on Bluehost - install problem

Content-type:text-html means your script is running from CGI instead of CLI.

so try to fix your install so that the PHP in the path uses a CLI

One simple way to do is to write php path to php-cli instead of php-cgi.

# .bash_profile
export DRUSH_PHP=/ramdisk/php/54/bin/php54-cli


In D7, I do galleries with the image field and the plup module. Nothing fancy, but at the same time, probably because it is nothing fancy, you automatically get support for colorbox, permissions (standard core or from contrib like Field permissions module), image styles, image captions (using the image caption module) and any other (image-)field related functionality.

So far it has fully satisfied my needs


Mollom captch disappear after using hook form alter for validation

I have done below changed above code:

$form['#validate'] = array('useredit_user_pass_validation');

by

$form['#validate'][] = 'useredit_user_pass_validation';

And it's works !


How to get the human readable content type name in a node template

You should be able to get the human-readable name of the content type (or the "label") by using the following snippet in your node Twig template.

{{ node.type.entity.label }}


If you already have a calculator that you like and the commerce portion is working the way you want it, the best thing to do is probably to change as little as possible. My first thought is to use a simple javascript that looks for the field where commerce stores the order total and copy it into your webform field. In my kickstart staging environment, there is a field called "ajax-item-price". So you could do a jquery one-liner like

$('#name-of-your-webform-field').val($('#ajax-item-price').html());


Views3 date field (filter) treated as string

In the Date project there is submodule called "Date Views". Enable this and the operators you're looking for will appear.


Pass variable from theme page template to commerce-product file

You can use the next function in your theme / module:

function YOURT_HEME_preprocess_commerce_product(&$variables) {
 $variables['product_cta'] = 'Static Text';
}

function YOURT_MODULE_preprocess_commerce_product(&$variables) {
 $variables['product_cta'] = 'Static Text';
}

And show the variables in the commerce-product.html.twig file:

{{ product_cta }}

;)


How do I troubleshoot PrivateTempStore for session data?

I am updated one of my Drupal 7 modules for Drupal 8 and I discovered
  that I need to use PrivateTempStore rather than $_SESSION variables.

The Drupal 8 replacement for $_SESSION is not PrivateTempStore, it is the session object in the request:

Drupal 7:

function mymodule_session_counter_increment() {
  if (!isset($_SESSION['mymodule_count'])) {
    $_SESSION['mymodule_count'] = 0;
  }

  return $_SESSION['mymodule_count']++;
}

Drupal 8:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

See the change record: https://www.drupal.org/node/2380327

For more info see this topic: How do I store the values submitted in a form in the session?


adding input format for CCK fields in drupal

Multi line text fields switch to filtered text. For single line text fields the answer is no.


You don't have to do it the hard way. There is a variable (bool) $is_front that you can use in this case.

<?php if (!$is_front && $breadcrumb) {
  print $breadcrumb;
}
?>

You can read more about page.tpl.php variables here.


You can use the Special menu items module.
In your case you can use the <nolink> placeholder in the menu link path field to show the menu item as text.


How do I get settings in admin/config/people/accounts/fields and admin/config/people/accounts/display into a Feature

For account fields, they will be listed under the 'fields' section just like any other. Just look for the fields that start with 'user-'.

For the view modes, I beleive you can export them to features by using the Dispaly suite module


Programmatically assign a node to an organic group

Assuming Drupal 7, you want to use the og_group function in the API

/**
 * Set an association (e.g. subscribe) an entity to a group.
 *
 * @param $gid
 *   The group ID.
 * @param $values
 *   Array with the information to pass along, until it is processed in
 *   og_entity_presave(). Keys are:
 *   - "entity type": Optional; The entity type (e.g. "node" or "user").
 *     Defaults to 'user'
 *   - "entity" :Optional; The entity to set the association. Defaults to the
 *     current user if the $entity_type property is set to 'user'.
 *   - "state": Optional; The state of the association. Can be:
 *     - OG_STATE_ACTIVE
 *     - OG_STATE_PENDING
 *     - OG_STATE_BLOCKED
 *   - "save": Optional; TRUE if fields value should be saved. Defaults to TRUE.
 *   - "force reload": Optional; Determine if og_load_entity() should be used on
 *     the passed entity. This can be used when you pass an entity that has been
 *     saved yet to the database, but you want to assign it groups. Defaults to TRUE.
 *     // TODO: Adds docs on rest of keys.
 *
 * @return
 *   The entity with the fields updated.
 */
function og_group($gid, $values = array()) { ...

For your code, this would look like:

$values = array('entity type' => 'node', 'entity' => $node, 'state' => OG_STATE_ACTIVE);
og_group($target_group, $values);
node_save($node);


Why does $page['content']['#attached']['js'] works , while $page['#attached']['js'] does not?

For #attached elements to be processed, the array needs to be run through drupal_render(). That never happens for the $page array.

Parts of it are rendered, e.g. in page.tpl.php:

<?php print render($page['content']); ?>

But never the $page array itself.


What's meaning of %contact in this menu path?

All requests on admin/structure/contact/edit/[anything] will be handled by a Drupal form callback, contact_category_edit_form() in contact.admin.in` which returns a form array.

%contact means this parameter will be passed to contact_load() and the result will be pass to contact_category_edit_form() as first argument.

See hook_menu().

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named
  mymodule_abc_load().


You can do this on the theme level.

Your obviously going to want to setup the content using the CMS so will take the form of nodes.

You can then use a process function to determine what content type you are on for applying your script, for example...

function YOURTHEME_preprocess_node($variables) {
   if ($SOME_NODE) {
      // Add JS plugin...
   }
}

You can then create template files for node or specific fields in that node with markup that the plugin can manipulate.

node--[CONTENT_TYPE].tpl.php

To be honest, take Clives advice, use the modules, thats what makes Drupal what it is.


How to create a custom frontpage using page--front.tpl.php and keep theme responsiveness

There are different ways to set up a frontpage in drupal. I think the 2 most used ways are panels or context.

Panels allows you to create a page through drag and drop functinality. Almost every piece of content created in drupal (nodes, views, blocks, custom blocks, ...) can be added to a panel. In addition to that, if you use for example "omega" as a base theme, omega has a couple of default (responsive) build in templates you can use with the panels module.

Context allows you to expose content through conditions. So you can expose a block, view, node,... only on your frontpage. You will have to apply css to make your frontpage responsive though...

Both modules have there advantages and disadvantages, you should check them out and decide which is best for you. I'm certain there are other ways to create a frontpage, but this is how I usually get the job done.


How to display view in all available languages?

You could try to do this with the field language setting in view.
I would try to set this to language neutral.

I have not tested this myself, just my 2 cents ;-)

Look to screenshots for clarification


Which is the correct "code/word" for Language Neutral?

From Drupal constant LANGUAGE_NONE api documentation Und stands for undetermined and in Drupal 8 it is called LANGCODE_NOT_SPECIFIED


How to assign roles to grant permissions to update particular pages?

The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

For way more details about this module, such as how to configure it or available integrations with other modules, refer to my answer to "What are the alternatives for the Organic groups module?".

For this specific question you'd only need 1 Group Type, with 1 Group (of that Group Type) for each set (= collection) of "Specific Pages" (as in your question). BTW, available for either D7 or D8.

Have a look at the Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site". Even though it is about D8 (already), the key concepts of it are the same as in the D7 version. Maybe also review the answers to various questions around here tagged with the group tag.

Some more details about this part of your question:

  Some more details about what I'm trying to do: I do not want to give the permission to whole content type (that is not required). I want a user wise permissions like I have a role named ouroffice-user. Then under this I have a 10 users and I want to allocate different permissions to these 10 users like no. 1 have a permission to update the welcome content and no. 2 have a permission to update the about us page all users belong to single role that ouroffice-user.

Be aware that "roles" in the Group module are different from the typical (standard) roles in Drupal. For more details about the various roles and permissions that can be configured, refer to my answer to "What are the various roles supported by the Group module?".
Assume you create a custom Group role like "content manager". And you allow members with this group role to edit nodes of content type ABC.
From those 10 users (in your comment), those that correspond to your "no 1" should become members of some group (say titled Group no 1), in which they receive access to that Group role "content manager". And assume you create a similar group titled Group no 2, for those that correspond to your "no 2" users.
Using the gnode submodule you assign the nodes such as Welcome to the Group no 1 group and About us is assigned to the Group no 2 group. Note that it doesn't matter what the content types are (if they are the same or not), which is part of the beauty of the Group module.

Done ... really! Give it a try to get the idea ... those who try, love it ... after they get it ...


My php is showing a numeric value for my list field...Why?

Try using $form_state['values'] instead of $form_state['storage'].

Check out the $form_state keys for a bit more information.


Sort 2 views in a page by 2 different ways

Well, as I understand,

You have created a 'page view' and a 'block view'.
Now you want those to be sorted in two different ways.

Well, that's straight forward. But I got a confusion with your statement '..and place them in a page..'. Do you want to mean that you shall place your 'page view' and 'block view' in a another page? If so, then it's not the right approach, as you already have a 'page view' which will have it's own URL or, MENU.

Now, considering the feasible scinario where you want to display 'block view' in the 'page view' where both will have same content but in different sort orders, that you can just manage from drupal view's sort criteria.

Hope it helps


If you look at your code and the output you wrote, it come clearly out, that either:

$message['headers']['From'] = $site_name . ' <' . $site_mail . '>';
$message['from'] = $site_name . ' <' . $site_mail . '>';

is not working at all.

I would get rid of the unnecessary code first, and then trying to modify the working line.


Basic question with respect to Drupal form API

The HTML produced from the first function (the form builder) can be roughly seen checking the code for the theme functions, which are at least two: theme_textfield(), and theme_form(). The exact output can change basing on the theme being used, and third-party modules installed on the site.

For the validation handler, the function that adds the class for form fields with a validation error is _form_set_error(), while the list of the validation error messages are set with form_set_error(), which uses the following snippet:

  if ($message) {
    drupal_set_message($message, 'error');
  }

The messages that are set with drupal_set_message() are then output with theme_status_messages().

Also in this case, the real output depends from the theme being used, and from other modules installed on the Drupal site; both can alter the output used for the rendering.


You could use the Title module to convert your title to a proper field. Following that, your template file should work.


HTML isn't rendering, HTML tags are being printed

This is currently a known bug with the views-view-fields.html.twig template: https://www.drupal.org/node/2363423


How do I spawn additional instances with the same configuration?

Would this workflow be completely incompatible in the case that,
somewhere in the future, one instance would start getting additional
configuration?

If having one instance with divergent configuration is a concern, it is probably worth considering setting it all up as a distribution.
While rolling your own distribution may be overkill, this provides the most "future-proofing" long term because you will have a base configuration in the distribution that can be overridden on a per-site basis if it becomes necessary.
Rough documentation on configuration in distributions
With a distribution, in addition to default configuration, you can even include default content.


How to manage placement of blog articles in omega regions

All content ends up in the Content region.  If you need something different, then I think g you have two options.

One, you can try to use a process function to move the content to a different region withing the zone.  The function would be function mytheme_alpha_process_zone (&$variables) and you would place it in "process/process-zone.inc".  I have no idea if this would actually work, but it is worth a shot.

Two, you could use one of the various techniques for changing layout based on content type.  Personally, I am a fan of Panels, but you could also try Delta (which plays nicely with Omega).


Can authenticaded users publish own content and see only own content?

For node access, you should set permissions based on role.

It is /admin/people/permissions on Drupal 7.

Yo can set who can view, edit , create any of your content type based on role.

For more grained field permission based on role, use Field Permission module


How can I auto-increment available options for an integer field?

I could create the list in a text editor and paste it

You can use Microsoft Excel. on A(1) put 2015 on A(2) put 2016.

Highlight both cells, click on the bottom right corner (you will get a + cursor) and drag down.


Have you tried with a contextual filter with Flags: content ID, and then take the default value of type 'User ID from logged in user'.

It worked for me.


Populate $form_state['values'] with defaults from drupal_get_form()

This is the function I've come up with.

/**
 * Given a form get the default values from it.
 *
 * @param array $defaults
 *   An empty array used to populate the default values.
 * @param array $form
 *   The form returned from drupal_get_form().
 * @param string $parent_key
 *   The key name of the parent.
 */
function get_defaults_from_form(array &$defaults, array $form, $parent_key = '') {
  foreach (element_children($form) as $key) {
    $values = $form[$key];
    if (isset($values['#value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#value'];
      }
    }
    elseif (isset($values['#default_value'])) {
      // Grab defaults at this level.
      if (!isset($defaults[$key])) {
        $defaults[$key] = $values['#default_value'];
      }
      else {
        $defaults[$parent_key . '-' . $key] = $values['#default_value'];
      }
    }
    elseif (is_array($values)) {
      // Go deeper if needed.
      get_defaults_from_form($defaults, $values, $key);
    }
  }
}

Use it like this:

$theme_name = 'seven';
// Load the required file for the form functionality.
$router_item = menu_get_item('admin/appearance/settings/' . $theme_name);
if ($router_item ['include_file']) {
  require_once DRUPAL_ROOT . '/' . $router_item ['include_file'];
}
// Get the form for this theme.
$form = drupal_get_form('system_theme_settings', $theme_name);
// Get the defaults.
defaults = array();
get_defaults_from_form($defaults, $form);
print_r($defaults);


i think you should look at hook_menu_alter()
please Visit:https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu_alter/7


Yes, you can build that type of data model using fieldable entities in Drupal 7.

For example add base "Member" fields to the user entity and use entityreference for the related reference fields on other entities (similar to a foreign key relationship)

The addressfield module provides a good standard address field and associated data structure to hold that info.

In your model, because it appears a "Member" may have many "Member Contact" records, you could perhaps just create a node type for "Member Contact" and add an entity reference field to the relevant "Member".

More info on Drupal 7 Entity API

Lastly, if you want to do it completely custom, you can define your own entity types with hook_entity_info


positioning sticky field using hook_form_alter in drupal 7

This code:

$form['sticky'] = array (
    '#type' => 'checkbox',
    '#title' => 'Top vacature',
    '#default_value' => $form['#node']->sticky,
    '#weight' => -100,
);

works for me just fine. I don't know what's happening in your node edit form, but for me title field had #weight equal to -5, so obviously this item with weight -1 wouldn't show up on top.


How to deal with duplicate table name with db_select left join

You can fetch data with drupal db_select as below code:-

$query= db_select('table1', 'column1');
$query->join('table2', 'column2', 'column1.column=column2.column');

$query=$query->fields('column1',array('column'))
       ->fields('column2',array('column'))
       ->execute()->fetchAll();

For more information on db_select join queries click on this link


How to limit access to content for which the Content Access module doesn't limit access?

I prefer to use Node view permissions for this. As long as all you are trying to do is control access to content types based to user type.


Drupal Commerce AJAX HTTP Error 200 while adding product display

I've seen this error before, you should start from scratch with the latest release candidate for Drupal Commerce, located here: http://drupal.org/node/1786764. This fixes the AJAX bug.


How to create a list of similar nodes in Drupal 7/Views 3

For those upvoting and favoriting, I've got the answer here: https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

It boils down to:

Create a block view
Add Contextual filter -> Content: Nid -> Provide default value -> Content ID from URL
Add Relationship -> Content: Taxonomy terms on node -> specify the appropriate vocabulary
Add Relationship -> Taxonomy term: Content using vocabulary as specified
above -> Check off Require this relationship
Turn on Views aggregation
Assuming you are listing title only, edit the title field to use the Relationship you set up in #4 above.
Add new sort criteria of Content: Nid. In aggregation settings, select Count. Use relationship from #4 and sort descending
Add Contextual filter -> Content: Nid -> Use relationship from #4 -> Provide default value - Content ID from URL -> Scroll down and expand "More" then check "Exclude" to remove current node from the view.


Cannot access empty property in /var/www/clients/client1/web9/web/modules/field/field.attach.inc

This solved my problem: https://drupal.org/node/2051839

Apparently there's something wrong with my image field of a slider, I have no idea that happened during bulk delete of a different content type.


As it turns out this functionality was possible with only one extra module, the Content Access module.

Select the file field on the user account. You can find them at the following path:

/admin/config/people/accounts/fields

Edit the field and under permissions select, custom permissions. You'll need the Content Access module installed for this to work.

Then in permissions you can set custom permissions for the field. To allow a user to upload and not download, you give them only the ability to create or edit their field. You don't give them the permission to view it.


Math Expression in Views: Date functions like now()

If you only want to display the duration between the given date and today in a view then you don't need any calculation.

Just use time ago display option and display your given date with this time ago option.

You will have the result something like this -- 1 year 3 months ago.

You can drop text ago if you don't need.


routing.yml for a custom form not working

Try these steps one by one.

Keep calm.

1) Check you are in the correct domain in your browser

Ugh, I hate when this happens, wrong domain, lol.

2) Check you're uploading or committing to the correct environment

Download the file from the server to see if it indeed changed and make sure you're in the correct environment.

3) Check that your form (SREventListForm.php) is indeed inside the /Form folder.

Simplify your process

4) Back up your current module. Delete all the other routes except for the one that you're trying to dbug.

5) Simplify your form's code. Put some basic code in there.

6) Change your routes path


Site architecture - consistent paths, breadcrumb and menu

I think instead of using Article content type, you should use Book content type.
so you could create a book page named a-page, then a page named b-page and provide it a-page as parent in options below.
Now start adding article-1 and article-2 as child of b-page.

So when you view these pages article-1 or 2 the breadcrumb and will provide the url as site.com/a-page/b-page/article-1

Correct me if i misunderstood the question and do tick right if the answer is right.


How can I increase the number of allowed values on an image field?

You could also change the cardinality setting of your field instance without doing a direct query. The key function would be field_update_instance() and here is an example of how to modify your field: http://sivaji.drupalgardens.com/how-programmatically-change-field-instance-properties


How to use drop tables on target when via drush sql-sync?

Drush sql-sync will not drop tables on the target unless you specify --create-db.  Note that the later drops and recreates the entire database; if you do not have permissions to do this, you could run drush sql-drop on the target first.

There has been a feature request to add this functionality (drop before sync) in the Drush issue queue for years: http://drupal.org/node/716412.  Patches welcome.

Important update:  On Drupal 7, if you drop tables on the target prior to sql-sync, you could run into trouble unless you have http://drupal.org/node/1996004#comment-7419764. This is fixed in 8.x-6.x-dev, but is not part of 5.9, 7.x-5.x-dev or 8.x-6.x-beta1.

Update 2: This fix has now also been committed to 7.x-5.x-dev.


Your '#limit_validation_errors' may be set when the form gets built, not when it's processed.

Hence in your custom *_form() function or a hook_form_alter(); not in *_validation() or *_submit().


Checking view access to a block includes visibility checks. so you can just do this: if ($block->access('view')).

Why do you want this information? block.module has a block.repository service with a getVisibleBlocksPerRegion() which gives you exactly that. a list of visible blocks, grouped by region.


How do I migrate the content of a specific type?

If you can get a CSV of the particular nodes you wish to migrate, then the Feeds module will do exactly what you want.

Worst comes to worst you can generate an RSS feed in Views of the content on your original site and then import using Feeds to the new site from that RSS feed.


How to prevent users uploading images from their system?

There are three major projects for handling media libraries in Drupal 7:

IMCE
Media
Scald

The most basic solution is IMCE. It is simply a file browser for files on your server. I.e. image files are just files on your server and Drupal isn't really aware of them and their meta-data.

The Media module uses in its ver. 2.0 File Entity module to manage media files, making it well aligned with the Drupal framework. It is a tried and tested solution for those who want something more sophisticated than IMCE.

Scald is a relatively new entry for media management. It comes with a very powerful media library sub-module and integrates seamlessly with the CKeditor WYSYWYG editor through drag and drop.  It has a bit steeper learning curve than the two others, but is IMHO well worth the effort.

Whether users are allowed to upload files (as opposed to pulling them from a library) are for all three projects handled by permissions settings.


How can I create a page in Drupal that doesn't appear in the Drupal configuration menu?

You want to use hook_menu() and define a path with the type element set to MENU_CALLBACK. The API docs linked above has an example for the path example/feed.


How to add Email field in Checkout page and sending E-mail in Drupal Commerce?

I believe you are using Customer Profile for asking customer billing and shipping address.

So navigate to
Store->Customer profiles->Profile types->Billing/Shipping Information->Manage fields.
Add one more fields in there for email & make that mandatory.
Add a checkout rules, put condition like "Entity has field" & check your added field.
Add a action "Send mail" and select your added field in TO field & organize your template using tokens of commerce-order.

I hope this will work, though there are other way working around code.


How to count the node of content type for corresponding entity reference field

In Views, under Advanced, Use Aggregation - Yes.

Suppose you have content type A and B. B has entity reference field which refers A.
Now you have already created a view for content type A and added its relationship to B.

Now under Fields, Add a new field of the content type B(suppose body), change the label to Count set its aggregation settings to count.


How do I set access permissions per field?

You're stuck doing this in code, but the Examples module includes a field_permissions example module.


I found the problem. I hardcoded $tid as 1 in my template file.


There are couple of things you could consider before deciding on a particular approach.

Is this data static?

If yes, then you could store data in memory and retrieve as needed. Performance should no longer be an issue as our js libraries are being loaded on demand and I am sure there are many other ways to optimize your code to work for your particular need.

Is this dynamic data stored in db?

You could expose your data using the built in REST solution. Once you have your data exposed. You could just use jQuery REST api's to retrive your data.

Hope this helps.


I don't think that it's possible through the UI. But here is how I would do programmatically:

function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
  }
}

It would make your "Provide a menu link" checkbox as checked automatically.

You can also set all these values if you need to:

EDIT: I'm so sorry I forgot the node_save line in the code. Here is the correction:

function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    $node->menu['enabled'] = 1;
    node_save($node);
  }
}


I have experienced similar kind of problem, I want to show all the group content shared within a group in a view. Just download og_extras module, enable it and you will get amazing blocks and views including the one you wanted.


user_load() and EntityFieldQuery not found when running script via Drush

Ok, WOW, I found the error by running my script with the -d option:

drush -d scr /path/to/my/script.php

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I regranted the privs and my script ran just fine.

The error message about not being able to find a function was a total red herring.


Some modules still don't have a Drupal 9 compatible release. One option is to install the Upgrade Status module on your Drupal 8 site and resolve all compatibility issues before upgrading to Drupal 9 core.
After enabling the module, you can run the compatibility test from the Update Status UI (under Reports - admin/reports/upgrade-status). The test scans modules for the use of deprecated code, among other things. In the case of deprecated code, it'll tell you the file and line number of the problem so you know what needs to be fixed.
Here's a sample of the results when testing the Allowed Formats module, version 8.x-1.2:

As with any other modifications to contributed projects, make sure to use the project's issue queue and patches to modify the project's code.


Drupal Commerce: how to add "Middle name" field to the "Address" pane?

You can add the field under store -> customer profiles -> profile types -> Billing Information -> Manage Fields (Or go to admin/commerce/customer-profiles/types/billing/fields)

You can add any additional fields there. You can't add any fields directly to customer_commerce_address, but if you add any fields under the Billing Information they will show up during checkout.


How do I increase the character limit for the default "Fixed value" of a contextual filter?

Why don't you write a small code snippet and pass contextual filters using hook_views_pre_view(), that allows altering a view at the very beginning of processing a preview.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'YOUR_VIEW_MACHINE_NAME' && $display_id == 'page_1') {
    $nids= get_nids(); //write a custom function to get nids.
    $args[] = implode('+', $nids);
  }
}


Drush and database credentials from external sources

As you can see, drush is run from command line interface, so it uses cli/php.ini and not regular one. If you feel like keeping password and username in ini file, you need to make sure there are synchronized between WWW and CLI php.ini files.


How to remove a theme's default menu class from a specific menu?

You can remove all unwanted classes and add your own classes using the code below, Its for a rough idea, use dpm or any debugger to locate exact tool

function THEME_menu_link(array $variables) {
  //unset all the classes
  unset($variables['element']['#attributes']['class']);

  $element = $variables['element'];

  if($variables['element']['#attributes'])

  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}


CAPTCHA session reuse attack detected error message when form is submitted

I had the same problem because I have an ajax file upload on the form. The solution is to patch the captcha module with the patch found here http://drupal.org/node/918856#comment-6353912 .
You just need to download the patch and put it in the same folder and run in command line:

patch < captcha-patch-10022012.patch

if using git, you can just use :

git apply --directory=your/module/derectory captcha-patch-10022012.patch


Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params

You can alter the path by adding a class that implements the InboundPathProcessorInterface

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class HelloPathProcessor implements InboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/hello/') === 0) {
      $names = preg_replace('|^\/hello\/|', '', $path);
      $names = str_replace('/',':', $names);
      return "/hello/$names";
    }
    return $path;
  }

}

This way the router will interpret the path /hello/bob/bobby as /hello/bob:bobby and you will get the parameters separated by : (or any other character that won't conflict with the parameters) in your controller.

You will also need to register the class as a service in mymodule.services.yml (make sure the priority is set higher than 200)

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\HelloPathProcessor
    tags:
      - { name: path_processor_inbound, priority: 250 }


Rather than using a filter like "current user" which would display uniquely for the logged in user, you will need to attach the view to each members profile with a "contextual filter" (under advanced on the right hand side). Use "User: Uid", then select"Provide default value" and "User ID from URL".

The above will mean that each view is unique to the user profile and any user can see another users list by going to their profile page.


How to get Media entity image (Entity Reference Field) URL in TWIG theme

If this entity referenced image is controlled by Media, then you should let normal rendering occur:

{{ content.field_image2 }}

The rendering is then controlled by the field formatter, which will look to a display mode in Media, which is not dissimilar from Node display modes (default, teaser, etc).

Your filename would be something like:

media--media-bundle--display-mode.html.twig
media--media-bundle.html.twig

The first one is most specific, the second one would be the base for that media entity wherever it is used. I usually opt for the first one.

It is in this specific twig template where that code should live. The markup should be sourced there, instead of the referencing entity, in my opinion.

You could also do some preprocessing to solve this as well. Here is an example:

/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle == 'landing_page' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('landing_page_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

Then in my respective template...

<div{{ attributes.addClass(classes) }} style="background-image: url('{{ hero_image }}');"></div>

Alternatively, you can preprocess the media entity:

/**
 * Prepares variables for media templates.
 *
 * Default template: media.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - media: An individual media for display.
 */
function mytheme_preprocess_media(&$variables) {
  /** @var \Drupal\media_entity\MediaInterface $media */
  $media = $variables['elements']['#media'];

  $variables['media'] = $media;
  $variables['name'] = $media->label();

  // Helpful $content variable for templates.
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }

  $variables['attributes']['class'][] = 'media';
  $variables['attributes']['class'][] = Html::getClass('media-' . $media->bundle());

  if (!$media->isPublished()) {
    $variables['attributes']['class'][] = 'unpublished';
  }

  if ($variables['elements']['#view_mode']) {
    $variables['attributes']['class'][] = Html::getClass('view-mode-' . $variables['elements']['#view_mode']);

    if ($variables['elements']['#view_mode'] == 'hero') {
      $variables['hero_image'] = ImageStyle::load('hero')->buildUrl($media->field_image->entity->getFileUri());
    }
  }
}


How to put the Bootswatch theme locally?

The theme can not read the SCSS file. You have to covert them to CSS. To do this, follow the following instruction.

Create a new SCSS(Let's name it the "custom.scss") and import all the SCSS to this file. and convert it to CSS."
In the new "custom.scss" file, import the "_bootswatch.scss" and "_variables.scss". To do this, use the @import function. Add the following code to your "custom.scss".
@import 'bootswatch', 'variables';

Use a SCSS compiler to covert the SCSS to CSS.
Covert the "custom.scss" file to "custom.css", then minify the file to "custom.min.css".

On your "bootstrap_subtheme_front_office.libraries.yml" file, include the "custom.min.css". Add the following code below the "css/style.min.css: {}"
css/custom.min.css: {}


When you go to the view, open the advanced section - near the bottom is a link called theme: information.

This lists all the potential files you COULD adjust to tweak the output of the view. Some are very generic, and some specific to the view you are looking at - in general if you only want to theme the one view, choose a file name with your specific view name in it.
Exactly which file(s) need to adjusted depends on the kind of tweaking you want to accomplish.
These files (i.e. views-view-profile--page.tpl.php ) would then be placed in the theme directory (i.e. /sites/all/themes/zen) unless the theme uses a sub-directory for template files - a simple look through should tell you where they are found for each theme.


Display Suite - code field retrieve the first value in a multivalue field?

When you have a multivalue field, you have also a # on the format column. It represents all images. If you want to show only one or two images, you must write 1 or 2 in the box.

Good luck


Add state permissions and allow state changes

As far as I'm aware, there's no way to give permission to manage a specific state, nor workflow for that matter.

The only permission to cover these is administer workflows and it covers all workflows.

You can see this by looking the content_moderation.routing.yml

content_moderation.workflow_type_edit_form:
path: '/admin/config/workflow/workflows/manage/{workflow}/type/{entity_type_id}'
defaults:
  _form: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm'
  _title_callback: '\Drupal\content_moderation\Form\ContentModerationConfigureEntityTypesForm::getTitle'
requirements:
  _permission: 'administer workflows'

EDIT
That is with the default permissions.


Error trying to connect to database when installing new site on localhost

Thanks for the responses everyone.  I ended up getting so frustrated I uninstalled Aquia Dev Desktop and then re-installed a newer version of it.  It seems to have solved the problem because I haven't run into this issue since.


Why am I getting this error for the schema I define in my module?

I've managed to fix it. I've altered 2 things from my original schema, the first issue was that Drupal 7 no longer supports 'type' => 'datetime', instead use 'mysql_type' => 'datetime'. The second was 'unique keys' => array('id'), I removed this and everything works correctly.
Solution...
$schema['table_name'] = array(
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'nid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'oid' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            ),
            'start_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'end_time' => array(
                'type' => 'int',
                'mysql_type' => 'datetime',
                'size' => 'normal',
                'not null' => false
            ),
            'duration' => array(
                'type' => 'int',
                'unsigned' => true,
                'not null' => true,
                'length' => 11
            )
        ),
        'primary key' => array('id'),
        'mysql_engine' => 'InnoDB'
    );


Why would the body field's language not save as the same language as the node?

By default, drupal sets 'und' as the field language, that is LANGUAGE_NONE. So, when you print_r($node), you will see a field with something like $node->field_name['und'][0]['value']

Now, when you enable translation on this field, the 'und' will get replaced by the language code and somehow the $node structure would look like $node->field_name['en'][0]['value'] where 'en' is the language code. Your body field will now have 'en' as the language and won't be empty anymore when rendered

For your question above :

  I am having a problem where the user is creating new nodes and entering body text, but setting the nodes to "language neutral" for the language. Yet when it saves the node the body field's language gets set to English. Why would this be happening? What would cause this?

Check default language of your site, if its set to English, then probably Language Neutral will take your site's default language.


remove drupal admin menu from actual site

You can remove the toolbar from the "normal" part of you're site by unsetting its entry in the $page array using hook_page_alter. You can do this in either a module or a theme.

function mymodule_page_alter(&$page) {
  unset($page['page_top']['toolbar']);
}


How to check validity of one time login url by Drupal 7 Services module?

Note: I have not tried this solution myself, but think it should work.

Some concepts about one time login URL

You cannot just visit the URL (or even request it via a service, or any other request like curl or wget) to check if it is valid. As the name it is for one time use only.
It is valid for 24 hours from time it is generated.

These couple of things need to be taken into consideration while validating the login URL.

The URL where the check (and login) of a user happens is user/reset/%/%/%, where the dynamic arguments are in order : user id, timestamp of the one time login url creation, and the hash of the password.

To implement your solution, I suggest you to create a custom service endpoint and implement the logic which is implemented in user_pass_reset.
You can just skip the part where the function actually logs the user in.


How to autoload, so composer packages work correctly?

Call to undefined function PHPEncryptData\mcrypt_get_key_size()

mcrypt is a php function of the mcrypt extension. Autloading is working perfectly fine, or you wouldn't get that far. You're simply missing that extension.

The error message is a bit confusing because PHP always looks for functions in the global namespace and in the namespace the code is in and then prints the error for the one with the namespace.


Using a PHP class defined in the module file inside the implementation of hook_install()

No need, it's already loaded. Check http://api.drupal.org/api/drupal/includes--module.inc/function/module_enable/7

if ($existing->status == 0) {
  // Load the module's code.
  drupal_load('module', $module);
  module_load_install($module);
  // …
}