How to conditionally attach a stylesheet to a page, preventing anonymous users from getting a cached version? I'd like to create a module capable of overriding some of the theme's css (for any theme). Think of small things like hiding the image, changing font sizes and colors, etc.

My initial thought was to toggle this using a session variable:

/**
 * Implements hook_library_info_build().
 */
function my_module_library_info_build() {
  $libraries = [];
  $libraries['override'] = [
    'version' => '1.0',
    'css' => [
      'base' => [
        'override.css' => [],
      ],
    ],
  ];
  return $libraries;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function my_module_preprocess_page(&$variables) {
  if ($_SESSION['override']['enabled']) {
    $variables['#attached']['library'][] = 'my_module/override';
  }
}

This works very well for logged in users, but for anonymous users it only caches the first version of the page (using the status of $_SESSION['override']['enabled'] at that time). So some pages show the regular lay-out, and some only show the overridden version.

I realized that I probably have to add a cache tag, so I tried adding

$variables['page']['#cache']['tags'][] = 'override:' . $_SESSION['override']['enabled'];

Assuming this would allow 2 versions of the page to be cached, either for override enabled or disabled. But that does not work either.

What needs to be done to allow multiple versions of the same page to be cached and served, depending on a $_SESSION variable?

Related: Cache context drupal don't work.

But your logic is actually depending on the session, and the internal page cache is disabled automatically for users with a session.

So it is more likely that you are having a problem with the dynamic page cache.

Your problem is that cache tags are not about caching multiple variations. They are about invalidating already cached things when something changes. So if you have configuration which override value should load which value, then you'd need a cache tag for that, so you can invalidate it when that happens. Also in 95%+ of the cases, you don't need to make up your own cache tags, but just use the default cache tags for entities, config objects and so on.

What you want is a cache context, either the default 'session' or make your own, that doesn't vary for the whole session content but only your key, whould is more efficient. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts

And you should also read https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays to understand when you need cache tags, contexts, ..


How add a views page url to the admin_menu? I tried creating a view with a page display, giving it a normal menu item in navigation, the url admin/people/allusers (or any url like admin/content/listing), clearing the caches, but the admin menu does not pick up the page and put it in the drop downs.

How do I do this without having to use hook_menu for each views page url I want in the admin menu bar?

The link needs to get added to the Management menu to show up in admin_menu.

You can add a admin menu link on:
http://example.com/admin/structure/menu/manage/management

Or through the interface at : Structure->Menus->Management->Add Links


How to run custom function after clicking next on a multi page webform I've created a multi page webform and I want to run a function after the user clicks the 'Next page' button on the first page only. After the user fills in the data on the first page, I want to grab that data and do stuff with it. After that the webform should work like normal on through the submission process.

How can I do this so that the function runs only once? I've tried using hook_form_alter and testing the value of $form['details']['page_num']['#value']. This value is 2 if I'm on the second page. For some reason the function fires twice and I can't figure out why.

Thanks

One way to accomplish this task, because the webform module is so complex, is to just use jQuery and attach to that button and node id and run an AJAX query or whatever else you want to do like redirect the user away and then back.

Otherwise you would probably be neck deep in a custom module that extends Webform. In my experience to alter webform modules becomes a major pain and I generally just go another route.


How to include jplayer.js on all pages I am using module - jplayer (http://drupal.org/project/jplayer), in the jplayer.module i've found this piece of code, since i am very weak in php i need a help :)

/**
 * Add the jPlayer library to the page.
 *
 * @param $add
 *   By default this function will add jPlayer to the page JavaScript array
 *   directly. If wanting to store the jPlayer file as an #attached property,
 *   set this to FALSE and jplayer_add() will only return the needed array
 *   suitable for use as an #attached property.
 */
function jplayer_add($add = TRUE) {
  static $added = FALSE;

  $directory = variable_get('jplayer_directory', 'sites/all/libraries/jplayer');
  $return = FALSE;
  if (file_exists($directory . '/jquery.jplayer.min.js')) {
    $filepath = $directory . '/jquery.jplayer.min.js';
  }
  elseif (file_exists($directory . '/jquery.jplayer.js')) {
    $filepath = $directory . '/jquery.jplayer.js';
  }

  if (isset($filepath)) {
    $jplayer_js = jplayer_get_file_path('jplayer.js');
    $jplayer_css = jplayer_get_file_path('jplayer.css');
    $settings = array('jPlayer' => array(
      'swfPath' => base_path() . variable_get('jplayer_directory', 'sites/all/libraries/jplayer'),
      'autoPlay' => (int) variable_get('jplayer_autoplay', ''),
    ));
    if ($add) {
      drupal_add_js($filepath);
      drupal_add_js($jplayer_js);
      drupal_add_css($jplayer_css);
      if (!$added) {
        drupal_add_js($settings, 'setting');
        $added = TRUE;
      }
    }
    $return = array(
      'js' => array(
        array('data' => $filepath),
        array('data' => $jplayer_js),
        array('data' => $settings, 'type' => 'setting'),
      ),
      'css' => array(
        array('data' => $jplayer_css),
      ),
    );
  }

  return $return;
}

What should i modify in this code to show .js files on every page, not only when a node with a player loaded.

UPDATED. The question is - what to modify in this code to attach jplayer js files on every page, not when im viewing a node with a jquery player.

The easiest way to add a JS file to your theme is to add it in the .info file:

scripts[] = js/my_script.js

Be sure to put your js file in a js folder inside your folder's theme.

Reference: Adding JavaScript to your theme or module  (works in D7 too)


Get the value of the "src" attribute I am having hard time with getting the value of YouTube video thumbnail URL, in order to use it as background image in a template file.
I created a video content type and added a remote video field (field_url_vid2). The output format is thumbnail.
{{content.field_url_vid2}} gives the full HTML markup, but I just want the value of the src attribute.

To get the YouTube video thumbnail URL in twig!
Try with:
{{ file_url(content.field_url_vid2.0['#media'].thumbnail.0.entity.uri.value) }}


No default selection in a select item on commerce checkout pages using hook_form_alter Thanks to the help I received in my previous question, I was able to change the HTML of shipping service from radios to a select field. This was done, as suggested, by means of a custom module implementing hook_form_alter.

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
    if ($form_id=='commerce_checkout_form_checkout') {
        $form['commerce_shipping']['shipping_service']['#type']='select';
    }
}

Now what i need is to have an empty option ("select the proper value") in it, so that the user would be forced to actively choose one of the shipping methods.
What I get from

print_r($form);

is

    [shipping_service] => Array
                (
                [#type] => radios
                [#options] => Array
                    (
                        [deli] => Delivery : 5,00
                        [pickup] => Pickup: 0,00
                    )
                [#ajax] => Array
                    (
                        [callback] => commerce_shipping_pane_service_details_refresh
                        [wrapper] => commerce-shipping-service-details
                    )

                [deli] => Array
                    (
                        [#description] =>
                    )

                [pickup] => Array
                    (
                        [#description] =>
                    )

                [#default_value] => deli
            )

        [service_details] => Array
            (
                [#type] => container
                [#prefix] =>

                [#suffix] =>

            )

I tried to tinker with dafault value, inserting another option, like

$form['commerce_shipping']['shipping_service']['#options']['_none']='['-select-']';
$form['commerce_shipping']['shipping_service']['#options']['#default_value']='['_none']';

(which was somewhat randomly inspired by the 'print_r' output from a taxonomy term field on the same form  but brought no results and did cause AJAX errors.
Any ideas?

The documentation says:

  If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.

So take the default value out and make sure that the form code includes '#required' => TRUE,

I also read somewhere that you must use drupal_get_form() to build the output for a form otherwise the additional form processing functions will not run.  I did not use hook_form_alter() to modify shipping services but instead used hook_commerce_shipping_service_info() in a custom module to give me more flexibility.


How to embed user photo upload form in a page of Drupal 7 site I want to embed user photo(avatar) upload form in a node page like this: node--37.tpl.php so a user can change or upload their profile picture by visiting a particular node.
Can't understand what to do, reading some api documentation like function form_load_include with no luck.Also i found an amazing snippet here but how to use it as a form?

$uid = 3;
$account = user_load($uid);

// suppose that a source user picture is located in the 'sites/default/files/upics'     directory.
// get image information
$image_path = 'public://upics/userpic.jpg';
$image_info = image_get_info($image_path);

// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];

// standard Drupal validators for user pictures
$validators = array(
  'file_validate_is_image' => array(),
  'file_validate_image_resolution' => array(variable_get('user_picture_dimensions',     '85x85')),
  'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);

// here all the magic :)
$errors = file_validate($file, $validators);
if (empty($errors)) {
  file_save($file);
  $edit['picture'] = $file;
  user_save($account, $edit);
}

Please give me some ideas to get started, your help is really appreciated.
Thanks

You can do it like this:

Open node--37.tpl.php
locate the container(div) where should be placed a form and use drupal_get_form() function.

example:

<div class="some-class">
<?php print render(drupal_get_form('MY_FORM_ID')); ?>
</div>


On Autocomplete empty I have a project that I need to display some help text to the user if an autocomplete text comes back empty.

Right now, the autocomplete is on a custom form, and I'm using an autocomplete like:

function autocomplete($string) {
  $result = autocomplete_lookup($string);
  $matches = array();
  // Save the query.
  foreach ($result as $row) {
    // Perfom my logic rows here.
  }

  drupal_json_output($matches);
}

Is there a way I can run a check at some point in the process to display a pop up or something if the autocomplete doesn't return anything?

Not sure if it would help or not, but if your looking for trying to tell the user nothing exists in the database, you can always add logic to the autocomplete that will return something to the field that indicates no results are found.


Add multiple co-authors while creating node I have a content type proposal. Now I would like to have multiple co-authors of the node. I want to give the author the opportunity to add users like this:

The users have to be entity references. I know there is a module Node access user reference but how can I have a collection of entity references that bundles the "co-authors". The module doesn't work with Field Collection module.

Has anyone encountered this and is there a module for this or a simple solution?

I suggest you look at these two modules

https://www.drupal.org/project/references
https://www.drupal.org/project/entityreference

They're both quite similar.

They allow you to add user reference fields to your content type. On the field you created, set the number of values to be unlimited and then the author can select as many co authors as they want.


Webform Filter Component Roles How may I be able to limit a webform component visibility by logged user role? In Drupal 7, this was possible with webform_component_roles module but there is no version for Drupal 8.

Thank you.

When creating/editing a field, scroll down to ELEMENT ACCESS. There you can set all the limitations based on roles.

If you use YML you can use something like:

'#access_create_roles':
    - administrator
'#access_update_roles':
    - authenticated
'#access_view_roles':
    - authenticated

Finally, if you want to change the accessibility of the webform, check the Access tab (admin/structure/webform/manage/FORM_NAME/access).


How to create new field type I'd like to create a new field type that can be attached to content (ie an article) via the admin interface through 'manage fields' of the content type. I am unsure of the process and required hooks to achieve this.

At this point I'd like the field to be nothing more than a simple text field. So far I have defined the field in:

hook_field_info
hook_field_schema (in .install file)

What other hooks do I need to get this to:
a) appear in manage fields options.
b) appear in the content editor for the content it has been applied to.

Many thanks

When I did this a while ago I adapted the excellent field_example module from the Examples Module which is always the first place to look, as it has a lot of Drupal best practice in it.

As they say in the module comments:

     * Providing a field requires:
     * - Defining a field:
     *   - hook_field_info()
     *   - hook_field_schema()
     *   - hook_field_validate()
     *   - hook_field_is_empty()
     *
     * - Defining a formatter for the field (the portion that outputs the field for
     *   display):
     *   - hook_field_formatter_info()
     *   - hook_field_formatter_view()
     *
     * - Defining a widget for the edit form:
     *   - hook_field_widget_info()
     *   - hook_field_widget_form()

So, not for the faint hearted, but as others have said, all the information is there to get you started.


How can set a custom action with a custom attribute selected in form? I have a view of persons. I like to add the persons to an event. I also like to set the status of the resulting relation to one of the values "optional" or "required".
Therefore I use VBO on a list of persons. With the submitted NIDs I like to build a relation from the person to the event and fill the relation data field "status" with the selected value from the from.
To create only the relation it was easy to create a new action with custom php code, which builds my relations programmatically.
To add a parameter to the relation I have to edit the view's form programmatically. So I hook into the form alter of the views form and add a custom dropdown with the two values "optional" or "required".
The questions are:

Is it possible to use the selected dropdown value in the vbo action with custom php code? I only know how to handle the selected nid's. This option would be easier for me to implement.
If 1) is not possible: Should I use a custom submit function for the vbo form? And where to assign the function?

I tried the following code to assign a custom submit custom_webform_pre_build_list_vbo_submitfunction but it isn't called.
function custom_webform_pre_build_list_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_form_person_list_panel_pane_9"
    and $form['#id']=='views-form-person-list-panel-pane-9') {
        $form['#submit'] = array('custom_webform_pre_build_list_vbo_submit');
    }
}

It is possible to use the $_POST array in the custom php code, which can be called in the action, which is assigned to the vbo action!
The page to show the view with the vbo fields is: /node/%node/add_person_to_event, so arg(1) is the nid of the event.

So my custom action code is:

$status = $_POST['status'];
$event = arg(1);
foreach ($_POST['views_bulk_operations'] as $key->$vbo_nid) {
   build_relation_person_event($event, $vbo_nid, $status);
}


Trying to get property of non-object throws exception that cannot be handled In a custom Drupal 8 module I decided to wrap a line of code in a try...catch block, in case $node was null.

I understand that in php errors and exceptions are different, and according to Error message - Trying to get property of non-object this is an error, so will not be handled by try...catch, and the code should continue to run after the error.

However when this code runs under Drupal 8 the error hander raises an exception. So I added the try...catch block. But the exception is still unhandled crashed the program.

This is a cut-down version of my code:

$node = null;
try {
  // The next line results in an unhandled exception
  $f = $node->field_example;
} catch (Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
}
// Never gets here

Am I missing something? Surely this can't be the intended behaviour?

I actually over-simplified by question. The crash doesn't happen in the simple case I posted, just an error and execution continues. It arises when I use field API syntax to refer to a null referenced entity, and only then when the target_id is not null.

$node->field_foo->target_id = 999; // term 999 does not exist
try {
  // The next line results in an unhandled exception
  $v = $node->field_foo->entity->field_bar->value;
} catch (\Exception $e) {
  // Never gets here
  watchdog_exception('example', $e);
}
// And never gets to continue here

The issue was why and Drupal does this. The solution (thanks @Clive) is to replace catch (\Exception $e) with catch (\Throwable $e)


Scroll to links for articles on page I would like to create a block and place that on the right hand side of my site.

Within the block I would like to have a list of links.

The links would scroll the viewport down to that article.

The page will be the homepage of the site.

I will use Views to create a page. I will select 10 full articles to be displayed on the page.

How can I go about creating a block to add to the right hand side which will contain links.

I will need to have an id hook on the h1 of the article titles for
the links to work.
I have to loop through articles which show up in the view to get titles
I need to create a block using the titles to create links such as a href="#example-article"

Day to day I code in Ruby on Rails, I am working on a Drupal project for a client and I am not well versed in PHP, never mind Drupal. I wouldn't be surprised if someone had wanted this same feature in the past - however - I don't work with 'blog style' sites often and I have not found any examples when searching online.

Any tips would be much appreciated. A link to a guide on how to achieve this would be amazing. Merely explaining how to get the articles object and loop through it for the titles and then put this in a block would get me 90% there.

The good thing for you is this is completely doable within the Views UI alone. No PHP is needed here. A full explanation is too lengthy here (and asking for tutorials is off topic). If you're a novice to Drupal, watching some tutorials on Views would be a good time investment since it's a core part of Drupal now.

Here's some additional info to navigate you 90% there. See the image of the Views UI to yourself started with your page & block view:

If you have a view of full content nodes, Drupal, by default, wraps a node display in a div with an id of node-<NID>. (if you have a custom theme it might differ, but it should be pretty easy check that out). As such, a default Views page of full blog posts should already be linkable with a #node-nid anchor.

As for the block, Views allows you to have multiple displays based off the same query. When you create your view, you can also create a block. You'll just to make a few alterations to the block so that links are presented as anchor links for the page they'll appear on:

Add a Content: Nid field to the Block display, making sure to set For selectbox to This block (override) (i.e. only add it to the block display).
Tick the Exclude from Display checkbox so that the Nid field doesn't appear on the block.
Rearrange the Content: Nid field (via the down triangle next to the Fields Add button) so that appears first.
Click on Content: Title to reconfigure its display, you'll want to  untick Link this field to the original piece of content to remove the hyperlink to the blog and tick Output this field as a link under Rewrite Results, you'll be placing #node-[nid] in Link Path, which if you did all the above correctly, should rewrite the block links to an anchor link for each post display.

That should get you most of the way there. Views UI is pretty complex so it's going to take a bit of experimentation to understand it all. The above should navigate you mostly through it.


Does poll not allow multiple anonymous votes? We're having a problem with the core poll module on drupal 7. We have a poll that we want anonymous users to be able to vote on. There is currently one anonymous vote, and now anonymous viewers only see the result (we've tried looking at it from outside our network).

We've checked the perms, and anonymous can vote and view results ( but not change vote). We've cleared the cache.

How does Poll work on D7 with regards to the anonymous user?

The problem is that the poll module only allows one vote per anonymous IP address.  In the case of your hosting provider I suspect that they are using some sort of proxy that sends all requests to Drupal from the same IP address.

The Poll Enhancements Module modifies this behavior to allow multiple anonymous votes from the same IP address.  The documentation on this module's description page also suggests the Poll Improved Module may solve this as well, but it does not have a production release at this time.


Topics are not getting associated with forum I am testing out the Drupal 8 core Forum module.  I am using a theme that I based off of Acquia Lightning.  I have successfully installed the module and added Containers, Forums and Topics.  My issue is that the Topics I create don't seem to get associated with the Forum taxonomy.  In other words, when I go to /forum I see my containers and forums but every forum has Topics: 0, Posts: 0, Last Post: n/a.

I have tried clearing cache, running cron, looking at the watchdog logs but nothing seems to indicate why it isn't working.  I am not receiving any memory errors, white screen of death, etc.  All other site functions seem to work properly: I can save content and taxonomies, create new views, assign blocks, etc.

See the attached screen grab.  I could use some ideas on what might be causing this.  Any assistance would be greatly appreciated.

Try:

drush state:set comment.maintain_entity_statistics TRUE

Explanation:

core/modules/comment/src/CommentStatistics.php in the update() function says this:

// Allow bulk updates and inserts to temporarily disable the maintenance of
// the {comment_entity_statistics} table.
if (!$this->state->get('comment.maintain_entity_statistics')) {
  return;
}

In my case, somehow this was not set, causing this function to bail out and not update the comment_entity_statistics table. Drupal needs this table updated to display the proper forum posts.

"drush state:get comment.maintain_entity_statistics" can be used to check if this is already set.


D6 - Create a files table entry for a file I have to migrate some content and everything is fine except the images.

I'm getting the images using file_get_contents() and save the file in the drupal /files folder using the following code:

    $image = file_get_contents('http://www.someurl.com/xx/util/yy.jpg');
    $file = file_save_data($image, 'yy.jpg',FILE_EXISTS_REPLACE);
    print $file; // returns the path to the file ( /files/yy.jpg )

So the image is uploaded in the /files folder.

What I'm not able to understand is, how can I add the image to the files table so that I can be able later to use the file object?

I was looking through the files.inc functions for Drupal 6 but I wasn't able to find anything that could help.
Should I insert the data manually using db_query()?

Thanks.

It's just done manually, e.g.:

$file = new stdClass();
$file->filename = 'foo.bar';
$file->filepath = $file;
$file->filemime = file_get_mimetype($file->filename);
$file->uid = $user->uid;
$file->status = FILE_STATUS_TEMPORARY;
$file->timestamp = time();
drupal_write_record('files', $file);

See file_save_upload() for a much broader example, including validation.


Route access check for local task I've created a view with a page display, filtering on a specific node type. The view's URL is /admin/poi.

Now I want to create a local task, linking to this view, for all nodes of type poi. The local task is showing, but it is visible when viewing/editing any node type, not just my POIs.

wt_poi.routing.yml

wt_poi.admin_list:
  path: '/admin/poi'
  requirements:
    _permission: 'access administration pages'
    _custom_access: '\Drupal\wt_poi\Controller\WtPoiController::isAllowedPoiAdminList'
  options:
    _admin_route: true

wt_poi.links.task.yml

wt_poi.list_overview:
  route_name: wt_poi.admin_list
  base_route: entity.node.canonical
  title: 'List all POIs'
  weight: -9999

src/Controller/WtPoiController.php

<?php

namespace Drupal\wt_poi\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;

/**
 * Controller for the POI node type tasks.
 *
 */
class WtPoiController extends ControllerBase {

  /**
   * Used to limit visibility of local task "List" to POI node type
   */
  public function isAllowedPoiAdminList() {
    $bundle = false;
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $bundle = $node->bundle();
    }
    return AccessResult::forbiddenIf($bundle !== 'poi');
  }
}

Why is my _custom_access check not hiding the local task on other node types?

UPDATE: There seems to be an access check, but it is coming from "Access" in views module "Page settings" and my own access check is completly ignored. Best case would be my access check in addition to the view's access check, in a pinch I would prefer my own custom check replacing the view's access check.

I've found a workaround. When I add the view's URL as path in routing.yml, Drupal always used the view's access check. So instead of directly using the view's path, I wrote a simple redirect controller in order to get an alternative path.

wt_poi.routing.yml

wt_poi.admin_list:
  path: '/admin/poi-redirect'
  defaults:
    _controller: '\Drupal\wt_poi\Controller\WtPoiController::redirectToPoiAdminList'
  requirements:
    _permission: 'administer nodes'
    _custom_access: '\Drupal\wt_poi\Controller\WtPoiController::isAllowedPoiAdminList'
  options:
    _admin_route: true

wt_poi.links.task.yml remains unchanged

src/Controller/WtPoiController.php

<?php

namespace Drupal\wt_poi\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Access\AccessResult;

/**
 * Controller for the POI node type tasks.
 *
 */
class WtPoiController extends ControllerBase {

  /**
   * The only purpose of this controller is to provide an
   * alternative path to the POI view, so we can attach an
   * _custom_access check to it.
   */
  public function redirectToPoiAdminList() {
    // redirecting to a view: view.VIEW_MACHINE_NAME.DISPLAY_MACHINE_NAME
    return $this->redirect('view.poi.admin_list');
  }

  /**
   * Used to limit visibility of local Task "List" to POI node types
   */
  public function isAllowedPoiAdminList() {
    $bundle = false;
    $route = \Drupal::routeMatch();
    $routeName = $route->getRouteName();
    $node = $route->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      $bundle = $node->bundle();
    }
    // the first part ensures the local task is shown on node pages,
    // the second part makes sure it also works during the redirection itself
    return AccessResult::allowedIf($bundle === 'poi' || $routeName === 'wt_poi.admin_list');
  }
}

Two remarks:

A) Remember that the user still has to pass the view's own permission check after the redirection (and this is a good thing, otherwise anybody knowing the alternative URL could bypass the access check).

B) The access check must use an allowedIf($positiveCondition). Do not use an forbiddenIf($negativeCondition), because it only returns forbidden or neutral, which always hides the local task.

My solution still feels a bit hacky, and I still would be open for a cleaner solution, but at least it does everything I need.


How would you convert a link to a media item to the file URL in a menu? I would like to be able to link to media in a Drupal menu and have the link converted to a file url.  Is this possible?

I came up with a solution, where you add the link like this: '/media/1234'

And then add this code:

function mymodule_link_alter(&$variables) {
  $url = $variables['url'];

  if (!$url->isRouted() && $uri = $variables['url']->getUri()) {
    preg_match('/base\:media\/(\d+)/', $variables['url']->getUri(), $match);
    if (!empty($match) && !empty($match[1])) {
      $media = \Drupal::entityTypeManager()->getStorage('media')->load($match[1]);
      if (!empty($media) && $media->bundle() === 'document') {
        if ($file = $media->field_media_file->entity) {
          $variables['url'] = Url::fromUri(file_create_url($file->getFileUri()), $url->getOptions());
        }
      }
    }
  }
}

I hardcoded the source field.  You could make it more generic if you like.


import multi-value from csv into entity reference field from a field collection I posted this question at https://stackoverflow.com/questions/39234531/import-multi-value-from-csv-into-field-collections but I have not got any replies yet. Below is the summary:

I have a simple csv file with 3 columns: NID|Key|List; where NID is the node id and Key was the unique value used to add field collections to the respective node. "List" is a multi-value field separated by ";".

Example (csv file):
NID,Key,List
1,2,text1;text2;text3
1,3,text4;text4
2,123,text1
...

Field collection has an entity reference field to a taxonomy plus other fields.

Field Collections:
Field1: text;
Field2: Term Reference;
Field3: Entity Reference; <-- importer/tamper not working!
...

The field collection fields were mapped correctly, except for the field that was an entity reference to a taxonomy. I configured Feeds Tamper with the Field Collection Feeds module but the entity reference list was not imported.

Does anyone has experience (suggestions) importing a multi-value field from a csv file into an entity reference field within a field collection?

Solution: using the same feeds importer's configuration but instead of importing with the standalone form, it worked once it was moved to a content type form. If a content type is selected a source is imported by creating a node of that content type.


How to add more Display Suite template suggestions If you have Display Suite installed, then on the "Manage Display" tab of any content type you will see template suggestions:

  Possible template suggestions are:

  ds-1col--node.tpl.php
  ds-1col--node-page.tpl.php
  ds-1col--node-page-search-result.tpl.php

None of these suit what I'm wanting to achieve, as I wanted a template to apply to all "search-result" view modes for any content type. So my template suggestion would be:

  ds-1col--search-result.tpl.php

But it seems it's not by default accepted. Which hook can I use to add this template suggestion? I was thinking of hook_preprocess_node and adding my own template suggestion to theme_hook_suggestions but this didn't work as it wasn't using my suggestion on node types which have search_result view mode applied to them. The template was only being used on the ones without any search_result view mode configurations, and even then only normal node.tpl.php variables such as $content was passed to this DS template so I don't think it's the right way to do it.

The problem actually wasn't in ds-1col--search-result.tpl.php. It was when I suggested a custom template for a node when I was doing quick tests, with print $ds_content; in them, the nodes which didn't have the search_result view mode configured, weren't being preprocessed by display suite hence didn't have the $ds_content variable set which was being printed on the custom template. Hence it gave me the impression that it wasn't working.

But to answer the question, there's no special stuff you need to do to suggest a template for display suite. First copy the template from display suite folder to your themes folder. And then all you have to do is use the normal hook_process_node and suggest that template for a certain view mode.


How to add the Interest field in profile page which links the user with similar interest? I have seen this type of field in drupal.org where some fields appeared as links which lists the users with similar interests or country. Don't know how to do that in Drupal7.

This is done using taxonomy and the term reference field. Each term assigned to an entity has the option in the display mode to be a link to the term page, which in turn shows all entities tagged with that term.

Edit-

Since default term pages only look for content entities you will have to create a view to override those term pages to show user entities instead. You  can use the taxonomy views integrator module to selectively choose which terms use which view. https://drupal.org/project/tvi


Display field from referenced entity using Display Suite and Views I have a view which displays some products (node) teasers.

In the products, I can select a producer (taxonomy term).

Now... In the products teasers I want to display the country, which is a field from the producer taxonomy term. How can I add this field to the teaser using Display Suite?

You have to configure a new view mode for vocabularies (admin/structure/ds/view_modes). Let's call it "country"

Then on your newly created view mode (admin/structure/taxonomy/{tax_name}/display/county) configure the fields you want to show. In your case this will be the term name and the country.

After you done that you have to go to the manage display of your product content type and select the "teaser" view mode. There, on your taxonomy field, choose "Rendered taxonomy term" as format. Then click the button on the right and choose "country" as view mode.


How to pre-populate fields on a node creation form based on fields from Profile2 module? There is a content type ("Job Listing") that a business account can use to list job openings, and a Profile2 profile for each business that contains the business's address, organization name and taxonomy terms such as industry type.

95% of the businesses that will list a job posting will use the same information; I could just use the profile information, but I need to account for the 5% that might want to change the job listing form. For example, the job might be in another state or country and that needs to be accounted for. I think the the best way to handle this situation is to have the same fields in both the profile and job listing form but allow the business change the information in the job listing form.

It would make sense to pre-populate the job listing form with business profile information as the default. How do I best do this? I was going to use Rules but I can't find a single option for a Rule before the original node creation form is created.

Should I just use hook_form_alter() to access the profile information on orginal node creation and use that information to set the default values?

I created a hook_form_FORM_ID_alter() function in a helper module that tests to see if the node has a NID and if so if it is not in the operation preview. Then I populate the default values of the form with the companies profile information so they can change it later.

// We need to set the default of the Job Listing fields on a new Job Listing form */
function helper_form_job_listing_node_form_alter(&$form, &$form_state) {
  // test if node for has been assigned a NID. If not then populate fields with default data */
  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))){
    $profile = profile2_load_by_user ($form['uid']['#value'], 'business_profile');
    // We currently do not know what the profile language is */
    // Organization name
    if (isset($profile->field_job_organization['und'][0]['value'])){
      $form['field_job_organization']['und'][0]['value']['#default_value'] =  $profile->field_job_organization['und'][0]['value'];
    }
    // Set the default address
    if (isset($profile->field_resume_address['und'][0]['thoroughfare'])) {
      $form['field_resume_address']['und'][0]['#address']['thoroughfare'] = $profile->field_resume_address['und'][0]['thoroughfare'];
    }
    if (isset($profile->field_resume_address['und'][0]['locality'])) {
      $form['field_resume_address']['und'][0]['#address']['locality'] = $profile->field_resume_address['und'][0]['locality'];
    }
    if (isset($profile->field_resume_address['und'][0]['administrative_area'])) {
      $form['field_resume_address']['und'][0]['#address']['administrative_area'] = $profile->field_resume_address['und'][0]['administrative_area'];
    }
    if (isset($profile->field_resume_address['und'][0]['country'])) {
      $form['field_resume_address']['und'][0]['#address']['country'] = $profile->field_resume_address['und'][0]['country'];
    }
    if (isset($profile->field_resume_address['und'][0]['premise'])) {
      $form['field_resume_address']['und'][0]['#address']['premise'] = $profile->field_resume_address['und'][0]['premise'];
    }
    if (isset($profile->field_resume_address['und'][0]['postal_code'])) {
      $form['field_resume_address']['und'][0]['#address']['postal_code'] = $profile->field_resume_address['und'][0]['postal_code'];
    }
  }
}


