Access field on relation from rule I am using the Drupal 7 Rules and Relation modules. I have a relation between a user entity and a node content type (membership). The relation has an added field (relationship type). I was able to define a rule to create a new relation entity and set the relationship type field when creating a new membership node.

Now I am trying to write a rule with a condition that checks the value of the relationship type field at the time some event referencing a user or membership entity fires. The Relation module provides actions to fetch endpoint entities, but I cannot find a way to fetch the relation entity itself. What I'm searching for is a way to load that relation entity, tell Rules the relation type to expect, then be able to access the field (relationship type) on that relation.

Thanks in advance for any advise.

I believe Rules lets you write custom php. Relation has an API. You can query for a relation directly using relation_load and giving it a relation_id. You can also search for a relation by supplying 1 endpoint and the type of relation you are looking for (or empty to return all relations of that endpoint, using the relation_query() function.

/**
 * Returns a query object to find related entities.
 *
 * @param $entity_type
 *   (optional) The entity type of one of the endpoints.
 * @param $entity_id
 *   (optional) The entity id of one of the endpoints. Can also be an array of
 *   entity IDs.
 * @param $r_index
 *   (optional) The index of the search entity in the relation to be found
 *   (0 = source, 1 = target).
 *
 * @return RelationQuery
 *   The query object itself.
 */
function relation_query($entity_type = NULL, $entity_id = NULL, $r_index = NULL) {
  return new RelationQuery($entity_type, $entity_id, $r_index);
}

The RelationQuery is simply a small custom extension of the core EntityFieldQuery. You can use relation_query() and pass it a UID and a NID as the endpoints -- relation_query will return the Relation ids (RIDs) for those objects. You can inspect the relations further by calling relation_load($rid).

You can then do whatever you need to with the relation(s). A small example. In my app students have surveys assigned to them to complete; using Relations. When they're done with a survey I want to change a flag on the Relation that the survey is completed ...

function _mark_student_survey_as_completed($user_id, $survey_id) {
  // using relation query we want to search for a $user and a
  // specific survey they should have been assigned. Many arguments
  // to relation_query are optional, you can more results; like
  // if you just supply a UID, you'll get all relations that use
  // that UID as an endpoint.
  $relation_ids = relation_query('user', $user_id)
      ->related('custom_survey',$survey_id)
      ->execute();
  $relations = entity_load('relation', array_keys($relation_ids));
  if (count($relations) == 1) {
    $relation = reset($relations);
    // survey_is_completed is an attached field, to the Relation;
    // not an endpoint.
    $relation->survey_is_completed[LANGUAGE_NONE][0]['value'] = 1;
    // Save our field change on the parent relation.
    relation_save($relation);
  } else {
    watchdog('survey_check', 'Duplicate Survey!'.$user_id.'::'.$survey_id.'::'.print_r(array_keys($relation_ids), TRUE), WATCHDOG_ERROR);
 }

Lastly, since RelationQuery is just a class ... I've seen people extend it to make custom "relation logic" more easy, or even Views-like listing easily. Look at this blog post for such ideas (not my blog post):
http://www.phase2technology.com/blog/building-energy-gov-without-views/


Send php variable to js in drupal 8 block I am trying to attach js files attach_library() inside a custom block.

However, I can neither add the libraries via block nor add a library. attach_library() does not accept variables like drupal_add_js.

Any ideas on A) how to send a php variable in the block::build() function and how to attach the library through the build() instead of the twig templates?

This is from the documentation how to attach libraries to a render array of a block plugin and send php variables to js:

  Attaching to a render array of a Block Plugin

  To give another example of attaching a library to a render array, If
  you are building a block plugin in your module, you can attach the
  libraries to the render array in the build() function of your class
  extending the BlockBase class (as of Drupal 8 beta 6).

return array(
      '#theme' => 'your_module_theme_id',
      '#someVariable' => $some_variable,
      '#attached' => array(
        'library' =>  array(
          'your_module/library_name'
        ),
      ),
    );

  Attaching configurable JavaScript

  In some cases, you may want to add JavaScript to a page that depends
  on some computed PHP information.

  In this case, create a JavaScript file, define and attach a library
  just like before, but also attach JavaScript settings and have that
  JavaScript file read those settings, via drupalSettings (the successor
  to Drupal 7's Drupal.settings). However, to make drupalSettings
  available to our JavaScript file, we have to do the same work as we
  had to do to make jQuery available: we have to declare a dependency on
  it.

  So that then becomes:

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

and

$build['#attached']['library'][] = 'fluffiness/cuddly-slider';
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'bar';

https://www.drupal.org/developing/api/8/assets


How to add Follow Me link inside content type in Drupal 7 My project contains two content types:- Professor and Lecturer.
Here the users are student so students can log in using their own credentials.

Now I want to show up a button/link with Text "Follow Me" in Professor & Lecturer Content Type.When User/student will select the link/button then the corresponding Lecturer/Professor will be attached to the student profile and will be visible inside their home page. Similarly that student will be visible in Teacher/Lecturer.

I look at The "Relation" Module in Drupal 7 but my use case don't need to display too many things in the widget. There should be a simple button/link which relate user and content type.

You should try the Flag module for this. It should solve your purpose.

  Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.


How to create arguments in path with regular page node instead of module, yet pass them to a module I know how to create a URL with hook_menu() in a module, but is it possible outside a module?
Here's what I'm needing/asking:
My front-end guy wants to create a page as a node using a Content Type via the Content menu. The URL for this content type needs to be something like www.somesite.com/some-page/arg1/arg2. Can this be done without a module defining the route with hook_menu() in a module?
If so, in my module that needs to do the work, it needs to collect these args and use them to insert data into the DB.
Is it possible for him to create a path with arguments that I can get? If so, what would be the best way to get these args to my module that is going to work on the backend.
I could do this all day with hook_menu() in module, but the front-end guy seems adamant that he can create a node and get the args from it's path. I don't understand how he can do that.
Thanks in advance.
Cy

https://www.drupal.org/project/pathauto
will help you on your quest ... to do this make custom fields to collect the arguments then use tokens to replace them...
Edit:
but if your developer is using the front end to create content (nodes) its easy to create path arguments ...
my idea was to make the fields to help generate the "path" ...
then in your module you have to simply load the node then access the fields .. sure there is more ways to do this like look in to the path and explode out the "/" then use them but way easier just to get from the loaded node object.
other than that can you please up date your question to be more clear


User Login Destination | to his first submission | Webforms i have a career form built with webforms ; I need the users to go back to their first submission when they come back to the site again .

Login Destinations | can help me with that . but it will send only to a specific URL . where in my case every user have its own submission and i want him to return back to it in Edit mode when he/she logins again .

any clues /
thanks

You can achieve using hook_user_login() function.

function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location.
  // Get the logic and fetch where do you want to redirect.
  // Here i am redirecting to node 34. You can fetch your own webform submission path
  // where do you want to redirect.
  // Fetch the submission of done by the current users. by using http://api.drupalize.me/api/drupal/function/webform_get_submissions/7 function
  $redirection = 'node/34';

// Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}


Count only published nodes with taxonomy term I have implemented a view according to this question: Views and node count for taxonomy terms

But the view also counts the unpublished content.

How can I modify the view to count only published content?

You need to add a Filter Criteria on the view, and choose Content: Published as the criteria, and Yes as the value. This also needs to use the (node) relationship.

See /* Filter criterion: Content: Published */ on this code. Or import it and look under "Filter Criteria"

$view = new view;
$view->name = 'Taxtest';
$view->description = 'Displays node count values for terms';
$view->tag = '';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'term_node_count';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '100';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['expose']['items_per_page_options_all'] = 0;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'name' => 'name',
  'nid' => 'nid',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
);
$handler->display->display_options['style_options']['override'] = 1;
$handler->display->display_options['style_options']['sticky'] = 0;
/* Relationship: Taxonomy term: Content with term */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'taxonomy_index';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = 0;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['name']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['name']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['name']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['name']['alter']['trim'] = 0;
$handler->display->display_options['fields']['name']['alter']['html'] = 0;
$handler->display->display_options['fields']['name']['element_label_colon'] = 1;
$handler->display->display_options['fields']['name']['element_default_classes'] = 1;
$handler->display->display_options['fields']['name']['hide_empty'] = 0;
$handler->display->display_options['fields']['name']['empty_zero'] = 0;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = 1;
/* Field: COUNT(Content: Nid) */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
$handler->display->display_options['fields']['nid']['relationship'] = 'nid';
$handler->display->display_options['fields']['nid']['group_type'] = 'count';
$handler->display->display_options['fields']['nid']['label'] = 'Count';
$handler->display->display_options['fields']['nid']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['nid']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['nid']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['nid']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['nid']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['nid']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['nid']['alter']['trim'] = 0;
$handler->display->display_options['fields']['nid']['alter']['html'] = 0;
$handler->display->display_options['fields']['nid']['element_label_colon'] = 1;
$handler->display->display_options['fields']['nid']['element_default_classes'] = 1;
$handler->display->display_options['fields']['nid']['hide_empty'] = 0;
$handler->display->display_options['fields']['nid']['empty_zero'] = 0;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['relationship'] = 'nid';
$handler->display->display_options['filters']['status']['value'] = '1';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');


How to show different content for various roles for the same url? we have a use case whereby 6-7 types of user roles can access the same nodes (lots of them) and see different content based on roles.

For example a user with role A accesses sitename.com/faq and sees a particular content.
However when a user with role B accesses sitename/faq that they see some different content as based on their role. (Please note that we are not merely talking about translation here)

How would I get about getting this setup? I know that if we had 2-3 nodes that required such access that I could check it programmatically however in this case it is a lot of nodes and doing that would be problematic.

Any tips or modules that you can think off that would help me with that?

Many thanks

Sounds like either the Content Access module, the ACL module, (maybe) the Nodeaccess module, or possibly even a combination thereof, would be a good place to start.


Same drupal webform is showing error messages in two different way, on different palces in the same website I am using drupal webform for my website, I am using single Contact Us form on multiple places in my website.

But the problem is on different places the way of showing error message is different, its not uniform through out the website.

Here is the image that shows the first way that how error messages comes-

and here is the image that shows the second way to show error messages-

I want first type of error messages which is in red box.

Please help me that how can I achieve this.

Thanks

Try to use Webform Validation module. I hope through this you can solve your issue.

  This module adds an extra tab to each webform node, allowing you to
  specify validation rules for your webform components. You can create
  one or more of the predefined validation rules, and select which
  webform component(s) should be validated against those. By using the
  hooks provided by this module, you can also define your own validation
  rules in your own modules.


drupal 6: passing multiple arguments to a view using code I have a template file that uses execute_display to pass arguments to a view and this works great for single arguments. However, one of my arguments is a taxonomy id and the form allows the user to choose multiple term ids.

I've set the view to accept multiple arguments in the form 1+2+3 etc. But when i pass execute_display an array array containing arguments in the form of term1+term2 it doesn't work.

Any ideas how to pass multiple ids as one argument using code

the array must be array in "execute" then this array in array - in "preview", e.g

$args = array($arg1, $arg2, $arg3);
$view2->execute('block_1', $args);
print  $view2->preview('block_1', array($args));


Get the list of available services Is there a way to get the list of the available services in  Drupal 8?

The module Devel provides a searchable list (/devel/container/service).

For the command line use Drupal Console:

drupal debug:container


Wordpress Migrate Inline Images looking in wrong folder I've recently used the Wordpress Migration module to bring over a lot of posts into drupal. The images get moved, and the text comes in fine. The problem is when the images get brought over they are put in one location on the server, but the inline media tags tell them to use view_mode: media_large the images don't show in the post because it's looking in the '/sites/default/files/styles/large/public' folder instead of where they actually got imported to. How do I either import these posts so that the images go there, or so that the media tags that are created don't look in the large folder but where the files actually are?

Turns out the styles folder inside /sites/default/files was the only folder in there that was not writable by the server so it put the images elsewhere. I rolled back the wordpress import, fixed the permissions, and ran the import again. Everything seems to be good now.


Devel and XHProf configuration! I have installed Devel and XHprof to profile (kind of performance analysis) my website . Configured everything but i am confused with this setting

  XHProf URL: Path to the publically accessible xhprof_html - required to display profiler reports. You will need to set this up
  outside Drupal, for example at http://xhprof.localhost/xhprof_html

my drupal installation is in inside /www/
please help

You need to set up a virtual host on your server and put the xhprof front-end HTML files on it (the ones that come with the the xhprof download). Give the host an address (e.g. http://xhprof.localhost/xhprof_html as suggested), then give that path to Devel.

Then you should get the link at the bottom of each page to check the profiling information for that request.


How to hide the configure slider in MD Slider? I've installed the MD Slider, but I would like to remove the Edit Slider and Configure Slider links in the administrator role. What function should I use to remove that?

You probably would need to uncheck the permissions of the MD Slider to administrator. You can do this by going to the admin/people/permissions.


Why do all my products (in Ubercart) get taxes applied after upgrading my Rules module? I am using Drupal 7 and Ubercart (version 3). I try to add TAX to only certain items which has a particular Taxonomy Term Selected.

This functionality worked fine in previous version of Rules 7-2.8  But now for some reason all rules conditions come back as true and VAT is applied on all products.

I have tried downloading the older version same issue.

How to Replicate:

Configuration > Tax > Editing Condition Set VAT
Entity has field (Parameter order:product:0:node) has Field Product_Type
Data Comparison (Parameter order:product:0:node:Product_Type) one of Books, Hardware

So my real problem is that somehow all the products which do not have these terms selected are getting Taxes.

Any suggestions?

Your comment about Rules version 7.x-2.3 rings a bell: I'm about sure that that is actually causing your problem. Refer to these issues for some more details:

Upgrading Rules from 2.3 to 2.6 brings white screen.
<7.x-2.4 breaks site with "Fatal error: Class 'RulesEventHandlerEntityBundle' not found".

I've hit a similar issue some months ago (in an "old D7 site where Rules wasn't upgraded yet from a pre-7.x-2.3 version). After I upgraded to the most recent Rules version (7.x-2.9) my site was broken also. I don't remember what the actual error was, but I narrowed it down to this Rules upgrade issue.

The way I got around it was like so:

Uninstall the 7.x-2.9 version of Rules (that I had ust upgraded to).
Re-install (from scratch) the 7.x-2.9 version of Rules.

That solved "my" issue. And I'm pretty sure it will also solve yours ... wanna try it? Attention: backup any of your custom rules first. E.g via an "export" of those custom rules (before uninstall), and "import" again afterwards (after you upgraded).

PS: just in case anybody else ever looks at this answer before upgrading from a pre-7.x-2.4 version of Rules, you can avoid the above surprises when upgrading Rules to something like 7.x-2.9 by:

first uninstalling the old version (after export of custom rules),
and then installing the newest Rules version (and then import of custom rules).


How to set value programmatically for mobile number module's field using entity wrappers? how do I set value for the mobile_number field using entity wrappers?
Currently, this field is attached to an entity and I'm trying as below.

$entity_type = 'mp_customer';
$entity = entity_create($entity_type, array('type' => 'mp_customer'));
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$wrapper->field_phone = "0777123456";

This gives an PDO Exception .... field_phone_value cannot be null....

Adding more
This field needs more data to store in field_data_field_phone,
those are:
{field_phone_value}
{field_phone_country}
{field_phone_local_number}
{field_phone_verified}
{field_phone_tfa}

This field was created using this module : https://www.drupal.org/project/mobile_number

To store a value with entity wrapper set() should be used. Please read https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers

So your code $wrapper->field_phone = "0777123456"; would be $wrapper->field_phone->set('0777123456'); if the field structure required just a simple string.

However, according to the error message, it is not a string as it requires additional values for {field_phone_value} {field_phone_country} {field_phone_local_number} {field_phone_verified} {field_phone_tfa}.

So to make sure I would first figure out its structure. You could do so, for example, saving any value via UI and then outputting the value of respecting variable using dpm(). However, most probably its an array and you could give a try to:

$phone = array(
  'field_phone_value' => '0777123456',
  'field_phone_country' => 'US',
  'field_phone_local_number' => 'some value',
  'field_phone_verified' => 'some value',
  'field_phone_tfa' => 'some value'
);
$wrapper->field_phone->set($phone);


How to switch to other site's database in multisite enviroment? The use case is the following:

I am in default site. I want to get the connection of the "preview" site instance database from the default site code. How is it possible?

I tried Database::setActiveConnection('preview')), but it didn't help. setActiveConnection method seems to choose only from your site settings.php.

* WORKAROUND *

If you want to handle multiple database under one site instance then you should declare their connection array under your site's settings.php!

You can't.

Multi-site is only about sharing the code in the file system. Unless you actually add the database connections to the specific settings.php, Drupal doesn't even know that there are other sites.

Functionally, once the bootstrap and site selection happened, there is 0 difference between two different installations and a multi-site.

IMHO, there are more downsides than advantages with multi-sites these days, you can use git and e.g. different branches to share code between multiple sites at least as well, with way more flexibility and options for updating and customizing them.


Dynamically filling up fields of a node in Drupal We have a content type named "Person", which has fields as Full Name, Age, Address etc.

There are thousands of people entries on the site. We are using Views to sort out people's list on different pages as per need.

Lately, there has been a requirement that we need to sort the list of people by Last Name. But the problem is that there's no last name field as there's only "Full Name" field of the person in the site.

I am using views to sort the results in the pages and I am not sure how to sort the results by last name. Is there any way I can achieve this?

May be I can create a field as "Last Name" in the content field but is there a way I can dynamically fill in the Last Name by extracting Last word from Full Name?

May be through someway in SQL?

Any idea or assistance would be highly appreciated.

Thanks.

Here is my way of doing it:

Create a Computed Field to manipulate the substring (Last Name) and store it as a field

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code.

Use Computed Field Tools to bulk update the value for the existing nodes

  The Computed Field module only updates its computed values on saves or
  on load (if no computed value is computed yet). This is not optimal
  when using computed values in lists etc., or if you should wish to
  change the logic in the computed field.