Flexslider change caption style How do I change the caption style in Flexslider?  I know how to change what the caption text, but I don't know how to change the size, font style, color, etc.  I've been pulling my hair out trying to get this to work today.  I've changed everything around it, through the flexslider.css file, but not the actual text.

That is going to be dependent on the name of the field you used for that field.  If you inspect, using your browser's inspection tool (right click on the element and choose "inspect element") you can search the DOM for the appropriate div to use to style the field as a whole.

Most likely the field name you are looking for will be similar to:

.field-name-field-description

It should use that naming convention with the machine name of the field at the end, with the spaces as underscores.

This will not exist in the flexslider.css file by default.  You will have to add this.  I would recommend that you add this to your theme css rather than the flexslider's css.

Try adding these attributes to your field's selector initially to get a good idea of where it sits on your page relative to the flexslider itself:

float: left;
width: 100%;
background: red;


auto uncheck product attribute Each of my products has it own attribute with an expiration date. How can I auto unchecked the option when it expires?

I know there is a module call scheduler which can help to auto publish and unpublished the node. How about the attribute?

Scheduler doesn't have any sort of integration with Ubercart. Unless there's existing module out there (I've never heard of it), you'll need a custom module that can hook into the attribute option form & display/store your expiration for each option (via hook_form_alter) & disable it when your option expires (via hook_cron).


Why computed field is not getting displayed while creating content I using "computed field" Module. I have installed the 7.x-1.0-beta1 version computed field module. Enabled and save the configuration.

I have created a computed field and just displayed "Hello" in my content type "abc".

But this "computed field is not getting displayed while content creation.

Any ideas why this computed field is not getting displayed.

Try adding the following JavaScript to your theme or in a module (so it's added on the page you are working on with the fields):

It's pretty rudimentary, but it works!  You might want to expand it to work on keypresses rather than .change() events.

Drupal.behaviors.jqFill = {
    attach: function(){
      $('#edit-field-half-und-0-value, #edit-field-full-und-0-value').change(function(){
        half = parseInt($('#edit-field-half-und-0-value').val());
        full = parseInt(+$('#edit-field-full-und-0-value').val());
        total = half + full;

        if(!isNaN(total)){
          $('#edit-field-total-und-0-value').val(total);
        }
      });
    }
  }

Note I got the field names from your other question here.


Contextual filter in taxonomy- Drupal 7 I have vocabularies "destinations" and vocabulary "places". Destinations vocabulary is for example : Europe>France>Paris Place vocabulary is: museums, restaurants, pubs...

I set the path pattern (url alias) for destination content type: [node:field-destinations:parents:join-path]/[node:title]

I also have Place content type [node:field-destinations:parents:join-path]/[node:field-destinations:name]/[node:field-place:name]/[node:title]

Every Destinations content is tagged with destination term and every Place content is tagged with destination term (where is that museum, pub or... located) and also with place term (what kind of place is, is it museum, pub...)

Basically, I want to make views page so when user is visiting Paris page (url alias is europe/france/paris) he should have All places link (in the menu block) pointing on the All places page where he will see listed and grouped museums(3), restaurants(7), pubs(9) or as much as exist for that destination...

I tried everything, I'm sure there is the way to achive it, but I'm missing something...Or am I doing something wrong from the beginning. I'm still not so familiar with Drupal API so I cannot make my own module at this moment.

I suppose that i need views page for all places (grouped by taxonomy term from location vocabulary) and then somehow to pass destination term filter from previous page (europe/france/paris) when the user click to paris he will go on views page europe/france/paris/all-places where he should see Museums (number of museums) and other locations. All that links should link to separate page europe/france/paris/museums views page with, again, listed place content for that destination.

I know this is more than one question but I needed to explain what kind of things I'm trying to achieve.

So, short resume: Can I pass filter term from previous page (term paris) and is there I way to make this grouped place link (Museums (8) Restaurants (22)...) and make them link to separate term page. And, the crucial is to preserve url in views pages, for example all-places page: europe/france/paris/all-places, and for specific place page: europe/france/paris/museums

Can this be done with views module, contextual filters and with some kind of arguments in views url (but Drupal dont allow argument at the first position in url).

Any advice would be helpful, if you have any idea how to achieve this... Thank you very much for your time and help!

This is how I have gotten this working:

First thing you need to do is install the References module
Update your Place content type:

Rather than add a Destination term reference field, you should create a Destination node reference field.

Configure your view.

Under Format > Settings, select Grouping Field Nr. 1 as Content: Places (or whatever you called your places term reference field).
Assuming you have no relationships added, create a Relationship on Content: destination (field_destination) (or whatever you called your node reference field).
Save your relationship.
Assuming you have no contextual filters added, create a Contextual Filter on Content: Nid.
Select the relationship on field_destination (or whatever you called your node reference field).
Select Provide default value with a Type of Content ID from URL.
Save your filter.
Save your view.

Configure View Block

Go to Structure > Blocks
Configure your View Block
Add to region and set Content-Type to Destination.
Save the block.

Now if you go to one of your destination pages, you will see a list of places grouped by place type.


What causes the 'DB Error: unknown error' after adding custom fields to a report in CiviCRM? I have one particular set of custom fields made up of plain text fields and rich text fields. But if I try to add any of them to a report for display, the following error is returned:

  DB Error: unknown error

I don't have this problem with other similar custom field sets, just this one. Is this something anyone has experience before? What's the cause of it?

After turning on the debugging tool,it appears the field label was changed at some point and now cannot be referenced through reporting because the database is expecting the old field label and set name of the database cell to be referenced. It doesn't affect exporting the data though. If you have no access to the actual server then a solution is to create a new field and export and import all the data from the errant field to the new field, as far as I understand.


Error while migrate wordpress to drupal I want to migrate a wordpress blog to drupal. I create an "Article blog" content type with three fields: body, tags and categories (plus default title field). I am trying to import with Wordpress migrate (version 7.x-2.2) via url or file, both solution return same error while importing for each article:

  Illegal string offset 'translatable' File drupal_root/modules/field/field.multilingual.inc, line 176

I am using drupal 7.22 with commons profile 7.x-3.2.
All other imports (tag, categories and attachments) works fine.

Do you have an idea about how to solve my problem?

If you can export the content to a csv format. Then use Feeds to import the csv file to the mapped fields.


Drupal 7 Simple Ajax Module returning 404 I am trying to do a simple Ajax call in drupal 7.
But i get a 404 not found.
I tried with another drupal install and it worked.

Here is the list of the installed modules :

CKEDITOR,
ctools,
entity,
field_collection,
field_group,
pathauto,
references,
token,
wysiwyg

And here is the code :

function bookmark_ajax_menu() {

  $items['ajax-bookmark'] = array(
    'page callback' => 'bookmark_ajax_add_article',
    'access callback' => 'user_access',
    'type' => MENU_CALLBACK,

  );

  return $items;
}

/**
 *
 * AJAX FUNCTION FOR ADD ARTICLE
 */

function bookmark_ajax_add_article(){
   global $user;
           $user_name = $user->name;

   drupal_json_output($user_name);

}

function bookmark_ajax_init(){
    drupal_add_library('system','drupal.ajax');
    drupal_add_js(drupal_get_path('module', 'bookmark_ajax') . '/bookmark_ajax.js', array('scope' => 'footer'));
}

(function ($) {
  Drupal.behaviors.bookmark_ajax = {
    attach:function (context) {

      // If the site name is present set it to the username.
      $('document').ready(function(){
           $('body').load(Drupal.settings.basePath+'ajax-bookmark');
      });

    }
  };
})(jQuery);

The first arg to user_access is mandatory, so you need to provide it in hook_menu via access arguments. The default for access callback is already user_access as it happens, so you can omit that:

$items['ajax-bookmark'] = array(
  'page callback' => 'bookmark_ajax_add_article',
  'access arguments' => array('access content'), // Or whatever permission makes sense.
  'type' => MENU_CALLBACK,
);

After you clear caches the page should be accessible.

Incidentally, you don't need to use jQuery.ready when you're inside a Drupal behavior attach method, as those are only ever invoked on DOM ready anyway.


How can I fetch the Inviter in Rules How can I fetch the Inviter of a user in Rules?
I'm using Drupal 7 and the invite-by-email module (part of the invite module https://www.drupal.org/project/invite), to allow users to invite others.
Now i need to create a Rule that grants points to Inviters whenever their Invitees vote on the site.The voting is controlled with the voting api module, which gives a Rules event.
The event is User votes on a Node
The Invitee is [vote:user]
For the inviter I tried  [vote:user:invite:inviter] but it didn't work.
Been going around in circles, but just can't find the Inviter.

any help appreciated.
d

As a workaround, i ended up using the views rules module at drupal.org/project/views_rules  which "Provides Views directly as Rules actions and loops to seamlessly use view result data."


Connection to AWS MySql server over SSL Running Drupal 7 and trying to enable secure connection between my AWS EC2 and RDS server using SSL.

Php version 5.3.29

I have found some information suggesting the following setup but I'm unsure how to configure this given my own SSL certs and the single certificate bundle I have from amazon?

When I try the below config I get a 500 server error.

Any pointers much appreciated.

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'AWS RDS Endpoint',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array (
            PDO::MYSQL_ATTR_SSL_KEY => '/path_to_your/client-key.pem',
            PDO::MYSQL_ATTR_SSL_CERT => '/path_to_your/client-cert.pem',
            PDO::MYSQL_ATTR_SSL_CA => '/path_to_your/ca-cert.pem',
                     ),
      ),
  ),
);