Use this Computed Field as a sort criteria in Views.


How to change the default selection in views filter? Content type has two fields: Property type and bedroom.
I created a view where above fields were exposed to visitors.
When I visit my site, I see -Any - is the default value for the both fields. First field is the property type and the second field is the bedroom field.

Property type field :

Bedroom field:

How can I replace the default value -Any - by the corresponding field label? For example, for property type field, I like to see Property Type as the default value and for the bedroom field, I like to see bedroom as the default value in the drop down list.

You can change it with custom code in a module or overriding your theme.
You can also use the Better Exposed Filters module. Change the Exposed form options in your Views to use that module option. Then in the further settings you'll be able to override what the options are called for each filter separately.
Drupal 7 also had Views Advanced Labels.

Use this field to rewrite the filter options displayed. Use the format of current_text|replacement_text, one replacement per line. For example:
 Current|Replacement
 On|Yes
 Off|No

Leave the replacement text blank to remove an option altogether.


How to bypass menu link access permission I have added some links from the admin page to a menu, but these links are not displayed in anonymous.
Certainly anonymous doesn't have access permission to the links, but I want to display the menu.
is there a hook or something that bypass access permission?
Thank you.

You could create your menu links as /user/login?destination=/my-path and that will mean authenticated users would get taken to /user/login but then instantly redirection to /my-path because they're already logged in

Anonymous users will see the menu links and be taken to the login page if they tried to click them


How to show/hide "printer-friendly version" link according to workflow states? There's a review content type on my site with a workflow: I use 'draft' and 'completed' workflow states.

I'd like to create a printer-friendly and pdf-version of 'finished' reviews only, so I'd like to hide the links generated by Print module in any other case.
I tried to modify MYTHEME__preprocess_node() to achive this with this code, but it didn't work:

if($vars['field_review_workflow'][0]['value'] == '13'){ //sid of 'finished' state
  show($vars['elements']['links']['print_html']);
}else{
  hide($vars['elements']['links']['print_html']);
}

How could I do it properly?

One way of doing it is by using hook_node_view_alter(). For example, you would put the following code in a custom module called hideprint (see many tutorials online on how to create a custom module). Be sure to dpm() the array $build when you are testing the module to correctly check the value of field_review_workflow.

function hideprint_node_view_alter(&$build) {
  if ($build['field_review_workflow'][0]['#value'] == TYPE_VALUE_FOR_NOT_FINISHED){
    hide($build['links']['print_html']);
    hide($build['links']['print_pdf']);
  }
}


How to correct my rule to prevent duplicate taxonomy terms to be created? This is a followup of my question at How to create a rule to combine the terms of 2 fields to create a new term and store it in a 3rd field?.

How can I prevent that each time a node is viewed, it creates duplicate taxonomy terms, as shown in this example:

Any suggestions?

I think the Rules condition, URL Alias Exists is perfect for this scenario if put into two rules, one for yes and one for no. Taxonomy terms will have an alias once created so it's easy to check if /taxonomy_vocabulary/[A][B] exists before doing anything with C.

When the node is created or updated, the rules check for A and B added together to see if that AB taxonomy term already exists since every taxonomy term has an alias. If it already exists (yes), the rule fetches it and uses it and if not (no), it creates it.

For example, the first time a node is created or updated with A: New and B: York, "/cities/newyork" wouldn't exist so we create it. The next time we use A: New and B: York, the rule finds the existing term and fetches it.

The below assumes a single-language taxonomy vocabulary. The nodes can be multi-lingual.

PSUEDO-RULES

Rule 1 - Taxonomy C exists
Events: Node is saved / Node is updated
Condition: URL Alias Exists > Use replacement patterns to join A and B in Value field
              eg. taxonomy/[a][b]
Action: Create variable > [a][b]
Action: Fetch Entity by Property > Taxonomy Term > Name > Created Variable
Action: Set Data Value > C: Fetched Entity:0

Rule 2 - Taxonomy C doesn't exist yet
Events: Node is saved / Node is updated
Condition: NOT URL Alias Exists > Use replacement patterns to join A and B in Value field
Action: Create entity > Taxonomy Term > "AB" using replacement patterns
              (not the drop-down list!)
Action: Set Data Value > C: Created Entity

Rules exports
To test these rules, you'll need a Drupal install with Articles, Tags and no Pathauto messing with the urls.
Add three term reference fields to Article for the Tags Vocabulary.

Machine Names
field_tax_tags_a
field_tax_tags_b
field_tax_tags_c

Rule 1 - AB Term exists so fetch it

{ "rules_exists" : {
    "LABEL" : "Exists",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "[node:field-tax-tags-a][node:field-tax-tags-b]"
          },
          "PROVIDE" : { "variable_added" : { "variable_added" : "Added variable" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "name",
            "value" : [ "variable-added" ],
            "limit" : "1"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-fetched:0" ] } }
    ]
  }
}

Rule 2 - AB Term doesn't exist so create it

{ "rules_doesn_t_exist" : {
    "LABEL" : "Doesn\u0027t exist",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "path" ],
    "ON" : {
      "node_insert--article" : { "bundle" : "article" },
      "node_update--article" : { "bundle" : "article" }
    },
    "IF" : [
      { "NOT path_alias_exists" : { "alias" : "tags\/[node:field-tax-tags-a][node:field-tax-tags-b]" } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "taxonomy_term",
            "param_name" : "[node:field-tax-tags-a][node:field-tax-tags-b]",
            "param_vocabulary" : "tags"
          },
          "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "node:field-tax-tags-c" ], "value" : [ "entity-created" ] } }
    ]
  }
}

After that, create and edit some articles only using A and B. C matches and instead of duplicating, will fetch the existing term.


How do I migrate while content is still created on production site? I've written a bunch of migration script to migrate a site from Drupal 6 to Drupal 8.

On the development server I just ran a sample of each content type migration to test everything was OK while new content was still being created on production server on  a daily basis by redactors.

During the validation time by the project team (which could take several weeks), I'll run migration everyday on a fresh database dump from production server. During that time also, the project team will need to create specific new content (content that is not being migrated) for different purposes, like testing brand new content type or creating specific base pages needed by the new site templates.

Since the migration process keeps the original ID, I need to find a way for new content to be created without taking the node ID  from a node created on the production server. I’ve not been able to find any information about that case (which is quite a common case, I think) in the Drupal migration literature.

My first idea would be to change auto_increment value in relevant tables adding (let’s say) 100.000 to the current value, that way there wouldn’t be any collision between newly created content and the ones created the day before on production server. A brief look to the Drupal 8 database schema gave me the following tables and fields to alter:

file_managed => fid
node => nid
node_revision => vid
url_alias => pid

I am not sure the file managed fid field is kept during migration process; the same is true for the URL alias pid field since the link is made on the source field.

Do you think it would be enough to alter only the node and node_revision tables?

I also noticed a sequences table with a single value field with only one row. As far as I've read about this table, I've not really been able to figure out what it is used for. Maybe some of you can explain me and tell me if it's important regarding my issue.

Do you this is a correct approach? Are there other tables that could need to be altered?

Migrate, as shipped with Drupal 8, has two components:

The migrate module. This provides a very flexible API.
The migrate_drupal module. This provides Drupal 6 / 7 to 8 migrations (the migrations themselves has been scattered into the modules). This is the part which keeps IDs and the motivation for this was very simple: there's just no way to tell where those IDs might lurk. Say, one of the old nodes has a http://example.com/node/12345 link in the body text and we changed the node id to 67890 during migration? Then that link breaks. It also made for more rapid development which is not a bad side effect either. It is arguable whether for example file IDs deserved such treatment or not.

As @berdir comments, if you remove the nid: nid process definition from a node migration then it will happily generate new node IDs for you, no sweat but you need to look everywhere for the same to make sure that any references are changed to a migration_lookup process definition. Some of it is already done for you, some of it is not.

For example, comment/migration_templates/d6_comment.yml has:

# If you are using this file to build a custom migration consider removing
# the cid field to allow incremental migrations.
cid: cid
pid:
  plugin: migration_lookup
  migration: d6_comment
  source: pid

For core, pid: pid would work just as well but instead, this migration is already prepared for this migration creating new IDs. But then it continues with

entity_id: nid

Now the corresponding node/migration_templates/d6_node.yml has

# If you are using this file to build a custom migration consider removing
# the nid and vid fields to allow incremental migrations.
nid: tnid
vid: vid

If you actually do that then you need to circle back to comment/migration_templates/d6_comment.yml  and write

entity_id:
  plugin: migration_lookup
  migration:
    - d6_node:article
    - d6_node:page
  source: nid

Because the actual migration is not d6_node but rather d6_node:nodetype.


Module Background Image (bg_image) installed, image not showing Installed the Background Images module with path of image, but nothing is showing.  I am using 'node/*' to apply image to all pages

Did I miss something?

Did you configure the base bg_image settings? You need to specify a css selector to apply the background image to.


Field value not updating when posting data via JSON Here I am getting 200 response but the date field over here is not getting updated.

The node is getting created and other fields are getting updated, only this date field is not getting created.

the error which iam  getting

The Json and content type format is below:

"field_date_of_cage_card_creation": {
        "und": [
            {
                 "date":"17 Dec 2018",
                  "time":"02:45 pm",

                "timezone": "Asia/Kolkata",
                "timezone_db": "Asia/Kolkata",
                "date_type": "datetime"

            }
        ]
    },

You should be adding your date in the value property and not including a time.

"field_date_of_cage_card_creation": {
    "und": [
        {
            "value":"17 Dec 2018",
            // or maybe
            "value":"2018-12-17",
            "timezone": "Asia/Kolkata",
            "timezone_db": "Asia/Kolkata",
            "date_type": "datetime"
        }
    ]
},


Having trouble seeing YouTube video in Drupal 7 using Media and Media YouTube I'm having trouble seeing YouTube video in Drupal 7 using Media and Media YouTube.

I've followed this tutorial but I never seem to get a video to show up on my page.
http://www.cleverlogic.net/tutorials/drupal-7-video-setup-using-media-and-media-youtube-module

Another thing I've noticed is that when I add a video to some content type, I never see the video's thumbnail.

No errors seem to get displayed.

I'm using Drupal 7,
Media 7.x-1.0-rc2
Media YouTube 7.x-1.0-alpha5

Thanks for your help.

For future reference, the video_embed_field module now works well for youtube and vimeo videos.


How do I include JavaScript on a single page in a way that is amenable to scale I've read through a bunch of material about using JS in Drupal 8 theming and module development, but did not come away with an understanding of the most straightforward way to routinely add things likes GSAP animations and interactive D3 charts to individual nodes.

Each piece of custom JS will only ever be needed on one page. Over time the site may grow to include 10s or even 100s of such pages.

From reading the module development documentation, creating a custom module and adding each JS file to the myModule.libraries.yml with logic to load each on only one page based on id would work, but before I start down that path I thought I'd ask if there is some other way to do this.

Following Steps will make working with External JavaScript libraries in Drupal 8 absolutely clear (including how to conditionally load it in specific pages):

Step 1:
Place the JavaScript file in your theme or module inside a folder called js. After this step your folder structure must look like :

my-theme/js/my-script.js

Step 2:
If your theme already has a my-theme.libraries.yml file open it, if not create it.

In Drupal 8 Libraries are simply collections of CSS or JS files bundled together under a uniquely identified library name.

In this step we need to include the JS file that we created in step 1 in our library. we do it by adding following lines of code in our my-theme.libraries.yml file.

my-library:
  js:
    js/my-script.js: {}

Now we have an asset library called my-theme/my-library which can be loaded to our site in several ways.

Step 3:
Final step is to load the library in our site. This can be done in 4 specific ways:

Way 1:
Attach library globally via theme-name.info.yml file

Libraries can be specified in the theme-name.info.yml file by adding it to the libraries property, like this:

name: my-theme
type: theme
description: my theme
package: other
core: 8.x
libraries:
  - my-theme/global-effects
  - my-theme/my-library

base theme: stable

Any libraries specified here in the themename.info.yml file will be made available on evey page.

Way 2:
Using hook_page_attachments_alter in theme-name.theme file.

Following lines of code will attach our library only to the node listing page.

function mytheme_page_attachments_alter(&$page){
  $path = $current_path = \Drupal::service('path.current')->getPath();
  if($path == '/node') {
    $page['#attached']['library'][] = 'my-theme/my-library';
  }
}

Way 3:
Another useful way to conditionally add a library is by using a preprocess function like hook_preprocess_page().

Here's another example of restricting our asset libray to the front page

function mytheme_preprocess_page(&$variables){
  if ($variables['is_front'] == TRUE) {
    $variables['#attached']['library'][] = 'my-theme/my-library';
  }
}

Way 4:
Asset libraries can also be attached from within a Twig template using the attach_library function. Anytime that template is used the corresponding library will be attached in accordance with any template-specific conditions.

In order to see this in action, we need to create or modify a template in our theme. In this example let us modify node.html.twig template to attach our library only if node.id == 1 with following lines of code

{% if node.id == 1 %}
  {{ attach_library('my-theme/my-library') }}
{% endif %}

With this in place, visiting node 1 in our site, we will be able to see our library in action.


Change page URL structure based on node field value I'm using Pathauto to produce nice URLs for my Drupal 7 site, and have run into the need to edit the URLs based on a node field value.

Specifically, when the content is archived on my website, the URL needs to be automatically changed to include the substring 'archive'. So when editing this page:

www.mysite.com/mypage

and node:field-status is changed from none to archived, I need the URL to become:

www.mysite.com/archive/mypage

Also, pages that already feature a substring, such as mysite.com/blog/mypage would ideally have the new substring prepended to the relative URL, so:

www.mysite.com/archive/blog/mypage

I have tried using Flags and Rules to rewrite the URL pattern based on the field value, but with no luck. Any ideas?

You can build a small module, called myalias and use this code to generate custom alias

<?php
function myalias_node_insert($node){
    //here you can access the $node variable and get its fields value
    $node->path['alias'] = 'your_custom_path';
}

You can also change the hook to myalias_node_update($node) to alter the node alias once it is updated.


Migrating a changed view I've created a view that I then turned into a 'Feature.'  I then successfully added this feature to a second site by copying the module files from the first site into the module folder of the second. Only the first-site has the D8 Features Module.

Then on the first site I changed the Title of the View and went through the process of detecting the change and regenerating the Feature:

Edit the view with the new title
Go to the Features Config page where the state of the feature shows "Changed"
Import the code back into the database (i.e. 'revert')
Re-re-edit the view title
Export the view as a feature

Now I want to import the changes of the first-site Feature into second-site Feature.

Uninstall the imported/copied module from second-site
Replace module folder of second site w/ new module from first-site
Re-install the module

I then receive a long error:

  Unable to install My Image Gallery, core.base_field_override.node.my_image.promote, core.entity_form_display.node.my_image.default, core.entity_view_display.node.my_image.default, core.entity_view_display.node.my_image.teaser, field.field.node.my_image.body, field.field.node.my_image.field_my_image_field, field.storage.node.field_my_image_field, node.type.my_image already exist in active configuration.

Obviously there is a problem with either my procedure or my understanding of how to use the 'Feature' feature of Drupal 8, or I have a misconception of what it's supposed to do. Any help would be appreciated.

Procedurally, you should skip steps 3 and 4 in the first list.  For views, reverting will delete the view's config from the database, which is why you had to re-re-edit the title.  FYI, reverting works differently for other objects.

  In some cases (e.g. views), the revert operation will delete the respective configuration in the database, so the system will instead use the default configuration that is defined in the feature module's code.

https://www.drupal.org/node/582680

I am not sure what caused the error you received.  It might be related to the steps you used.  I'd try again and see what happens. :)


Notice: Array to string conversion in token_replace() (line 102 of /var/www/html/includes/token.inc) I am getting this notice when adding a content type in Drupal 7.24.

  Notice: Array to string conversion in token_replace() (line 102 of /var/www/html/includes/token.inc)

What does it mean? Could I reinstall the modules to fix it?

Check Notice: Array to string conversion in token_replace() (line 102 of /.../includes/token.inc).

  This is a dirty fix that excludes wrong values passed into the
  token_replace(). Use it only as a last resort, this does not solve the
  issue but only disables the message !

  Open token.inc and change the content of token_replace()

return str_replace($tokens, $values, $text);

  Change to:

 foreach ($replacements as $value => $replacement) {
   if ((!is_array($value)) && (!is_array($replacement))&& (!is_array($text))) {
     $text = str_replace($value, $replacement, $text);
   }
 }
 return $text;


How do I load a third party PHP library? I have a third party php library which I would like to use in a module. How do I do that in Drupal 8? In drupal 7, I have done things like the following code, but libraries_get_path() doesn't exist in Drupal 8, and I'm not exactly sure how things change, not that we use namespaces (of which I am a beginner).

require(libraries_get_path('twitter-api-php') . '/TwitterAPIExchange.php');

And, where should I place my library? Should I create a new libraries directory and put it in the root, just like modules and themes are now in the root?

The 8.x-3.x branch of the Libraries module still provides the libraries_get_path() function. And (as of now) it looks pretty much unchanged. So you should be able to use it in the same way.

As far as where to put your library, the libraries_get_libraries() function has been updated with the following addition to the $searchdir array:

// Always search the root 'libraries' directory.
$searchdir[] = 'libraries';

Which indicates that you can place your libraries in a directory named "libraries" at your site root.


Splitting field value inside field template not working? I have a twig template for some text field. Inside it I'm displaying the value like (it's single value field):

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

And it's displaying value correctly, which means that inside that loop item.content contains correct value.

Now, field value actually contains tags, i.e. value is "tag1 tag2 tag 3". And I want to split that value by space sign. So I tried something like:

{% for item in items %}
  {% set tags = item.content|split(' ') %}
  {{ dump(tags) }}
  {{ item.content}}
{% endfor %}

And this split function should return list of elements 'tag1', 'tag2', 'tag3', according to documentation: https://twig.symfony.com/doc/2.x/filters/split.html

But instead, this dump call prints out null ?!?!

Why is that happening?