Figured it out and required SSL via phpmyadmin admin interface for my users.

There are my Drupal database params

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database name',
      'username' => 'username',
      'password' => 'password',
      'host' => 'AWS RDS Endpoint',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
        PDO::MYSQL_ATTR_SSL_CA => '<path to>/rds-combined-ca-bundle.pem',
      ),
  ),
);


hook_ENTITY_TYPE_insert never called Initially I wanted a list of Authors in an exposed filter (as a checkbox) but after looking into BEF (better exposed filters) it seems this isn't possible.

Instead I am trying to create a taxonomy term for each user created but have found regardless of what entity I am trying to create, the hook for insertion is never called.

I am using xdebug and was expecting at least a single breakpoint inside one of the functions to work but it never triggers, I have cleared my cache and other preprocessing functions inside this file (bare.theme).

A few examples of functions I have tried (my theme is called "bare"):

function bare_entity_insert(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_insert(\Drupal\user\UserInterface $user) {}

function bare_entity_create(Drupal\Core\Entity\EntityInterface $entity){}

function bare_user_create(\Drupal\user\Plugin\Core\Entity\User $user){

I feel I have missed something very crucial, perhaps I can't call these functions inside a .theme file?

Yes if you're trying that in a theme then it won't work and will need to be done in a module (Obviously changing the "bare" to whatever your module name is)


Passing node id as contextual filter to field collection view I'm trying to create a view of flagged field collections, filtered by the currently viewed node. I don't seem to be able to add either a relationship nor contextual filter to limit the field collections to those belonging to a single node.

Has anyone managed to do something similar?

Please try the following.

Add a relationship "Field collection item: Entity with the {Field Collection name (field_collection_machine_name)}" You should change the one in {} with your filed.
Now you should get the content nid in the contextual filter which could be used to filter using the node id.
To limit it to show only the flagged fields you should select the "Flags: Field collection item flag" from the relationships and select the flag you want to filter it by and select if it should be for the current user or all users


Applying Patches to Drupal modules - How to deal with error messages? I am trying to apply patch #110 from here in Drupal 7 - ViewsCalc.

I am following the instructions on this page: Applying patches on Mac OS X

When following the instructions, I get this error message:

Perhaps you should have used the -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/theme.inc b/theme.inc
|index 57d61ed..7db435b 100644
|--- a/theme.inc
|+++ b/theme.inc
--------------------------
File to patch:

What should I do?

I've tried giving it the path to the theme.inc file.  When I do this, it displays the following:

No such file or directory
Skip this patch? [y]

As a work around, I have installed Drush Issue Queue Commands and I have applied the following command in Drush:
drush iq-apply-patch 140665-#110

When I use this Drush command, I get the following error message:

Drush iq-apply-patch 140665-1: downloading patchfile                 [ok]
views_calc_grouping_140665-114.patch for project views_calc
Could not apply the patch with either -Np0 or -Np1; perhaps the patch[error]
was rolled for a different version of the project.

What am I doing wrong?

PS. I'm not sure if this is a valid question, as it deals with patching. However, it also deals with topics such as Drush so I believe it is on topic. If it is off topic, please could you direct me to the correct place to post it.

Thanks for all the help. I worked this out!

When I was applying the patch, I placed the patch file in the root module directory. But it actually has to go inside in the directory of the actual module. Whoops!

E.g.

The patch goes inside of sites>all>modules>views_calc
and not inside of sites>all>modules.


How do I set different front pages for domain access sub sites? I am using the Domain Access module and would like to have two distinct front pages. The primary one works as expected, and I have a separate front page template. The secondary domain front page is not picking up the front page template; instead, it is displaying the breadcrumbs and heading just like the secondary pages.

How do I configure the module so that the secondary domain picks up the front page template?

You didn't mention versions, so I will assume the most recent: Drupal 7 and Domain Access 7.x-3.9.

The preferred method requires that your 'secondary front page', as you call it, has a different path than your primary front page.

Make sure the Domain Settings module (part of the Domain Access package) is enabled. This will allow you to specify domain-specific configuration options on several admin forms.

Now, when you go to /admin/config/system/site-information, you will see a fieldset at the bottom of the page saying "Domain-specific settings". Choose the domain for which you want a different front page. Under "Default front page" higher up the form, enter the path of your secondary front page and click the save button.


How to use the admin theme for webform email I would like my html e-mails that are sent after a webform is submitted to use my admin theme. I tried using htmlmail module but that did not work.

Thanks for any assistance.

This has been asked before. You can use a webform email template.

https://drupal.stackexchange.com/a/82501/3279

For the template file you should be able to override the theme assigned to the template by trying one of the many approaches outlined on this page:

Force a page to be rendered in admin theme (overlay mode)


i18n - Not translating Menu's or Blocks The Problem
Using the i18n module, node translations are working, however Menu and Block translations are not showing up.
For example: I created 2 identical blocks. For one i set the Show this block for these languages to English and the other to Bulgarian. When i then go mysite.com it shows me the English block, but when i go to mysite.com/bg it still shows me the English block.
I have also tried the Make this block translatable but that doesn't work either.
The setup
Drupal version: 7.14
Related modules: i18n (all enabled apart from Multilingual Forum), pathauto, localization update, administration language, locale
Background
This is my first Drupal 7 website. The website im working on is a multilingual, multi-country website which is near completion. Hopefully that gives some idea of my exerpience, so if you could tailor your answers to that please.
Thanks in advance.

if anyone else is experiencing this issue, notice that it can also be caused by your configuration in yoursite/admin/config/regional/language/configure, even if you are not using Admin Language Module.

Menus are part of your interface, not of content. So, for example, if you set your interface language detection to default (only use site default language), because you want your interface to be only in english, you are not going to see your translated menu blocks when you navigate to yoursite/anotherlanguage!

Hope this helps someone!


In Drupal, how can I set a role to allow/deny user account requests but not be able to change User 1's password? I created a Drupal 6 site for a client which I, as user #1, will edit and maintain. However, I want the client to be able to allow/deny new authenticated user requests. I have created a new role and assigned it the following user permissons:

access user profiles
administer user
change own username

This works and the users with that role can manage new user requests exactly like I want. However, they now also have the ability to change the User 1 password and do some serious damage to the site.

Is there a setting, permission, or module I can use to prevent this?

User protect: protects specific fields of users from being edited.
Administer Users by Role: lets you decide which roles a user can edit. Assign a dummy role to the admin user and give permissions for every other role.

First one says it is complicated, second one may be a pitfall if you add new roles but don't give access to edit them.


How do I know what variables are available for a theme function? I am using the Menu block module. In one template I have used kpr($page); to see what hooks the menu block is calling. I then created the correct function in my theme's template.php file mytheme_menu_block_wrapper__1(). The examples I have read suggest that this should not take any arguments.

So what I'm really interested in learning is how to debug drupal.

Is there a function that I can call that will show me all the available variables, something like drupal_special_dump() that would show all variables I can use?  Any help would be appreciated.

The Devel module, and it's fantastic dpm() function, is the most widely used debug method for Drupal (at least I'm pretty sure it is).

It can be used on any variable, including arrays and objects, and will post a message to the standard message area containing a nicely structured representation of the variable. It looks something like this:

You would use it as simply as:

function mytheme_menu_block_wrapper__1($vars) {
  dpm($vars);
}

FYI I think all theme functions in Drupal 7 will receive at least one argument which will contain the data for that theme function. That argument is represented by $vars in the above example.

If you're looking to get hold of a list of variables that have been defined for the whole page request you might want to look at the PHP get_defined_vars() function instead.


How to add a Related Products View for Commerce Kickstart? I am trying to show related products in the products display for Commerce Kickstart. I tried using the method outlined in this tutorial but ran into a couple of issues:

The "Target Type" in the entity reference field (the field used for the related product) does not show "Node" as an option.
The SQL error mentioned in the tutorial appeared when selecting "Aggregate" in the view.

The bottom line is I couldn't get this to work of Commerce Kickstart.

Has anyone had any success in getting this to work for Kickstart, or an alternative approach?

Thanks in advance for any insight into this.

If you want to be able to reference nodes, your view must be taxonomy-based and utilise product categories. The category must be on the display node, not on the product and this is a good starting-point to understanding what's required. To see if this idea is relevant to your use-case, go here: http://www.bookfish.co.za/catalogue/gorongosa-joao-augusto-silva  Bear in mind that I'm not using Commerce Kickstart but various Commerce modules on that site but it should work with CK.

To display my products, I added the following relationships & what I selected there to get it to work I have put in square brackets [ ]:

Content: product [required]
(Products referenced by field_product)Commerce Product: Referencing Content [required]
(Content referencing products from field_product) Content: Taxonomy terms on node [required, select the vocabulary you want, identifier: term]
(term)Taxonomy term: Content using Category [required, identifier: field_category]
(field_category) Content: Category (field_category) [required, relationship: field_category, identifier: term from field_category]
Content: product [required, relationship: field_category, products referenced by field_product]

for contextual filters:

(field_category) Content: Nid [Relationship: field_category,

When the filter value is NOT available:

select "provide default value",

"type": Taxonomy term ID from URL

select  "Load default filter from node page, that's good for related taxonomy blocks" and "Limit terms by vocabulary"

select your relevant category

"Multiple-value handling" select "Filter to items that share all terms" or whatever is relevant to your use case

under "More" select "Exclude"]

Aggregation settings: [Group results together]

Content: Nid [Relationship: do not use a relationship,

When the filter value is NOT available:

select "provide default value",

"type": Content ID from URL

When the filter value IS available or a default is provided:

select "Specify validation criteria"

Validator: "Content"

Content types: select the relevant product display

Filter value format: "Node ID"]

Aggregation settings: [Group results together]

I then selected a view format of fields showing title, image, price and hidden fields of "add to cart form" and "stock" so that I could filter to relevant products that are in stock. For aggregation, I used "Group results together" and "entity ID"


unable to get webform submissions into our mail I'm unable to get webform submissions data into my default mail,but
  when submitting form i have received mail.getting below Body in my mail

Submitted on

Submitted by user:

Submitted values are:

The results of this submission may be viewed at:

Above name's comming from webform-mail.tpl.php file in webform module

<?php print ($email['html'] ? '
' : '') . t('Submitted on [submission:date:long]'). ($email['html'] ? '
' : ''); ?>

<?php if ($user->uid): ?>
<?php print ($email['html'] ? '
' : '') . t('Submitted by user: [submission:user]') . ($email['html'] ? '
' : ''); ?>
<?php else: ?>
<?php print ($email['html'] ? '
' : '') . t('Submitted by anonymous user: [submission:ip-address]') . ($email['html'] ? '
' : ''); ?>
<?php endif; ?>

<?php print ($email['html'] ? '
' : '') . t('Submitted values are') . ':' . ($email['html'] ? '
' : ''); ?>

[submission:values]

<?php print ($email['html'] ? '
' : '') . t('The results of this submission may be viewed at:') . ($email['html'] ? '
' : '') ?>

<?php print ($email['html'] ? '
' : ''); ?>[submission:url]<?php print ($email['html'] ? '
' : ''); ?>

Please help me I'm new to drupal

I have disabled all dependent modules for token and then disabled token module also again enabled all modules now working fine.


Is checking the value of $order->status sufficient to understand when an order has been completed? If I want to use this hook in order to execute a code when the order is complete.
function hook_commerce_order_update($order) {
  if ($order->status == 'completed') {
    // ...
  }
}

Is this condition sufficient, or should I add the following in order to prevent the confusion with the complete status that belongs to the checkout state?
 if ($order->status != $order->original->status) {
    $status = commerce_order_status_load($order->status);
    $state = commerce_order_state_load($status['state']);
    if (($state['name'] == 'completed') && ($order->status == 'completed')) {
      // ...
    }
  }

All the checkout order statuses are prefixed with checkout_, so there is no need to check the state. Just bear in mind that in Commerce 1.x, an order may be moved into and out of that status multiple times. If you need to ensure an operation only occurs once per order, you can follow the core precedent of logging the timestamp for your operation in the $order->data array.


Jquery toggle show/hide fields Hi I would like to offer a toggle show/hide for some fields that are not mandatory. Is there is a modules for this or would it be a case of using a template and jquery.

You can put the not mandatory field in a group installing Field Group.
The group have a 'collapsible' option.


How to programmatically set node field values. I have a content type.  I have firstname, lastname and email address fields.  I need the default value for each field to be the firstname, lastname and email address of the user profile.  Also, I need to prevent the user from modifying these values. The user should be able to see the values by default, but the user shouldn't be able to edit them.

You can create a custom module and add use hook_form_alter to change the default_value of your field and change them to #disabled => true. Here is an example. Don't forget to chage modulename to the name of your module and form-id to the id of your form :-).

function modulename_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form['#id'] == 'form-id') {
        $form['field_name'] = array(
            '#disabled' => TRUE,
            '#default_value' => $user->name
        );
    }
}


Using hook_theme_registry_alter() I am using hook_theme_registry_alter() in my custom module for overriding the theme function.
I have done something like this in my module file aml.module

function aml_theme_registry_alter (&$theme_registry) {
  $theme_registry['aml']['function'] = 'theme_menu_item_link';
  dsm($theme_registry);

}

function theme_menu_item_link () {
  drupal_set_message("hello");
}

I don't know how and where to implement this function theme_menu_item_link

I think you are trying to alter a $theme_registry['aml']['function'] which doesn't exist.

Try have a look through the $theme_registry array, and find what you want to override, put this in where you currently have "['aml']". I am guessing you want "['menu_item_link']", but you will have to check.

Then change theme_menu_item_link to aml_menu_item_link.


Core Drupal8 JS necessary for Drupal theme to function I have recently noticed that Drupal8 is adding number of JavaScript files. I would like to know if it is necessary for theme to function

<script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
<script src="/core/assets/vendor/jquery/jquery.min.js?v=2.2.4"></script>
<script src="/core/misc/drupalSettingsLoader.js?v=8.3.7"></script>
<script src="/core/misc/drupal.js?v=8.3.7"></script>
<script src="/core/misc/drupal.init.js?v=8.3.7"></script>

My theme does not use any of them. I would like them to be removed. Can anyone here tell me how to remove them?

In your .info.yml file specify:

libraries-override:
  core/drupal.active-link: false

You may have to remove more libraries, but this one is specifically for the files you mentioned.


Associate a content type to a specific group in drupal commons How is possible to create a content type associated by default to a group in Drupal Commons?

I will try to explain. I have two groups: literature and art. Literature will have three content types i.e. poetry, fiction and novels. Art will have painting, photography and drawings.

I've created contents types and i've tried to associate them with the respective group by flagging the group and group content checkbox but nothing changed. I also followed the steps described here https://www.drupal.org/node/2014781 but when I try to add some content I still see the "Post to specific groups" radio option and select.

Help please!!!

I am assuming you are using one group content type, and "Literature" and "Art" are contents of that group type.

Tell me if I am wrong in my assumption.

You can use hook_form_BASE_FORM_ID_alter() to set a default field value for group field based current content type.

    function mymodule_form_node_form_alter(&$form, &$form_state) {
      $node = $form_state['node'];
      if (!isset($node->nid) || isset($node->is_new)) {
       global $user;
       $groups = og_get_groups_by_user($user);
          if(is_array($groups)) {
          // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
          if($node['#bundle'] == "poetry" || $node['#bundle'] == "fiction" ||$node['#bundle'] == "novels") {
          $form['group_field_name']['#default'] = $groups[0];  //Whatever index Literature has
          }
          elseif($node['#bundle'] == "painting" || $node['#bundle'] == "photography" ||$node['#bundle'] == "drawings") {
          $form['group_field_name']['#default'] = $groups[1];  // Art's index
          }
          }
      }
    }


How can I force the user to select dates that have passed when using the Date picker in the form API? I need to use a pop up date picker from the Date module in the Form API.  It's displaying OK, but I want to restrict the user to only have the option of selecting dates that have passed, and not future dates.

How can I achieve this?

Here is my code:

$form['fieldset_one']['date_field'] = array(
  '#weight' => '5',
  '#title' => t('Date of Birth'),
  '#type' => 'date_popup',
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '-80:0',
);

They are talking about datepicker options here: Customize days that can be clicked on a Calendar popup

Apparently datepicker is quite versatile, with those options you can set max-date, min-date etc.


How to configure the toolbar in CKEditor? I've installed CKEditor in my drupal instance and all seems to work well until I realized, I can't change the text size (missing drop down). I went to admin/config/content/ckeditor and selected and saved Toolbar full from the examples, which feature a Size dropdown as shows in the "current toolbar' preview. I did this for both existing profiles, Advanced and Full. However, if I then go to admin/structure/block/add to add a new block, CKEditor still does not show a size drop down so that I could change the text size. Why not, what am I missing?

EDIT 1

I went to http://ckeditor.com/download and downloaded the full package which I then just copied to my existing sites/all/modules/ckeditor/ckeditor overwriting the existing standard package copy. I've reset the cache`, however what I'm seeing now is this:

The Size drop-down is visible but other buttons have failed to load their icons.

Any suggestions?

It's possible you are using a version of CKEditor (the editor, not the drupal module) that doesn't have the font size and family plugin.

See the different versions at http://ckeditor.com/download (click the "Compare packages" link to see what is included in each package).

On that page you can see that only the full version has the "Font Size and Family (font)" package, so if you are using one of the other version then it won't have that package.

It is also possible to use the "Or let me customize CKEditor" option to create a custom version of CKEditor that contains just the plugins you require.
If using that make sure you include the "Font Size and Family (font)" package.

There is an issue here on Drupal.org regarding messages to the admin to notify them of missing plugins.


Removing/Restricting for wrapper by role I want to remove the div that holds the comment wrapper from a content type. What is the best wayto do this?

I could create a module, but I think I would only hode the form and not the headers that are inside the wrapper (just outside the form).

I guess I could hold it via the template, but I'm not sure how to pull the roles.

Thanks

If it's Role based, why not remove the permission for that Role to View or Post Comments under admin/people/permissions?

If you need more granular control, try the Comment Permissions Module (https://drupal.org/project/comment_perm)


Only show menu level 2 from active trail (with option Show as expanded) I'm trying to do something pretty basic in my perspective, but I keep failing at this simple task.

My website has a main menu that is displayed on top of the page that is 2 levels deep (hence the Show as expanded). On the left toolbar it has another display of main menu, starting from level 2.

I have a main menu that looks like the following:

-link 1 (has option show as expanded)
--link 1.1
--link 1.2
-link 2 (has option show as expanded)
--link 2.1
--link 2.2

Problem now is that in the left toolbar all my level 2 links are always displayed, probably because I expand them. But I only want to view the children from my active trail.

Is this possible at all with the current setup? When I deselect Show as expanded, my top menu doesn't show the second level (except when I click the first level first = active trail).

Another problem with this new (menu) block system is that I use a template to render my main menu: menu--main.html.twig but both my top and left menu use this template. Is there any best practice to separate the templates?

I also discovered that if "Show as expanded" is checked, the menu is displayed at sublevels where it should not appear. This patch fix this behavior:

https://www.drupal.org/node/2631468#comment-10792980


Is there a way to use Translation Overview with Entity Translation? When I use the Internationalization module with Translation Overview all works fine, I can see through admin/content/translation-overview-manage the state of the translations of nodes.

But when I use Entity Translation I can't see this information. I've been searching for some info on the net, but I can't find anything about this.

So, is there a way to use Translation Overview in combination with Entity Translation?

Maybe you should consider switching from the Translation Overview module to the Translation Management Tool module, which allows all Drupal text elements to be used as source for translation. I.e. Nodes, Entities, I18n Strings (Menu, Terms etc.).

That's also what seems to comply with what is written on the Translation Overview project page, i.e.:

  ... The superseding Translation management (TMGMT) module was initiated with Drupal 7 and is already well ported to Drupal 8. We highly recommend it - already with Drupal 7.


Menu disappears on small screens On this site I implemented the Multi Level Push Menu. All works fine, but the menu disappears on small screens (tablet width and below). I use Bootstrap 3 und Drupal 7 in this project.

I already tried it with increasing the z-index on #menu, but it didn't worked.

I'm thankful for any suggestion.

According to this the problem, was that a div container pushed the menu away.

The old and wrong container was:

It could be fixed by adding additional bootstrap classes:


TinyMCE Filtered Html is stripping in line styles Is there anyway to allow inline styles.  When setting a table width, using the Table icon width field, the width gets set as an inline style for the table tag, and that gets stripped out.  How frustrating!

Anybody have any solutions?

if you use filtered html it is by default remove any inline styles or class attribute also javascript tags
you have to make it full html that allowed style
If you want to use filterd html you can use wysiwyg_filter module

It give you control which attibute you can use so you can add inline style


Search button with 'lens' icon on the exposed view's filter - Drupal 7 I can't figure out how to make a search button on the view's exposed (as a block) search filter to be styled similarly as in Drupal standard search form, with a 'lens' icon. The examples for hook_form_alter() I found using:

$form['submit']['#type'] = 'image_button';
$form['submit']['#src'] = base_path() . path_to_theme() . '/images/search-button.png';

-don't seem to work correctly, as image on the button just doubles (png file includes both 'active' and 'inactive' images of lens). Could there be a straightforward way for the search button 'lens' styling, not including CSS/templates modifications?

The code you posted is good. The only "problem" is that your lens image is "sprites" image - designed to be shown only partially, depending on the state of your button. There is no standard for this, so Drupal does not support this. You ave two options there:

Cut your image, leave only the part you need.
Use CSS to implement sprite style your image was created for.


How do I use the computed twig element to get the value from a custom composite element? I have created a custom composite element by cloning the example module of Drupal 8 Webforms. It has a radio button and 4 select boxes. So when clicking 'Add" button, another row is being created, and likewise a series of 10 clicks would make the page too lengthy.
I need to list out a selected element ( Product ) in another table beneath the custom composite, and hide the filled row when the 'Add' button is clicked.
Since I am relatively new to Drupal 8, I have no idea how to achieve this. I tried using computed twig to fetch the data from products table using the syntax {{data.products.product}} where products is the key of the custom composite element & product is the select field inside the composite element. I didn't receive any output following the above syntax.
Could anyone help me out here ?

I suppose I can answer my own question.
It didn't work because I didn't use the delta. For this to work, I need to do this instead
{% for data.products as p %}
{{ p.product }}
{% endfor %}

This is because we are using a custom composite element where the products are stored like
$products[0]['product']
$products[1][product']
...

I missed the array key and hence didn't get any value to the element in the custom composite.
FYI: The answer was in the 'Help' section of the module already, but couldn't really understand it well at the time.


How to create commerce product content using date repeat entity module? I am using date repeat entity module in a content type say Movies to successfully clone the nodes.I also have a commerce product reference field in that content type which is working fine when I am not using repeat date.
I want to be able to create a new commerce product content for each node in the series when using repeat date.(while creating the Movies node I can see product fields like SKU,product title etc.)

For example,
I am creating a new Movies having start as 1st Jan 2016 and end date as 2nd Jan 2016.I want to repeat this event for every Friday till 31st Jan.
Now there will be 5 nodes created automatically.
how do i create a new commerce product content for each of these nodes?

Thanks.

I'm not too familiar with Date repeat entity module, but why don't you try implementing hook_node_insert() in a custom module, to handle creating a new product every time a a new node is created:

/**
 * Implements hook_node_insert().
 */
function my_module_node_insert($node) {

  //check type and that no product set previously
  if($node->type == 'my_type') {

    //create product
    $cp = commerce_product_new('product');
    $cp->is_new = TRUE;
    $cp->revision_id = NULL;
    $cp->uid = 1;
    $cp->status = 1;
    $cp->created = $cp->changed = time();
    $cp->sku = 'My SKU';
    $cp->title = 'My Product';
    $cp->language = LANGUAGE_NONE;
    $cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
      'amount' => 1000, //$10.00
      'currency_code' => 'USD',
    )));

    //save new product
    commerce_product_save($cp);

    //set reference field
    $node->field_product['und'][0]['product_id'] = $cp->product_id;

    //update node
    node_save($node);
  }
}

I haven't tested this code, but this would be the general approach I would try.

This would only work if the Date repeat module invoked this hook though.


Modules ".module" file not being called when anonymous user I think I have a persmissions problem but I'm not sure how to resolve it.

I've made a custom block in a module called "people_passed". When I'm logged in the block displays fine, when I'm logged out the block HTML displays but the CSS does not. I've figured out that this is because people_passed.module is not being called and so the CSS is not displayed.

Here is the contents of my people_passed.info:

name = People Passed
description = A block that shows how many people passed in the last year.
package = Other
core = 7.x
files[] = people_passed.module

If your module file defines a block, but isn't being parsed, then the block wouldn't work at all; you'd get all sorts of fatal errors, not missing CSS.

You've probably got page and block caching turned for anonymous users...that'll be why your exit code doesn't run. Try clearing the caches, it should make a difference.


How to prevent taxonomy terms being duplicated on node form? I have a content type book and it has two taxonomy term reference fields (free tagging, autocomplete):

author
publisher

Both two taxonomy reference fields have taxonomy terms from the same vocabulary: people.
While creating new book content, if I enter the same taxonomy term for both author and publisher, it double creates the same taxonomy term (if  entered taxonomy term didn't exist before).
I don't want to use different vocabularies for these taxonomy reference fields.
How to prevent taxonomy terms being duplicated on node form?

Though there is a module for help with taxonomy term being duplicate here, but like module page says, it doesn't work apart from taxonomy term and vocabulary forms.

So a solution I can think of in your scenario is to use hook_node_presave and compare value of both fields. If it match, you can think of some logic such as, create single term & set newly created tag for both fields.

Other hook can also help you such as hook_node_insert with your own logic to tackle this. Happy Coding !!


How do I do git clone with drush to download the HEAD version of a module? Is there any way to clone or pull the HEAD version of a module in drupal.org git repository?

For example, if I'm on Drupal 7, and the last branch of Views is 3, I would like to do:

drush git-clone views

to achieve something equivalent to:

cd sites/all/modules/
git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git

Ideally, using drush git-clone views-3x should clone the 3.x branch explicitly.

Is this possible or am I dreaming? This would be really useful for developing.

drush dl views-7.x-3.x --package-handler=git_drupalorg

Update:

True, if there are commits after the dev release was packaged, you will need to run git pull to advance to HEAD after checking out via drush dl.  If there is no packaged dev release, and Drush checks out a stable release, then you need to run git checkout 7.x-3.x after drush dl.

There is no Drush command to do a verbatim git clone; part of the "value add" of drush dl is that it grabs published releases.  If git clone is what you want, perhaps a short bash script would be your best solution.  Something like this:

Usage:

$ clonedev views 3

Example script:

#!/bin/bash

MODULE=$1
VERSION=$2

DRUPAL=$(drush status "Drupal Version" --pipe | sed -e 's/\..*//')
if [ -n $DRUPAL ] ; then
  cd $(drush drupal-directory modules)
else
  DRUPAL=7
fi

git clone --recursive --branch $DRUPAL.x-$VERSION.x http://git.drupal.org/project/$MODULE.git

Modify to suit.


Server 500 error in a View which is working perfectly outside of the admin area I have a View which is affected by several hooks ( views_pre_viewand views_query_alter, mainly). It works perfectly in the final user area, but when I am logged and go to the Views GUI, the browser displays the following error message:

 An AJAX HTTP error occurred.
 HTTP Result Code: 500
 Debugging information follows.
 Path: en/admin/structure/views/view/NAME_OF_VIEW/preview/block/ajax
 StatusText: Internal Server Error
 ResponseText:

I see no error loging in the recent log messages, the browser keeps working, I can modify the View, but I am worried that something may broke later in the final user area. How can I debug what is happening? I have no previous experience in Devel or similar.

You are going to have to access the PHP error log file to determine the cause. Drupal may not always log an error since it the error may stop it from running. I would contact your host to see if they can provide you the log.


Fire custom submit handler in form embedded in node edit form I have a form that is being inserted inside of a node edit form and the inserted form is given a custom submit handler. The inserted form's submit button is defined as follows:
    $form['decision_select']['update'] = [
      '#type' => 'submit',
      '#value' => $this->t('Select Segment Set'),
      '#submit' => [[$this, 'updateSegmentSet']],
      '#limit_validation_errors' => [],
      '#ajax' => [
        'callback' => [$this, 'updateSegmentSetAjax'],
        'wrapper' => $wrapper_id,
      ],
    ];

However, when I click 'Select Segment Set' the entire node form is submitted to the backend (I've verified this by printing the request/route objects sent to the backend). Is there any way to press that submit button and have only the inserted form sent to the backend along with this custom submit handler? The idea is to have this inserted form filled with values given to it via ajax before the node form is ever submitted to save the node.

I came across https://www.drupal.org/forum/support/module-development-and-code-questions/2015-09-03/put-a-custom-form-inside-node-form which, while old, claims that what I wanted to do is not possible. To get this to function the way I wanted I:

Attached a JS event handler to the embedded form submit buttons that performed .preventDefault()
This handler then .ajax'd a custom route that I created.
In the Controller for that route, I had to perform all the primary operations for submitting the form and return markup back to the .ajax call.


Webform alter with ajax submit callback - field values are empty in callback At this point I'm doubting if I'm doing it the right way, but I'm struggling with an issue:
I'm adding an Ajax callback to the form alter of a specific form:
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'webform_submission_matching_node_218_add_form') {
    $form['actions']['submit']['#ajax'] = array(
        'callback' => 'matching_api_call',
        //'event' => 'click',
        'effect' => 'fade',
        'speed' => 500,
        'wrapper' => 'block-matchingblock',
        'progress' => [
            'type' => 'throbber',
            'message' => t('Matching...'),
        ]);
    }
}

The callback works fine but when I call $form_state->getValues(), I get an array with all my fields but they are simply empty or 0.
My callback function:
function matching_api_call(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // ajax debug
    $response = new AjaxResponse();
    $selector = '#block-matchingblock';
    $content = print_r($form_state->getValues(), true);
    $settings = [];

    $response->addCommand(new HtmlCommand($selector, $content, $settings));
    return $response;
}

My output:
Array(
    [field1] =>
    [field2] =>
    [field3] => 0
    [field4] => 0
    [submit] => Match
    [form_build_id] => {formbuildid}
    [form_token] => {formtoken}
    [form_id] => {form_id}
    [op] => Match
)

The entry is added in the backend so it does get submitted. Should I do something else because I'm using Ajax here?
Thanks in advance.

Someone guided me in the right direction. My Webform Confirmation setting was set to 'None'. After setting it to 'Inline', calling $form_state->getValues() finally returns the form values.


After calling drupal_flush_all_caches, menu items with access callback TRUE are giving access denied error I was building a custom module that affected the front page and I found myself having to go clear the caches for it to take effect. So as part of the code, I put in drupal_flush_all_caches().

After I ran the page, my website had all sorts of issues. It seems like any menu item with 'access callback' => TRUE, is getting access denied errors for any user. These items were working fine before the cache clearing.

Current versions (yes I know I need to upgrade)

Drupal: 6.38
PHP version: 5.6.38
Server: Red Hat Enterprise Linux Server 7.5 x86_64

PHP ini values:

session.cookie_httponly Off
session.use_only_cookies    On
session.cookie_secure   Off
session.hash_function   0
session.cookie_domain   .example.com

Things I have done:

Checked users table for uid of 0 - exists with status of 1, has role of anonymous user, has permission of access content
Repaired database tables
Clear browser cache
Clear drupal cache (/devel/cache/clear)
Rebuild menu (/devel/menu/reset)
Clear db sessions table

Please let me know if you need additional information. Thank you.

The answer lies in some custom code I wrote to understand why some unrelated things were issuing an error. I discovered it was this when I was copying the code to my test site and then putting in this new code which resulted in the same issue on the test site. So that is how I was able to narrow it down. Going forward, I am going to have 3 sites, one for new development, one that mirrors the live site, and the actual live site. The issue comes from being in the middle of upgrading modules on the test site and so I couldn't really use it reliably to test new code, so I would code it on the live site (a big NO-NO and I really shouldn't have done this). The only reason I didn't my custom code was an issue was because I hadn't cleared the cache in a while, so the menu items were still available.

Maybe this will help someone in there processes to not be dumb like I was.


Extra aliases in the url_alias table In a module, entity_save is being called 2 times. Each time it's called, an extra alias row is being added to the url_alias table. I couldn't find any paths being saved in node_save.

Is this expected behavior?

The entity type I'm dealing with are nodes.

I found some code within the module that was placed as a work around for issue https://www.drupal.org/node/936222. Now that it's fixed, all is well.


Can computed fields be added to a custom entity? How can the "computed field" contrib module's (drupal7) fields be added to custom entities (based on the entity API module)?

Or will the computed field work with nodes only?

Yes, I found that entities can take computed fields.

A very easy way to achieve that, is by the 'data' module. It takes any extra database table. Can expose that table as an entity automatically. That entity can take normal fields, in addition to it's database table field. It does all the heavy lifting in place of entity API.


Change Taxonomy Page to display first node in full By default in Drupal 7, a taxonomy page lists the titles of all the nodes that have been tagged with that term.

Is there any way to make it so the page shows just the first node that is tagged with that term?

I want it so the first node is displayed in full (Ideally, the term page should automatically take the user to the first node).

I know you can use Views to override a taxonomy and control what content is shown. However, I would like to do this without views (i.e. so the user is seeing the acutal node as opposed to a view of the node).

I also want it to happen automatically (i.e. for every term, the first node should displayed. The admin of the site should not have to manually set up this state for each individual term).

The way to do this is to enable the "Taxonomy term" view in Views:

Add and offset of 1 to the page view:

And then add and Attachment display that has a pager with an Offset of 0 and an Items per page as 1. On the attachment you can switch the Format to show full nodes instead of teasers.

This will work "automatically" for all Taxonomy terms. The reason this works is that the view takes an argument of the taxonomy term in the URL.

It overrides Drupal core's url for Taxonomy terms and uses the view as a replacement.


Drupal Calendar highlight all days in block with views I have calendar showing dates (start and end dates). When I create a calendar from the views template it adds several displays. The month display shows shows all days from the start to the end day highlighted with another color. But in the block display it does not highlights those days.

Below is the month display. I need the same in the block display.

This is a theming issue.  Inspect the classes of the boxes in the calendar, you will probably find .current-month or something similar in there for the boxes in the month being shown.  Then edit your theme's CSS (or SASS) with:

.current-month{
  background-color: [color-you-desire];
}


Migrate two user fields (translation) to translation I'm trying to migrate two user fields in Drupal 7 (name in two languajes) to a translated field in Drupal 8.
I have tried several options but all failed.
I have two yml templates (one for the user and another for the translation with parameter translations:true) but not working.
The user is migrated correctly.
The translation of the user is created correctly.
The field of the user is correctly but the translated field is not translated.

These are a part of the yml files...

migrate_D7_user.yml

source:
  plugin: d7_user
process:
  uid:
    -
      plugin: get
      source: uid
  name:
    -
      plugin: get
      source: name_english
  langcode:
    -
      plugin: default_value
      default_value: en
destination:
  plugin: 'entity:user'

migrate_D7_user_translation.yml

source:
  plugin: d7_user
  translations: true
process:
  uid:
    -
      plugin: migration
      source: uid
      migration: migrate_d7_user
  name:
    -
      plugin: get
      source: name_spanish
  langcode:
    -
      plugin: default_value
      default_value: es

destination:
  plugin: 'entity:user'
  translations: true

Thank you in advance,
Juanjo.

Now it works.  There was a problem with the migration of the user admin (user/1). If you migrate admin user, then you can't edit translations of any user.
Now I put a custom source plugin with function query() overwritten:

/**
   * {@inheritdoc}
   */
  public function query() {

    $query = parent::query();

   // Only migrate users not admin (1)
    $query->condition('uid', '1', '<>');
    return $query;
  }


How do I use an OR condition in an exposed filter? I have a view with more than 10 checkboxes for the multiple selection in exposed form with some field. Using the Drupal exposed filter for the multiple fields make the query of AND, but somehow I need the multiple selections in OR condition.

Is there any way to change the query to use a OR condition?

You can make view filter with OR condition by clicking on And/Or, Rearrange link.


Taxonomy Access module with role After install Taxonomy Access and access the basic admin content page "admin/content"
with an admin role called "publisher" which has the authority to administer the content the page does not show any content at all as in the attached image
even i created admin views to show specific content and it works well with the "publisher" role, any reason why the basic admin page is empty !?

It was from the custom relation i made to the Administration: Nodes (Content),
now it works after removing the unneeded relations.


how to create a free shipping coupon code in drupal commerce coupon code with free shipping ,example if coupon is applied to the order, estimated shipping rate (of $4.95) should become $0.00,i have a expedited_shipping in shipping methods with base amount of 4.95 which will be applied on order .how should i create a coupon for making the expedited shipping to amount zero.

Use Commerce Discount and Commerce Coupon.

Create a discount that uses the Free shipping offer.
Set the conditions (if any).
Add a coupon that links to this discount.

Now when the coupon is added to the order and the conditions (if any) are met the shipping method specified in the Free shipping offer will free.


Views gives wrong path I use Drupal Commerce module and Views Slideshow. In Fields I have this (Products referenced by field_product) Commerce Product: Product Image field and in Relationships Content: Product, it is an image field and selecting Link image to: Content it links it to admin/commerce/products/4 when the product display for user is node/5

What I do wrong?

The answer is only a google search away..

https://drupal.org/node/1108180