In a field.html.twig template {{ item.content }} is a render array. You can't use it in functions which expect a scalar like boolean, integer or string.

If you want to use field values in TWIG code better use the field object #items:

{% for item in element['#items'] %}
  {% set tags = item.value|split(' ') %}
  {{ dump(tags) }}
{% endfor %}

In a single value field you can access the value directly without a loop element['#items'].value.


What's the default expiration time for block caches? This article explains the cache setting in Drupal 7.

I'm using Blockcache_alter to cache some blocks. It's not clear to me how long those blocks are cached.

Nothing special here. It's the same as on your admin/config/development/performance page. Module Block Cache Alter just alters 'cache' key for block and does not interfere with the mechanism of caching in Drupal.

Example 1:
Minimum cache lifetime: none,
Cron: every day,
Block cache will be flushed every day or if someone flush cache manually.
On node or comment submit: the whole block cache will be flushed.

In Example 1 the whole block and page cache will be flushed immediately on every new comment, node, vote submit because of Minimum cache lifetime: none. See where cache_clear_all() is called.

Example 2:
Minimum cache lifetime: 12 hours,
Cron: every 6 hours,
Block cache will be flushed every 12 hours or if someone flush cache manually.
On node or comment submit: only block cache older than 12 hours will be flushed.

Block and page cache items which are older than 12 hours will be flushed immediately on every new comment, node, vote submit. See where cache_clear_all() is called.

Cron period is important because Drupal tries to flush caches on every cron run.

This behaviour can be changed with Cache Expiration module.


How to create dummy fields I use Drupal7. I want to create some dozens of dummy fields in my test node quickly. But, it will take long if I do at "manage fields page"(admin/structure/types/manage/CONTENT_TYPE).

Unfortunately, I couldn't find any modules to do it(Devel Generat can create contents, but not fields). Any suggestions to do it?
Thank you.

You could use this module:
https://www.drupal.org/project/bundle_copy

Create a field
Export the bundle/content type
Copy the field in the exported text, paste several times, changing stuff for each field that you want to change for each new field
Import the same bundle/content type


Price resolver save custom field I would like to update a custom field, added to my order items, in the price resolver process. The price resolver process do some sort of queries to select the right price and this selection has a key that I want to save in the custom field.
I'm not sure how could I alter the order line item after the right price was selected.

You price resolver should have something like
if (isset($result['price'])) {
    return new Price((string) $result['price'], $context->getStore()->getDefaultCurrencyCode());
}

Before your price resolver's return line put:
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
$order_items = $cart->order_items->referencedEntities();
foreach ($order_items as $order_item) {
  if (!empty($order_item->field_custom)) {
    $order_item->field_custom->value = 'Hello World'; // set new value
    $cart_manager = \Drupal::service('commerce_cart.cart_manager');
    $cart_manager->updateOrderItem($cart, $order_item);
  }
}


Pass parameters for node access on RESTful call I'm trying to figure out how to pass a filter parameter on a Services rest call.  I've got a node of a specific type that I'd like to access through the Services module and rest.  I'm testing with FireFox RestClient and I can get all nodes of the particular type by typing

http://localhost/drupal/gpa/node/?parameters[type]=node_type

But, I'd like to be able to get one specific instance of 'node_type' that contains a specific field value.  I've taken a look at node_resource.inc, but, I can't seem to make heads or tails of what I need to use as parameters.  I've tried several variations that typically return no result, or, all instances of, 'node_type'.

Is it possible to filter the returned results, or, is my approach incorrect?

EDIT: If any C# programmer stumbles across this, I was able to use the Basic HTTP Authentication module to prevent unauthorized access to the view.  First, as Tyler indicated, I needed to change the permissions settings.  In My case, I chose a Role (Administrator).

The entity index resources unfortunately cannot be used to filter by field values, they can only filter by entity property values (e.g. node nid, title, type, etc). I think you have two options:

create a custom service resource that uses parameters and a database query (or entity field query) to filter and return what you want
use views_json (a sub module of views_datasource) to create a View with a contextual filter for your field


Replacement pattern in view field template I have a body field view template:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

What I want is:

if nid == 1
print $output =  view_embed_view('my custom view')
else
print $output;

How can we do this?

Note: I'm already using the Views Field View module, but can't figure out as how to apply this condition of nid.

In view template file of body field, write this code;

$nid = $row->nid;
$body = $row->body;
if($nid == 1):
  $view = views_get_view('VIEWS_MACHINE_NAME');
  $view->set_display('DISPLAY_ID');
  $new_view = $view->preview('DISPLAY_ID');
  print render($new_view);
else :
  print $body;
endif;


Performance using location based information and proximity filters I'm building a site where each piece of content is geocoded with latitude and longitude. Information will be shown based on proximity to a location chosen by the user. It seems like it would be faster if the information was shown based on city or state arguments because then Views can be cached. If every page view requires a proximity search of nodes from a lat/lng coordinate that no two users will ever share, I imaging the database will be getting a big work out.

A proximity search is fine, but how do I show other nodes in context of proximity whether it is state, town, city, or country?
What would the information architecture be?

I'll answer the first part of your question about caching with a gentle warning and a tip...

I've tried caching location-based searches and it's a fast way to a HUGE (slow) cache_views_data table.

The reason is the same as the need to cache; there are lots of permutations of latitude and longitude, so every new request will add to the cache. Depending on the speed at which you have new content or updates, the cache will either:

become immense as the queries are stored for many different lat/long combinations. This will happen with long cache times.
be quite big but rarely hit because the cache times are suitably short to keep the pages showing fresh data.

Super-huge cache tables can quite possibly be as much of a performance hit as having the database just calculate what's nearby. Lookups might be ok but inserts and expunging old data will certainly slow your database server down.

One approach I considered but haven't yet implemented is to make the latitude/longitude arguments less granular by rounding the values to fewer decimal places. This way, you can have much higher cache hit rate at the expense of a little accuracy. For example, there's much more chance of (51.1, 0.9) being hit by multiple users than (51.123456, 0.887744). The number of decimals, and therefore accuracy loss, is entirely up to you.

You can either implement a views hook to change the views arguments, or use Views PHP to add custom code to your arguments which allows them to be rounded within the view itself.


Instant Search for Drupal 7 Are there any 'instant search' modules (similar to Google's instant search) available for Drupal 7?

I found the Drupal 6 modules listed below, but neither of them seems to be available for Drupal 7, yet.

Drupal Instant search
Instant Search

You should use the Finder module; I haven't used the D7 version yet, but the Drupal 6 version worked well for my needs.


Does Drupal resave the photo even if it's already the correct size as your Image Style? Does Drupal still recompress the photo even if the file you uploaded is already the same size as your selected Image Style? In the event that it does recompress it, is there a way to prevent it? Image quality is at stake in this case since it saves it in JPG.

I ran some Md5 tests and sadly it does recompress it again even if it's already the correct dimensions. Is there some way to prevent this? Uncool.


How do I use the time function in Views Math expression? I'm having trouble with the Global: Math Expression in a View.  I have an entity type which is a student.  I'd like the student grade level to change automatically from year to year, so I'm storing a graduation year and would like to display grade level by a Math expression.  To do so, I need to include a current time element (month and year).  I have read that time() is useable, but I can't get it to work.  Perhaps I'm using the wrong format in the Expression box under Configure field?  As a test, I put in just time(), but I get a zero at the output.  Is time() useable within Views Math Expressions or do I have to abandon that approach and learn to use the Computed Field module?  If time() is useable, would I be able to convert seconds to years by getting an integer value for time()/60/60/24/365.25 or does is there no integer conversion function here?

If you are using the Views PHP Field, http://drupal.org/project/views_php, you can enter in custom php field information. I would take the original date variable and subtract the date as of now to get the value you want:

  //Just creating a random freshman grad date

  $graduation_year = (date('Y-m-d', strtotime('+4 year')));

  $now = (date ('Y-m-d', (strtotime('now'))));

  $diff = abs($graduation_year - $now);

Based on the absolute difference in years you can do validation in your views field that validates this information and sets the student as a freshman, sophmore, junior or senior (assuming highschool :) ) based on the $diff value of 1,2,3,4.

That validation would look like:

if ($diff == 1) {
print('Senior');
}
elseif($diff == 2){
print('Junior');
}
elseif($diff == 3){
print('Sophmore');
}
elseif($diff == 4){
print('Freshman');
}

I didn't put exception handling but you get the idea.


Commerce View oddities? hi I'm trying to create a new Cart view which will simply show Items Total, Cost total and checkout links. I wanted to keep the Default view in place as a fall back, so I cloned it to work on it, but then I noticed my new clone view has a Save button attached to the footer* which isn't there on the original. Also the original is labelled as Display Master, which I've not sen before and dont believe I have access to create such a type.

The footer is set to Commerce Line Item: Line item summary  and investigating all the  options that come with this, none seem to control this Save button.

Can anyone help me out with these two oddities? show some info on the altered screen shots below.

cheers.

The master page is always present in a defined View, although it may not be visible.  To toggle its visibility on and off go to the views list page and select the 'Settings' Tab.  Check or uncheck the "Always show Master Display" checkbox.

When you begin a new view and generate the a page or block, the hidden master is also being completed.  It serves as the template for any new pages or blocks you create without cloning.  I keep the master display visible and will use it as the template for views with many alternate displays.


Get directories & files of a theme in module How can I scan a directory and its files from a module? Is there any permission issue?
I have to apply some logic based on the folder structure in the active theme.

When I use the below code, its returning empty

file_scan_directory($path,$depth=0);

I am getting the path to theme by below code:

$path = base_path() . drupal_get_path('theme','sandesh').'/'.'layouts';

Is this the wrong method to this? Or is there any other apis for that.

You are mixing filesystem path and URL path:

base_path(): Returns the base URL path (i.e., directory)
of the Drupal installation.
drupal_get_path(): Returns the path to a system item (module, theme, etc.).

The second argument for file_scan_directory() is the preg_match() regular expression of the files to find. You are using '0' which only match a single file named '0'.

file_scan_directory(DRUPAL_ROOT  . '/' . drupal_get_path('theme','sandesh') . '/' . 'layouts'); is all you need to do. Use base_path() only when building URL for which an existing helper function (url(), file_create_url(), etc.) cannot be used.


How to send mails with mime module only for specific modules? Fixed it, see answer below

On my drupal installation there are some fancy webforms which send plain text emails, turning on the mime module messes them all up. But, I need the mime module to send html mails when using simplenews newsletters.

I did the following in the settings but it has no effect (html = plain):

(http://abload.de/img/bildschirmfoto2013-11w1j7v.png)

What did I miss? How to use the mime mails only when simplenews is sending mails? I set HTML as format in newsletter settings.

Thanks!

I installed the HTML Mail module and created a new setting with Mail >> Simplenews leaving the key blank, which works fine now!


Better Search Api Solr score sorting for strict word match in Drupal Given the following configuration:

A Search Api views page(connected with a Solr server) with a "Search: Fulltext search" exposed filter searching only on one "Full Text" aggregated field (Node Title).
All the content is in Dutch;

The issue:

Having a list of node titles as following:

AVENE CREM NUTRITIVE COMP POT 50 ML
Widmer Nutritive Creme Parf 50ml
AVENE TRIXERA NUTRITION NUTRI-FLUIDE 400
NUTRITIC MEMOTONIC 7 FLAC
NUTRITIC VIT A-D GINKGO 30 TABL

Searching for the keyword "Nutritic" will return me the following order:

NUTRITIC MEMOTONIC 7 FLAC
AVENE CREM NUTRITIVE COMP POT 50 ML
Widmer Nutritive Creme Parf 50ml
AVENE TRIXERA NUTRITION NUTRI-FLUIDE 400
NUTRITIC VIT A-D GINKGO 30 TABL

It seems like the keyword "NUTRITI" is considered the same as "NUTRITIC".

How can ensure that searching on keyword "NUTRITIC" the content containing specifically "NUTRITIC" will have the bigger score than others?

Having just worked with Solr myself (for English) text. You need to assure Solr is Configured to search how you want. Out of the box the Solr configuration provides:

a case insensitive, stemmed search (fuzzy, such as "savage" searches for "savage", "savages", "savaged", etc. and the search ignores punctuation. It also supports short phrase searching such as "find me this text" although Search API in 7.x-1.20 has a bug that removes min_length words from quoted strings:
https://www.drupal.org/node/2832196

This issue is resolved in the current -dev release available on 12/09/2016.

You have 2 options

So, if the default stemmed search works for you as-is OK. If you want exact word searching with no stemming you need to alter the Solr schema to index text content differently than it does out of the box.

For non-stemmed, case sensitive searches change the analysis and query and multi-part logic to not use SnowballPorterStemmer and CaseInsenitive.

This is kinda outlined, but out of date for Solr 5x in this drupal issue.
https://www.drupal.org/node/1319516#comment-5158076
Solr 5x depercated enablePositionIncrements=true so don't do that in the comments, and it will work.
If you like the searching as-is. You can alternatively boost the exact words to score higher than the inexact results. You would do this by:

adding a fake entity property using an alter hook, and copying the text content from your fields into that field.
You would then define a Solr field in the solr schema to use for this drupal entity property field which doesnt use stemming to returned results
include this fake property field in your drupal search api Index.
use an alter hook for the solr query include this field with a boost (&myfield="FOOBAR"^10) in your search query.

Here's how you add a fake entity property to then be boosted:
http://cornel.co/article/add-entity-property-node-which-can-be-used-search-api-index-field

Then it's simply a query alter in your form (here for apachesolr module, but for search API it's the same thing):
https://www.phase2technology.com/blog/techniques-to-improve-your-solr-search-results/

Isn't Solr fun!!! (sigh) it's really cool, but also cumbersome.


Reset password via Services by email, and not by uid I'm trying to POST an email address to the password_reset Services endpoint so that it generates and sends a password reset email for a user. When I post the uid to the endpoint, it does this successfully. That said, I want to post the user's email to the endpoint (e.g. they type in their email to retrieve their password recovery email). How can I change the below in order to allow this? I tried changing user_load($uid) to user_load_by_mail($uid), but this didn't work.

Endpoint format:

  mydomain.com/myendpoint/user/emailhere@go.com/password_reset_email

user_resource.inc

  $definition = array(
  'user' => array(
  'operations' => array(
  'actions' => array(
    'help' => 'Send forgot password email',
    'callback' => '_user_resource_password_reset_email',
    'access callback' => 'services_access_menu',
    'args' => array(
      array(
        'name' => 'email',
        'optional' => FALSE,
          'source' => array('data' => 'email'),
        'type' => 'string',
        'description' => 'The email address of the user whose password should be reset.',
      ),
      ),
    ),
    ),
    ),
  ),

       function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset_email', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}

Obj-C

ViewController.m

- (IBAction)sendButton:(id)sender {

[DIOSUser userSendPasswordRecoveryEmailWithEmailAddress:self.forgotField.text
                                                            success:^(AFHTTPRequestOperation *operation, id responseObject) {

                                                                NSLog(@"Password being sent!");

                                                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieving Password"
                                                                                message:@"We're helping you retrieve your password! Please check your email in a few minutes for a rescue link."
                                                                                delegate:self
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
    [alert show];

      }failure:^( AFHTTPRequestOperation *operation , NSError *error ){

      if(!error){

     }
      }];

        }

DIOSUser.m

 + (void)userSendPasswordRecoveryEmailWithEmailAddress: (NSString*)email
                                              success:(void (^)(AFHTTPRequestOperation *operation, id responseObject)) success
                                              failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error)) failure {

   NSString *path = [NSString stringWithFormat:@"user/%@/request_new_password", email];

    [[DIOSSession sharedSession] sendRequestWithPath:path method:@"POST" params:nil success:success failure:failure];
}

It would be better if this was externalised into a custom module instead of 'hacking' the services module.

This is fine on my system

$definition = array(
  'user' => array(
    'operations' => array(
       ...
       'actions' => array(
          ...
         'password_reset_email' => array(
         'access callback' => 'services_access_menu',
         'callback' => '_user_resource_password_reset_email',
         'args' => array(
          array(
                'name' => 'email',
                'optional' => FALSE,
                'source' => array('data' => 'email'),
                'type' => 'string',
                'description' => 'The email of the user whose password to reset.',
        ),
    ),

Function is

function _user_resource_password_reset_email($data) {
  global $language;

  $mail = _services_arg_value($data, 'data');
  $account = user_load_by_mail($mail);

  if (empty($account)) {
    return services_error(t('There is no user with email @email.', array('@email' => $mail)), 404);
  }

  // Mail one time login URL and instructions using current language.
  $mail = _user_mail_notify('password_reset', $account, $language);
  if (!empty($mail)) {
    watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->name, '%email' => $account->mail));
  }
  else {
    watchdog('user', 'There was an error re-sending password reset instructions mailed to %name at %email', array('%name' => $account->name, '%email' => $account->mail));
}

  $result = "success";
  return $result;
}


Setting up responsive content within a responsive theme I want to make a layout INSIDE the main content which is responsive.
I've read through dozens of pages, watched several videos and still there is no clear path to acomplish resposive content.
I started out with the latest Zen, but Display Suite and Panels let me place my fields in different grid layouts, but these grids end up not being responsive.

I now installed Omega, ending up having the same issue.
So, which theme and which modules let me setup a responsive grid WITHIN the main content?

If you are using Zen theme, best way(i hope so) to do responsive design is - Zen grids,
First u need to install ruby gems, after you installed u need two more things, as root install sass and compass and ofc. zen-grids

gem install sass
gem install compass
gem install zen-grids

Then go to your theme folder, and write compass watch now all your css yo need to write in sass folder it will produce css in same files in your css folder. To do blocks responsive, in Layouts folder(ofc if you are using Zen sub theme) u will see responsive-sidebars.scss  or similar, now u need to import @import "zen";// Import Zen Grids with this statement. and write zen-grids code in your responsive-sidebars.scss. Read more about Zen grids - here.
I hope it helps.


Remove classes in hook_preprocess_block In Drupal 8 I'm struggling to remove classes from a given block. Here's a quick snippet from a preprocess function:

function mytheme_preprocess_block(&$vars) {
  $block_classes = array(
    'block_id' => array('custom-class'),
  );
  $id = $vars['elements']['#id'];
  if (isset($block_classes[$id])) {
    $vars['attributes']['class'] = $block_classes[$id];
  }
  return $vars;
}

Interestingly this works, and adds custom-class to the block, but even though it is overriding the existing class array, all the default Drupal classes are still added (later on maybe?). I know that I can remove classes in twig with {{ attributes.removeClass('class-to-remove') }}, but ideally I would like to have a preprocess function that doesn't require exposing more template files.

You can't do that. You can see node and file template. Unless, in your theme you set

base theme: stable

or when you don't define a base theme.


Drupal's "Add to Cart" field shows product variations instead of individual options This is probably a very novice question, but I'm working on a website that uses Drupal Commerce. There is a field defined for the product display called: Product variations which is of the format Add to Cart form.

On most products, this field correctly shows a combination of size and color dropdowns, whereas for some products, it just puts all products variations in a drop down and shows that instead of the color/size combination.

Any idea what might be going wrong or how to debug this issue?

Wrong:

Correct:

It looks like the products you've referenced from the "wrong" image do not all share the same attribute fields in common. One frequent mistake in this regard is forgetting to toggle the checkbox on the field edit form to instruct Drupal Commerce to treat a product field as an attribute field on Add to Cart forms.


Views sort for right to left language The titles of my nodes in Drupal 7 contain Urdu langugage (RTL) content. I have created a glossary view using Views module.

The alphabets of Urdu language are not in right order as they are in the original language.

For example,
(س (1) | ش (1) | ص (1) | ض (1) | ٹ (1) | پ (2) | چ (1) | ڈ (1

How do I fix sorting for View?

You don't. At least not in Views. That's not the task of the client, that's the task of the server. Set a proper collation for the column and / or table. If you really wanted to, you can write a sort handler to use ORDER BY collation but changing the collation with ALTER TABLE is the right thing to do.


How to add css class to specific rows base on fields in order commerce view page I would like to add a class based on the field value I used in commerce order view. I have tried a solution from here I have installed "devel" module and already enabled it. However, I cannot find the dpm() result from my admin order page. I don't know if it is because of my code or dpm() function.

Here is my code and put them in my theme's template.php file::

function MYTHEME_preprocess_views_view_list(&$vars) {
    if ($vars['view']->name == 'commerce_backoffice_orders' && $vars['view']->current_display == "Admin Page") {
        dpm($vars); //uncomment to see variables
        foreach($vars['view']->result as $key => $value){
             $timestamp = $value->node_created;
             if ($timestamp) { // add whatever conditional logic you need here
             $vars['classes_array'][$key] .= ' hello'; // note the space in front of class
             }
         }
     }
}

Here is a screenshot:

Does anyone have any idea about my issue? Thank you for anyone's help~~~~

Try this hook instead: MYTHEME_preprocess_views_view_table. Your view uses the Megarow table format. The hook you used is called for the list format.


Set default value of field in a field group I have had no luck trying to set the value of a field in a field group. I can see in the array that the default value has changed but the change does not show up in the viewed form. This is the same whether I place the code in form_alter or after_build.

If the field is not in the field group, the changed value is visible in the viewed form.

This is the code I'm testing:

<?php

/**
* Modify CCK form elements on the example node form.
*/
function test_after_build($form, &$form_state) {

// $form['field_collection']['und'][0]['value']['#default_value'] = t('Smithfield');

 dsm($form);  // pretty print array using Krumo to messages

  return $form;
}

/**
 * Implementation of hook_form_alter().
 */
function test_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'test_record_node_form')  {

 // target a specific form
  drupal_set_message("Form ID is : " . $form_id);

  $form['field_collection']['und'][0]['value']['#default_value'] = t('Smithfield');

    // Add an after_build function to process when everything's complete.
    $form['#after_build'][] = 'test_after_build';

   dsm($form);  // pretty print array using Krumo to messages

  }

}
?>

I don't know what I need to add to this to make it work. Help appreciated.

I was able to spend some more time on this and figured out that the field group was not where I should be changing the value in the form.

I am using the field group multiple module so the value is not being set at the field or the field group. If using devel, look for something like 'fgm_node_YOURNODE_form_group_YOURGROUPNAME' where YOURNODE will be the name of your content type and YOURGROUPNAME will be the name you gave to your field group. I'm assuming 'fgm' is short for field group multiple.

You will have to travese 'fgm_node_YOURNODE_form_group_YOURGROUPNAME' to find the specific field within the field group multiple that you want to set the default value.

Example:

$form['fgm_node_YOURNODE_form_group_YOURGROUPNAME']['fields']['items'][0][field_YOURFIELD']['und'][0]['value']['#default_value'] = t('Some text');

My form alter code works now.


Append data to all fields of type x I want to add additional content/code to all existing fields of type x. I'm unsure of what options I have for achieving this. I initially thought that hook_form_alter on all *_node_forms would be ideal but this won't cover all instances of the field in the form.

Is there a hook I can use to get all instances of a specific field type?

Depending on what you're trying to add/change hook_field_widget_form_alter() might be an option. It's invoked whenever a field widget is built and you have access to context data so you can easily determine which field type/entity type/bundle you're dealing with.

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}


Can't find the "Create prev/next controls" option I created a slideshow using the Field slideshow module. However, I can't find the Create prev/next controls. Any tips on where they are located?

Oh, and I can't see the "Slideshow" option under Format in the Manage Display window for the newly created content type of Slideshow...

You can find it in the manage display tab of desired content type.

Choose the format to Slideshow.

Here is a Great Tutotrial


How can I change a field's widget type on its node edit page? I have a node type that uses Fuploader image field widget. When a user creates new a node of this type, I want them to be able to use the fuploader widget to upload images. When the user edits that node at some point, I want to switch to the normal imagefield widget. How can I accomplish this?

Login in as super admin:

content management ->content types -> edit [your content type]->managefields

click on configure of that field and there you will see second button which named "Change basic Information"

Click on this button and will get the way to edit widget type.


Import a list of suscribers from Excel I have a big problem with a database. I have a list of suscribers in an excel list with their names, phone and other info. I need to import that suscribers to my drupal website and use them for send them massive emails. How to do that? which newsletter module is better for use with my usecase?

Try the feeds module, or migrate for importing the data. Whatever module you end up understanding best for newsletters, is what I recommend.

Your question leaves out various details: show email templates be editable by site moderators or users, opt-in or opt-out features for the newsletters. Are newsletters recurring, or sent on-demand ... etc.

I recommend looking at the various newsletter modules, Rules based modules and scheduler modules to see what fits your needs.

I find leveraging an existing solution, like mailchimp and other email services typically well worth the cost (personally).

As example I wrote custom code that looks at emails in an imported DB table and uses a server-side cron task to run a Drush command to send emails with my own custom business logic (recurring scheduled emails, if tasks are completed they no longer receive emails)... my solution is not for everyone.


Control Webform's date field (datepicker) from JS I have to change number of months that's shown in datepicker of my date field in Webform, on desktop I need 2 months, but on mobile just 1.

I'm not able to control that using JS, so I created patch for Webform module to change that and show 2 months.

Is there some solution for this, how I can change stuff like this using JS even I initialized it through field settings in Webform module?

You can override it with js .. the trick is when it is when your js is attached.

so in your module you need ....
<?php
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id === 'webform_submission_YOURFORMID') {
    $form['#attached']['library'][] = 'YOURMODULE/mymodule.fix-datepicker';
  }
}

then in your js please try some thing like..

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.fixMyDatepicker = {
attach: function (context) {

  var dateElement = $('#edit-1'); // id of your date picker
  var dateData = dateElement.data();
  if (dateData.datepicker) {
    makeChangesToDatePicker();
  }
  else {
    var myInterv = setInterval(function() {
      if (dateData.datepicker) {
        makeChangesToDatePicker();
        clearInterval(myInterv);
      }
    }, 100);
  }

    function makeChangesToDatePicker() {
      //@TODO here check if mobile .
      var settings = dateData.datepicker.settings;
      settings.maxDate = '2019-03-11';
    }
   }
  };
 })(jQuery, Drupal, drupalSettings);

the above worked for me. remember datepicker is just: https://jqueryui.com/datepicker/


How can I disable a region at with the context module at all pages but the  (home page) How can I disable a region at with the context module at all pages but the  (home page).

I've been trying to disable a region on all pages, except the , without having to write all the paths.
I can't make the wildcards * ~ work on the <front> page.

In the condition field, I've tried to put alot of different combos i cant show here, because my post is deemed spam:

Imagine me using * ~ wildcards in front and in back of all the ways you can write the front page path: eks.  http//www.domain.com/
same goes for <front> with all the different combos.

Which one is supposed to work? Hope you get the idea.

Thanks!
Best Regards Elias

Set ~<front> in path. This will exclude only the front page.

I just tried it and it works properly.


Authenticathed users can't edit Etherpad-enabled field I integrated Etherpad on my Drupal site. I did everything as instructed, but still only the administrator role can edit the Etherpad field.

This is how it goes:

Content type X has a text field which is set to be Local Editable in Manage Display (as instructed by the Etherpad readme file).

Furthermore, using the Field Permissions module, the same text field has custom permissions and is editable by authenticated users.

The url for the Etherpad-enabled field goes like this:

http://mysite.com/etherpad/[node:nid]/[etherpad-field-name]#

Despite all this, when I log in as a regular, non-administrator user, I get an "Access denied" message for the field page.

When logged in as admin, when viewing the node, by hovering over the top right corner of field, the "Edit" dropdown appears with the above mentioned url. As a regular user I don't have that option.

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


Apply a dynamic string to a field before validation I am attempting to set the "title" value of a content type before it becomes "required" . So what happens is the title field becomes hidden based on user name, after filling in the "first name" and "last name" fields I need to take those values and then apply them to the "title" field, before drupal states that the field is required. Here's what I have so far

/**
*  Implements hook_form_alter().
*/

function editorhide_form_alter(&$form, &$form_state, $form_id){
//form id = artist_node_form
//title id = edit-title label: edit-title

global $user;
global $fullTitle;

if($form_id == 'artist_node_form'){
    hide($form['artist_node_form']['edit-title']);
   if( $user->name == 'Editor'){

        // drupal_add_js("jQuery(document).ready(function(){
        //  jQuery('#edit-title').hide();
        // });","inline");
        $form['#submit'][] = "editorhide_form_submit_handler";

     }
}

}

//submit form handler.

function editorhide_form_submit_handler ($form, &$form_state) {

  $fullTitle = array();
  $fullTitle['0'] = $form_state['values']['field_firstname']['und']['0']['value'];
  $fullTitle['0'] .= ' '. $form_state['values']['field_lastname']['und']['0']['value'];
  form_set_value( $form_state['title'], $fullTitle['0'],$form_state);

}

With the current code it throws a error:: Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be an array, null given, called in

First You should write the these kind logic in validate function rather than the submit function.

So instead of

$form['#submit'][] = "editorhide_form_submit_handler";

you should have

$form['#validate'][] = "editorhide_form_submit_handler";

Second the first parameter passed to the function form_set_value is the form element and not the form state value so the function should look like.

form_set_value( $form['title'], $fullTitle['0'],$form_state);

I think what you are trying to achieve can be done with a custom module.

Automatic Nodetitles

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).


How do I make a page available via only a single URL? Is there a way to make the front page available via only a single URL?

The normal method is to use a <link rel="canonical"> meta tag, but this is not good for SEO.

That's what the <link rel="canonical"> meta tag is for.

I'm not sure where you've got the information that this meta tag is not good for SEO, but I'm afraid your source is incorrect; the exact opposite is true. This is what Google have to say on the matter:

  Carpe diem on any duplicate content worries: we now support a format that allows you to publicly specify your preferred version of a URL. If your site has identical or vastly similar content that's accessible through multiple URLs, this format provides you with more control over the URL returned in search results. It also helps to make sure that properties such as link popularity are consolidated to your preferred version.

As you can see this is what Google recommend you do to avoid the problem of SEO penalties for duplicate content. This information is several years old and hasn't changed.

To my knowledge the following modules will add a canonical link to your documents:

Global Redirect
Redirect
Meta Tag

There may well be more though. The 2 redirect modules above will probably help you out even further, as they will automatically perform a 301 redirect to the canonical URL when any of the others are visited. Google also encourages the use of such headers in this situation.

Be sure to read the whole Official Google Webmaster blog post linked to above to understand why this method is the correct one, it's pretty important in terms of SEO these days.

Oh, and if I were you I'd be suspicious of anything else your original source for this tells you...they obviously don't know much about SEO!

Further Reference:

About rel="canonical" on Google Webmaster Tools
Canonical URL Tag - The Most Important Advancement in SEO Practices Since Sitemaps on SEOMoz
Google, Yahoo & Microsoft Unite On “Canonical Tag” To Reduce Duplicate Content Clutter on Search Engine Land

And there are literally dozens more...search Google for "SEO canonical".


How do I add a header to the contact form? I want to add a text header to the core contact form (between the title and the "Name" field). How can I achieve this?

Just like Rylyn said you can use the #prefix attribute. You could change your form with the hook_form_alter:

 function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
    // replace the 'FORM-ID' with the actual id of the contact form
    if ($form_id == 'FORM-ID') {
       $form['name'] = array (
          '#type' => 'textfield',
          '#title' => 'your_title',
          '#prefix' => 'your_text_header'
       );
    }
 }


How do I automatically remove spaces from a path in the blog module Some places on the site are correct
e.g.  http://groundhogresearch.com/blogs/bob-schweickert-jr
but the blog module block show this path
http://groundhogresearch.com/blogs/Bob%20Schweickert%20Jr. which of course can't be found

Using Pathauto you can replace spaces with a character of your choice (and do a lot of other stuff too), like for example a dash. Once you have enabled the module go to admin/config/search/path/settings and start configuring the module.


Output block in particular region from custom module drupal 7 I have a custom module that spits out a form using the drupal form API. What I'd like to do is output a block (a custom menu) in a particular region of the page (using block regions would be the best way I'm guessing.) As of now, the block renders in the top left everytime. How can I output the menu block in a particular region of the page?

function client_menu(){

 $items=array();

 $items['campaign']=array(

   'title'=>'Campaign Manager',
   'description'=>'Area for clients to manage their campaigns',
   'page callback'=>'drupal_get_form',
   'page arguments'=>array('client_campaign'),
   'access arguments'=>array('access client administration'),
   'type'=>MENU_NORMAL_ITEM
 );

 return $items;

}

function client_campaign(){

$block = module_invoke('menu', 'block_view', 'menu-client-admin');
print render($block);

//a bunch of form API stuff...

}

Why aren't you creating a standard block which returns your form? Currently you have a page callback (http://yoursite.com/campaign), and you are injecting this into a block ...

Here is some sample code that could help you further:

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

    $blocks['client_campaign'] = array(
        'info' => t('Area for clients to manage their campaigns'),
        'title' => t('Campaign Manager'),
        'region' => 'content', // Your desired region, can be edited in administration screen
        'status' => 1,
    );

    return $blocks;
}

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

    switch ($delta) {
        case 'client_campaign' :
            $block['content'] = client_block_content();
            break;
    }

    return $block;
}

function client_block_content()
{
    return drupal_get_form('client_campaign');
}

function client_campaign($form, &$form_state)
{
    // Build your form

    return $form
}


Passing variables to custom block I am trying to pass variables to a custom block in a module. I can see that the custom block is used in the code, however I cannot get the variables to show up.

Any help much appreciated:

I am themeing the block in the module file

function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'block__etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

I am building the render array

class SocialBlock extends BlockBase implements BlockPluginInterface {
/**
 * {@inheritdoc}
 */
public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'block__etypeservices',
      '#facebook' => $facebook,
   ];
 }

}

and here is the template

{%
    set classes = [
   'block',
   'block-social-icons',
   ]
%}

    {% if facebook %}

Facebook

    {% endif %}

Can anybody see why this is not working?

For a custom template use your own theme hook etypeservices:

function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

Which uses it's own variables space:

public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'etypeservices',
      '#facebook' => $facebook,
   ];
 }
}

etypeservices.html.twig

{{ facebook }}

The content of the block is a normal render array, which can contain one or more custom templates to make them accessible in theming. These custom templates are reusable, not only in blocks.

In a module you can override the block template, as you tried to do by using block__..., but you need this in very rare cases. In drupal core there is only one. Then you will inherit the variables of the base hook block.

But normally you leave the block template as it is, so that it can be themed on it's own.


Adding translation files to install profile? I am building a Drupal installation profile to make deployment of my site easier, ideally I would like to include the translation files to the install profile as well. But apart from adding the core translation files download to the makefile, is there a way to somehow add the translation files for the modules that are in use and for the custom fields as well?

Ideally I would like to add the needed .po files to the makefile or the profile's .install-file. Any ideas on how to do it?

Have you seen http://zgadzaj.com/drupal-installation-profile-with-multiple-languages ?

Also you can try to export it with Features

  Features

  The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

And for more especific export data

  UUID Features Integration

  The UUID Features Integration module provides a mechanism for
  exporting content (nodes, taxonomy, fields) into a features module.
  What's that you say? You thought features was only for configuration?
  This module is meant to be used in the cases where certain pieces of
  content straddle the line between pure content and configuration.
  You've to configure the entity types / bundles to be exportable. Read
  the Documentation for further information.


How do I display two blocks separately? In my header region, I have two blocks: menu and search. I want to add some other HTML between them. I tried using {{ content.menu}}, but it doesn't actually do return anything.

I can split up the content with {{ content.field_type }}, but this approach doesn't seem to be working in region.html.twig.

Never mind! By using {{ dump() }} I was able to see that I can get the individual blocks by using:

{{ elements.search }}

{{ elements.menu }}


is it possible to disable ckeditor for private messages? I've ckeditor through out the site.But i don't need it for private messages(privatemsg module).Is their any way to disable CKeditor only for private messages?