Add location(s) to user account I have a Content Type called locations. I need to be able to assign these to Drupal users. Some users will have multiple locations.

Is there a module that will let me do this, or what are some suggestions you all might have?

There is a way but it may not be ideal depending on how far you are along in your site development. The way you would link content to content is through the node_reference field that comes with the CCK module. The problem is that this doesn't work with Drupal profiles in 6.x, only nodes. One solution is to install the content profile module

http://drupal.org/project/content_profile

which allows you to create a new content type for your profiles. From there, you would just add a field of type 'node_reference' to your new profile content type and connect it to 'locations', and allow the user to make multiple selections, etc.

Of course this is less than ideal if you already have a significant number of profiles on the system but there is a migration path from the core drupal profile data to the new type in another module:

http://drupal.org/project/profile_migrate


Create contextually filtered view of shared fields across multiple content types I have a content type "Construction Job" with the title field renamed "Job #". When we create a new job, we assign it a unique job number in the title field.

I have two additional content types, "Update team 1" and "Update team 2". These content types have different fields because the work being done is different, but they share a field called "pictures". Each content type also has an entity reference field to the "Construction Job" content type so we can tie them together.

I'm trying to create a dashboard type display with various different views so management can review jobs with all of the information in one location. I'd like to create a slideshow off all of the pictures uploaded from either of the two update content types, and contextually filter that slideshow so that only the images from the updates for that particular "Construction Job" are shown.

I can create a separate slideshow view for the pictures from each respective Update type, but then I'm left with two separate slideshows on the same page. I'm trying to combine this into one slideshow as we're looking at adding a third different Update content type.

I've tried adding a contextual filter for each entity reference field from the two independent content type, but that doesn't work. That is I can create a contextual filter for the entity reference field for the first content type, but the view then eliminates all images from the second update content type. When I add the second contextual filter, the view returns no results when I enter a value in the filter preview.

I haven't tried anything exactly like this buts it sounds like it is very possible if you mess with your AND, OR settings. Since they share the same field and that is what you are filtering on there should be no issue with that being your contextual filter.

Look at your regular filters under 'Filter Criteria'. Filter on the content type in an OR group using 'And/Or, Rearrange' (the arrow next to 'Add'). And it should work.


add title to front page teaser news feed I would like to add a title to my news feed. I have tried to edit node--teaser.tpl.php and added

<?php if($page['feed-title']): ?>
<!-- start feed title -->
<?php print render($page['feed-title']); ?>
<!-- end feed title -->
<?php endif; ?>

on top, then I added

regions[feed-title] = Feed Title

in my theme.info file. I created a block which is assigned to this region but still, nothing is being displayed, why not? Am I doing something wrong or can I not add regions into a region template file?

Thanks!

If you look at the page.tpl.php template file used by the Bartik module, you will notice it uses code like the following to render a region.

  <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

      <?php print render($page['triptych_first']); ?>
      <?php print render($page['triptych_middle']); ?>
      <?php print render($page['triptych_last']); ?>

  <?php endif; ?>

node--teaser.tpl.php is not used to render a page, but a node into a page. It is hierarchic, someway: html.tpl.php wraps the content of page.tpl.php, which wraps the content of node.tpl.php.
Regions are part of a page, not a node; therefore, the template file where to render the regions is page.tpl.php or any suggested templates used instead of that one.


How to override breadcrumbs defined by a module using a custom module? Is it possible, using a module, to override a breadcrumd definition defined in another module's hook_node_view()?

Module property_bc sets a custom breadcrumb for nodes of type Property.
Module property_bc_plus wants to override that behaviour.

property_bc implementation of hook_node_view would be:

<?php
/**
 * Implementation of hook_node_view().
 */
function property_bc_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'property') {
    $breadcrumb = array();
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
    $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
    drupal_set_breadcrumb($breadcrumb);
  }
}

Different solution depending of your context.

Change the module order by changing their weight: http://drupal.org/node/110238
Use an other hook than is called later like hook_node_view_alter
Add a flag in your node and test against it

First module

 <?php
 function property_bc_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property') {
        $breadcrumb = array();
        $breadcrumb[] = l(t('Home'), NULL);
        $breadcrumb[] = l(check_plain($node->name), "user/$node->uid");
        $breadcrumb[] = l(t('Properties'), "user/$node->uid/properties");
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }
    }

In your other module

    <?php
    function property_bc_plus_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'property' && isset($node->custom_bredcrumb_is_set) && $node->custom_bredcrumb_is_set != TRUE) {
        $breadcrumb = array();
        $node->custom_bredcrumb_is_set = TRUE;
        drupal_set_breadcrumb($breadcrumb);
      }

}


Change URL of Node Title Bit of an odd request. I want to somehow change/alias the URL of a node to an external website. We are importing a calendar of events from our booking vendor to show nicely on our page. In the end, the user must go to the booking vendor website to enroll though. While I want all the imported data to be able to be shown on our website (so we can show snippets in blocks, and so forth), I want the node link to go to the event on the booking website. Our import does include the booking URL for each event.

I tried using the rules module to overwite the node:url on import, but it obviously does not allow this. I assume I could work some wizardry in views, but I would need the URL to change for blocks, calendar views, list views, etc. Is there some way to make a node always redirect to an external URL based on the import I am using "Feeds import" with an iCal feed?

To make it harder, I also lack any code level access.

This is probably a hail mary, but I figured I would ask. Thanks!

Ok so since you already have a url field:

Set up a new rule where the event is Content is viewed of type YourContentType.
Add a Page redirect action.
For the destination use your field as a replacement pattern. So something like: node:field-url.

Just take note that you won't be able to view your content with this rule. But you can still access the edit page using the content management interface.

Just for your information, if you DO get access to the code:

You can use hook_node_view to create redirects. Since you already have the event URL in the node data you can use a drupal_goto.

Here's a snippet I found in a related question. I changed some things though.:

module_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && "Conditions") {
    // Change $node->url to what works.
    // Use the devel module and krumo() to check the contents of $node.
    drupal_goto($node->url);
  }
}

I've assumed you're using Drupal 7.


Problems with OG private groups I've installed a drupal commons site (7.x-3.23).
I'm trying to give ability to choose on group creation if the group content will be visible or not from non-members of the group.
So i've activated organic group access control, rebuilt permissions, added in OG the field 'group content visibility' to the commons group bundle.
When i go to the group content type i see the field so it must be OK.
But when i create or edit a group, i never see the option for privacy content.
I opened the fields settings in group content type for the content visibility, and all seems fine in spite of the default value which is not displayed.

Can you help me?

There are two different fields:

Group visibility. It only exists for Groups. It controls whether all group content is visible to non-members by default.
Group content access. It only exists for Group content. It controls whether a particular node in the group is visible or invisible to non-members, or whether it should leave that decision to the default setting of the group.

Check whether your group has a group visibility field and whether you have the permissions to edit it, and if not, add that field via /admin/config/group/fields and grant the right permissions to edit it.


Is this the proper way to add a 'class' attribute to a form date element $form['stop_date'] = array(
  '#type' => 'date',
  '#title' => t('Stop Date'),
  '#default_value' => date("Y-m-d"), // default to today
  '#id' => 'stop_date',
  '#attributes' => array('class' => array('dateSel-Fld')),
  '#required' => true,
);

When using the #attribute property the form is not being rendered successfully.

Yep.

Here's the references:

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes

And a usage example:

https://api.drupal.org/api/drupal/modules!search!search.module/7


How to see recently inserted terms in the site? I've many of my people tagging content in my site. I'd like to review all those newly entered terms of any vocabulary. Is there any easy way to do so? I understand there no author/date time entry when a new term is added.

I know one crude method. I can remember the tid from yesterday and display all terms greater than it if I want to see today's entry.

You could add a field to the term which saves the current date when saved. Use the hook_taxonomy_term_insert() for this.

I think there is no other information on the term itself than the tid.


How to attach username at the end of url? Suppose I have a site www.example.com with many users in it. Now user "abc" is logged in, then the username should be attached at the end of that URL, like: www.example.com/abc

Also I have fix content on my website e.g. about us , contact us etc.
Now if I go to the "about us" content then the link should be : www.example.com/abc/contact-us

Try this:

go here: admin/config/search/path/patterns

and add: /[user:name]

to your replacement patterns.


Fatal error while upgrading While upgrading to Drupal 7.39 from 6.37, after copying the new files over into the site's directory, when I tried to navigate to the website I see a blank page with the following error: Fatal error: Cannot redeclare template_preprocess_block() (previously declared in /home2/mccotter/public_html/test/includes/theme.inc:2042) in /home2/mccotter/public_html/test/modules/block/block.module on line 1038

I have not yet run update.php, and when I try to the page appears blank.  I was unable to sign in as the maintenance user, but I set $update_free_access = TRUE.

For reference, the site that I am attempting to upgrade is jailtraining.org/test

Pre-First back up your site.

First upgrade to the most recent version of Drupal 6. The follow instructions here to move to Drupal 7:

https://www.drupal.org/documentation/upgrade

Have trouble? Explain where you are in the process at that point so one might help.


Hide text field in hook_form_alter I have a field field_agent_name. I want to hide this field in my custom module using hook_form_alter.

How to do this.

Using the hook_form_FORM_ID_alter format is ideal:

function MODULENAME_form_CONTENTTYPE_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_agent_name']['#access'] = FALSE;
}

More info on hook_form_FORM_ID_alter


"Allow multiple selection" not available in exposed filters I'm having trouble making some options appear as checkboxes in an exposed view form.
The problem is that the "Allow multiple selection" option is not available in the filter.

How can i make it visible. "Allow multiple selection" option.

You can go for Better Exposed Filters module.

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.


How to make a direct admin-visible URL to a private file in: sites/default/private/ Say I have a file in sites/default/private/archive/20160221.csv

How do I make a direct full URL to this file for admins to download.

I looked at file_create_url but am not sure what it would require to be passed in:

https://api.drupal.org/api/drupal/includes%21file.inc/function/file_create_url/7

Use file_entity_download_uri() in view php field

function file_entity_download_uri($file) {
  $uri = array(
    'path' => "file/{$file->fid}/download",
    'options' => array(),
  );
  if (!variable_get('file_entity_allow_insecure_download', FALSE)) {
    $uri['options']['query']['token'] = file_entity_get_download_token($file);
  }
  return $uri;
}


How to theme field for many views in drupal 7? I want to theme field--uc-product-image.tpl.php for two views. How to do this?

Is Drupal have theme like view1-field--uc-product-image.tpl.php ?

If you want to use template file, you can do that with: views-view--[view name]--[display].tpl.php

If your view name is "My product Image" and display is "block"

view mashine name will be: "my_product_image"

and your template file will be:

views-view--my-product-image--block.tpl.php

in this file you can get your fields in that way:

$fields = $view->style_plugin->rendered_fields; // fields array

and then customize fields with the foreach loop.

Example:

<?php foreach ($fields as $delta => $item): ?>
    <?php if ($item['uri']) : ?>
        <img src="<?php print $item['uri']; ?>" alt="" class="pull-left">
    <?php endif; ?>
<?php endforeach; ?>

Of course there are several ways to custom your image field. In this example I assuming that you need to do that in view template file.


Multilevel submenu with bootstrap 3 I am trying to make a multilevel menu using a Bootstrap theme on Drupal 8. I have created the menu and activated the "Show children" flag for all submenu containers but only first level submenus are showing.

I have tried http://knackforge.com/blog/pathirakaliappan/create-multi-level-bootstrap-menu-in-Drupal-8, but it doesn't seem to work: The submenus aren't being generated at all in the HTML.

I am using Drupal 8.1.2 and the 8.x-3.x-dev version of Drupal Bootstrap

You should conigure the max number of menu level in block structure


How to do a newsletter / mailing list with Drupal 7 I would like to make a mailing to a Drupal (7.4) community, sending an email to every user or every user with a specific role.

I would like to send this mails from my admin interface and I want to send mails with HTML.

What is the best way to do it ?

Use Simplenews and Mime Mail and/or HTML Mail to achieve this.


Is it possible to extend Drupal's user_access() function to provide a more complex logic for permissions This question is specific to Drupal 7, and I'm pretty sure that I already know the answer to this, namely that I won't be able to do what I want, but I thought I'd pose it to you Drupal experts.

Is it possible to extend Drupal's user_access() function to provide a more complex logic for permissions? I know it is possible to create an access callback function that provides more complex logic, but I want it so that every function that calls the user_access() function will implement this new logic for determining permissions.

So, how do you extend Drupal's user_access() function to run your own functions too to check access?

Looking at the code there's simply no way to do this without directly hacking the user_access() function.

There are no hooks invoked and the logic is completely self-contained, aside from one call user_role_permissions(). That function just runs a database query though so there's no scope to intercept the process there.

Obviously you could write your own access function and call it from your own code, but there are 152 calls to user_access() in core files (and countless others in contributed modules) which won't be able to take advantage of it unfortunately.


What is difference in the referencing entity options while adding a relationship in a views? I have entity reference field field_patient_reference.
While adding a relationship in views I get two options :
What is the difference between the two options below:

  Entity Reference: Referencing entity A bridge to the Content
  entity that is referencing Content via field_patient_reference

  and

  Entity Reference: Referenced Entity A bridge to the Content
  entity that is referenced via field_patient_reference

Lets say that Content A references Content B via an entity reference.

Content B is the Referenced Entity, while Content A is the Referencing Entity.

It really depends on what you are trying to see.  Say for example you pull a view of all content type B but want data from content A.  In that case you would use Entity Reference: Referencing entity.  If you have Content A and want data about Content B you would then use Entity Reference: Referenced Entity.


Rendering plain HTML in a form I have HTML markup which is externally generated but I need to display in a form.

I've got the following code in a form controller:

public function buildForm(array $form, FormStateInterface $form_state){
    $form['phone_number'] = [
        '#type' => 'tel',
        '#title' => 'Example phone',
    ];

    $form['TEST-Cloze']   =   [
        '#markup'   =>  "
<select><option value='[Walter]'>[Walter]</option><option value=' Hank'> Hank</option><option value=' Gus'> Gus</option><option value=' Jessie'> Jessie</option><option value=' Mike'> Mike</option></select> was diagnosed with cancer in his 50th year. He began working with <select><option value='Badger'>Badger</option><option value=' Skinny Pete'> Skinny Pete</option><option value=' [Jessie]'> [Jessie]</option><option value=' Tortuga'> Tortuga</option><option value=' Bogdan'> Bogdan</option></select> to produce <select><option value='cocaine'>cocaine</option><option value=' heronie'> heronie</option><option value=' opiods'> opiods</option><option value=' [amphetamines]'> [amphetamines]</option><option valu\nhis death. He eventually became involved with hardened criminal <select><option value='[Tuco]'>[Tuco]</option><option value=' Gomie'> Gomie</option><option value=' Bogdan'> Bogdan\noption><option value=' Todd'> Todd</option><option value=' Gale'> Gale</option></select> to help with the distribution of his illegally manufactured product.
"
        // '#markup'   =>  $question->processed
    ];

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

    return $form;
}

However, the output is completely stripped of markup and displays as plain text, as shown below:

How can I get the markup printed?

UPDATE:

I am attempting to add my form element markup because of the complexity of having multiple drop-down lists in a single paragraph, such as displayed below:

I struggled to achieve this type form output using other form components which is why I began looking into the #markup component.

If this was just content I would replace #markup with #prefix. It will automatically render without escaping your HTML.

However, it seems like you don't just want to render this HTML. You actually want it to interact with the Drupal Forms API. As such, I would recommend that you parse the data you need from the source and construct the form element the recommend way:

form['example_select'] = [
  '#type' => 'select',
  '#title' => $this
    ->t('Select element'),
  '#options' => [
    '1' => $this
      ->t('One'),
    '2' => [
      '2.1' => $this
        ->t('Two point one'),
      '2.2' => $this
        ->t('Two point two'),
    ],
    '3' => $this
      ->t('Three'),
  ],
];


How to redirecting add to cart form in drupal commerce programatically? I just wants to redirect the add to cart form to a different page. After click on add to cart button i do not wants to go cart page. i just want to go thank you page.

for that i am altering the form

 if($form_id == 'commerce_cart_add_to_cart_form_1'){
            $form['submit']['#value'] = t("Submit Event");
            $form['#submit'][]= 'post_event_save';
    }

by using the above code i am able to redirect to post event save page but it will not stop in that page again redirect cart page after executing this post_event_save function.

what i have tried post_event_save function

drupal_goto();
$form_state['redirect'] = false;
$form_state['rebuild'] = TRUE;

by printing the form_state variable

[#validate] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_validate
                    [1] => tasteusa_commerce_add_to_cart_form_validate
                )

            [#submit] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_submit
                    [1] => post_event_save
                )

            [#after_build] => Array
                (
                    [0] => commerce_cart_add_to_cart_form_after_build
                    [1] => context_form_alter_node_after_build
                    [2] => test_commerce_after_build
                )

Check if you have any redirect rules enabled under admin/config/workflow/rules, which is force redirecting you to cart page.

As a solution you can have your custom redirection rule and disable the existing redirection rule, an example redirection rule which redirects to node/2 path after adding product to cart.

{ "rules_add_product_to_cart_redirect" : {
    "LABEL" : "Add Product to Cart Redirect",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "add-to-cart-redirect" ],
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : { "commerce_cart_product_add" : [] },
    "DO" : [ { "redirect" : { "url" : "node\/2" } } ]
  }
}

In case you import the above remember to change the redirect path from node/2 to your thank-you page.


Theming translatable nodes in D7 We used i18n module to have our nodes as translatable.
However we also themed a specific nid with e.g node--9.tpl.php.

Problem is that i18n creates separate nodes(this separate nids), for each translation language, thus the theme file only applies to 1 version of that particular node.

How can I handle this?

Add following code to template.php and clear cache

function <THEME_NAME>_preprocess_node(&$vars) {
    if(!empty($vars['node']->tnid) && $vars['node']->tnid !== 0){
        $vars['theme_hook_suggestions'][] = 'node__'.$vars['node']->tnid;
    }
}


How to find the url of a media library image field in a preprocess function? I have a preprocess function that I am using to grab one of 3 profile images.  Basically we're replacing a couple stand-alone image fields with a media library reference field.  The goal is to display the media library image if it is populated at a particular style (called '65x65') or fall back to other stand-alone legacy image fields if it is not populated.
I'm having a heck of a time building the media library image url.  I have tried quite a few things based on this discussion and this discussion and others.  The image field on the image media type is called field_media_image (screenshot).  I'm not sure if it's useful to post my half-baked code attempts so I will leave the parts that I know are working.
foreach ($block->field_block_contributors->referencedEntities() as $contributor) {
    # prefer the media library reference profile image if it exists

    if (!$contributor->field_profile_image->isEmpty()) { # check if there is a media library profile image

      $my_profile_image = $contributor->get('field_profile_image')->referencedEntities(); # seems to load this field ok
      if (!empty($my_profile_image)) {
      // kint($my_profile_image);
      # load a media library image using the '65x65' image style
      // $styled_image_url = ??????

      }
    } elseif (!$contributor->field_user_image->isEmpty()) { # or fall back to one of two legacy image fields.  This part works
      $styled_image_url = ImageStyle::load('65x65')->buildUrl($contributor->field_user_image->entity->getFileUri());
    } elseif (!$contributor->field_speaker_image->isEmpty()) {
      $styled_image_url = ImageStyle::load('65x65')->buildUrl($contributor->field_speaker_image->entity->getFileUri());
    } else {
      $styled_image_url = '';
    }
    $variables['profiles'][] = [
      'title' => $contributor->field_user_title->value,
      'link' => "/user/" . $contributor->uid->value,
      'image' => ['src' => $styled_image_url, 'attributes' => $contributor->field_user_image->value],
      'name' => $contributor->field_user_first_name->value . " " . $contributor->field_user_last_name->value,
    ];
  }

PS. Bonus beer for anyone who knows off the top of their heads how I can link to the user's name instead of their user id # ( the line    'link' => "/user/" . $contributor->uid->value, )
Thanks!!!

I wrote a little module I found helpful to get the media entity image values.
custom_helper_services/custom_helper_services.info.yml:
name: 'Custom Helper Services'
type: module
description: 'Provides useful services for working with themes.'
core_version_requirement: ^8 || ^9
package: 'Custom'

custom_helper_services/custom_helper_services.module:
<?php

/**
 * @file
 * Contains custom_helper_services.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_help().
 */
function custom_helper_services_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the custom_helper_services module.
    case 'help.page.custom_helper_services':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Provides helpful service functions.') . '
';
      return $output;

    default:
  }
}

custom_helper_services/custom_helper_services.services.yml:
services:
  chs:
    class: Drupal\custom_helper_services\Services\CustomHelperServices
    arguments: ['@entity_type.manager','@current_route_match','@entity.repository']

custom_helper_services/src/Services/CustomHelperServices.php:
<?php

namespace Drupal\custom_helper_services\Services;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;

/**
 * Class CustomHelperServices.
 *
 * Provides helper services to be used in modules and themes.
 */
class CustomHelperServices {

  /**
   * Entity Type Manager.
   *
   * @var Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Route Match Interface.
   *
   * @var Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Entity Repository Interface.
   *
   * @var Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * CustomHelperServices constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity Type Manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch
   *   The Route Match Interface.
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entityRepository
   *   The Entity Repository Interface.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, RouteMatchInterface $routeMatch, EntityRepositoryInterface $entityRepository) {
    $this->entityTypeManager = $entityTypeManager;
    $this->routeMatch = $routeMatch;
    $this->entityRepository = $entityRepository;
  }

  /**
   * Build our media style path service.
   */
  public function getMediaFieldImage($mediaField = NULL, $imageStyle = NULL) {

    if ($mediaField && $mediaField->entity) {

      // Get image.
      $mediaImage = $mediaField->entity
        ->get('field_media_image');

      // Get image attributes.
      $alt = $mediaImage->alt;
      $width = $mediaImage->width;
      $height = $mediaImage->height;
      $title = $mediaImage->title;

      // Get image entity.
      $mediaImageEntity = $mediaImage->entity;

      // Get image mime type.
      $mediaImageMimeType = $mediaImageEntity->getMimeType();

      // Get image file URI.
      $mediaImageEntityUri = $mediaImageEntity->getFileUri();

      // Set image URL.
      $url = file_create_url($mediaImageEntityUri);

      // Set image style URL.
      if ($imageStyle && $mediaImageMimeType !== "image/svg+xml") {
        $url = $this->entityTypeManager
          ->getStorage('image_style')
          ->load($imageStyle)
          ->buildUrl($mediaImageEntityUri);
      }

      return [
        'url' => $url,
        'alt' => $alt,
        'width' => $width,
        'height' => $height,
        'mimeType' => $mediaImageMimeType,
        'title' => $title,
      ];
    }

    return NULL;
  }

}

Then in preprocess node, for example, you can call:
$variables['myVariable'] = \Drupal::service('chs')->getMediaFieldImage($node->get("field_name"), "image_style");
// Just need to pass the media field name. The image style is optional.

Then in a Twig template you can access as:
{{ myVariable.url }}
{{ myVariable.alt }}
{{ myVariable.width }}
{{ myVariable.height }}
{{ myVariable.mimeType }}
{{ myVariable.title }}

I've stripped down this code to show just the media entity image get, so let me know if there are issues and I can update if needed.

A shorter version (using preprocess_node()):
use Drupal\image\Entity\ImageStyle;
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->hasField('field_name') && $node->get('field_name')->entity) {
    $imageURI = $node->field_name->entity->getFileUri();
    $variables['myVariable'] = ImageStyle::load('image_style')->buildUrl($imageURI);
  }
}


Programmatically setting a link I am trying to programmatically set a link in a Drupal 8 view. The client wants an external link used if a certain link field is set, otherwise default the link to the node.

I am trying to figure out how to set this, and despite looking at hook_views_pre_render() and hook_views_post_render(), I'm not seeing any method to make this happen. I'm trying to go into result -

foreach ($view->result as $key => $value) {

}

However Kint is giving me data like this:

public _relationship_entities -> array(0)
public index -> integer7
public node_field_data_langcode -> string(2) "en"
public nid -> string(2) "99"

for each ResultRow.

I don't remember this being particularly difficult in Drupal 7 - is there something I'm missing here? How do I programmatically set a link in Drupal 8 dependent on certain conditions for a view row/field in a row?

The hook you're looking for is hook_views_view_field().

This hook allows you to alter the output of the field, and still is early enough to have the entity data for for that field.

In the example below, I'm checking if the node has a link field, field_my_link set, and if it's set, I alter the title output (which is normally linked to the node) to output to the link field's uri, but only if it's an external link.

function mymodule_preprocess_views_view_field(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }
  $node = $vars['row']->_entity;
  if ($vars['field']->getField() == '.title' && $node->field_my_link->isEmpty() === FALSE) {
    if ($node->field_my_link[0]->isExternal()) {
      $link = $node->field_my_link[0]->view();
      $link['#title'] = $node->label();
      $vars['output'] = $link;
    }
  }
}

If you want to alter the output of one views field based on the output of another, use hook_views_view_fields():

function mymodule_preprocess_views_view_fields(&$vars) {
  if ($vars['view']->id() != 'testview') {
    return;
  }

  // Cast Markup object to string.
  $field_one_content = (string) $vars['fields']['field_1']->content;

  // Check if first field contains a substring, if so, update second field.
  if (strpos($field_one_content, 'my search string') > -1) {
    $vars['fields']['field_2']->content = \Drupal\Core\Render\Markup::create('hello world');
  }

}


Custom module for form I have created form by implementing custom module. Can anybody please guide about writing submit function for my form.

function custom_form_module_form($form,&$form_state) {
  $form['name'] = array(
   '#title' => 'NAME',
   '#type' => 'textfield',
  );
  $form['company'] = array(
    '#title' => 'COMPANY',
    '#type' => 'textfield',
  );
  $form['phone'] = array(
    '#title' => 'PHONE',
    '#type' => 'textfield',
  );
  $form['email'] = array(
    '#title' => 'EMAIL',
    '#type' => 'textfield',
  );
  $form['message'] = array(
    '#title' => 'MESSAGE',
    '#type' => 'textarea',
  );
  $form['submit_button']=array(
    '#type'=>'submit',
    '#value'=>t('SEND'),
  );
  return $form;
}

UPDATED

 function custom_form_module_form_validate($form, &$form_state)
{
 if((!isset($_GET[($form_state['values']['name'])]))||
 (!isset($_GET[($form_state['values']['company'])]))||
 (!isset($_GET[($form_state['values']['phone'])]))||
 (!isset($_GET[($form_state['values']['email'])]))||
 (!isset($_GET[($form_state['values']['message'])])))
 {
  form_set_error(t('Please fill the entire form'));
 }
 $valid_email = $form_state['values']['email'];
 if (!valid_email_address($valid_email))
 {
  form_set_error('email', 'Sorry. Your email address,' . $valid_email . ', is not valid. Please submit a valid E-mail address.');
 }
 if(!($form_state['values']['company'] > 1))
 {
  form_set_error('company', t('Company does not appear to be valid.'));
 }
 if (!($form_state['values']['message'] > 2 ))
 {
  form_set_error('message', t('message does not appear to be valid.'));
 }
}

and below is my submit function. Is this right? because I am not receiving email as I specified my own email address.

function custom_form_module_form_mail($key, &$message, $params)
{
 $headers = array(
 'MIME-Version' => '1.0',
 'Content-Type' => 'text/html; charset=UTF-8;',
 'Content-Transfer-Encoding' => '8Bit',
 'X-Mailer' => 'Drupal'
  );
  foreach ($headers as $key => $value)
  {
   $message['headers'][$key] = $value;
  }
  $message['subject'] = $params['subject'];
  $message['body'] = $params['body'];
}

 function custom_form_module_form_submit($form, &$form_state)
{
  $valid_email = $form_state['values']['email'];
  $body[] = 'Email: '.$valid_email.'<br />URL: '.request_uri();
  $to = 'me@example.com';
  $params = array(
  'body' => $body,
  'subject' => 'Welcome!',
  );
  if (drupal_mail('custom_form_module_form', 'some_mail_key', $to, language_default(), $params, TRUE))
  {
    drupal_set_message('Thanks, we will be in contact with more information soon.');
  }
  else
  {
    drupal_set_message('There was an error subscribing you. Please try again later');
  }
}

You can add '#submit' => array('SOME_FUNCTION') to your submit button and write your function normally.


How do I rewrite the way my view rows are displayed I created a view and added three fields. A title, a link, and an image.
When adding the image, I set the formatter as URL to image.

How do I rewrite my in my views so that each recipe can have the thumbnail as a background image instead?

In a way, each view row should be structured like this:

{{ title }}

{{ content }}

Is there a way I can do this in my template?
Note: The only question closed to mine that I found is here

Did you override view ?? If your not override view Please follow below views view suggestion -

views-view-fields--(yourviewmachinename).html.twig
views-view-unformatted--(yourviewmachinename).html.twig

Note - In views-view-fields--(yourviewmachinename).html.twig,file render your fields which are present in that view Eg. If will have field - title follow below render

{{ fields.title.content }}

Note - If your rendering page title then render {{ label }}

In these file - views-view-unformatted--(yourviewmachinename).html.twig - You will get loop here,don't change here any think.

Hope, this will help you.thanks!


Expose single filter of combination of two fields in views I have two user profile fields "Last Name" and "First Name". I also have a user list views. I want to expose "Name" as filter which can search for both Last Name and First Name.
How can I do single filter of combination of those two fields? Can I create it from views UI?

One possible way is to create another profile field "Name" which will be hidden in the form. On user save, I would combine the two field values into the "Name" field and then expose it as filter in the views. But this solution is hard coding and it needs to write hooks.

I eventually got a solution from this. I followed the second primary solution offered although the blogger personally used hook_views_query_alter().

installed the module Views filters populate.
added two filters "First Name" and "Last Name" (both must not be exposed) and added them to a OR filter group (Views 3 supports this). I had to use the operator "Contains any word" for both fields, otherwise the query gave me no desired result.
created a filter "Global: populate filters", added the two fields into this and exposed it.

This gave me a quick solution without hard coding.
Here is other helpful reference.


Detect if the value of a cck field has changed when a node is edited Drupal 6.25, CCK 2.9

I have a node of type EVENT. The EVENT node contains several CCK fields that allow users to submit events to our calendar which go in to a workflow. If the user requested IT support at their event, the IT support person is e-mailed. If they will be hosting an event with food, the catering staff is notified.

Everything works great except that we can edit the event later upon their request. If the edits that we make change one of these values that is used to notify staff, I need the system to automatically notify those people.

I know how to handle notification and everything else works well, but I don't know how to detect if the state of a single field is changing.

DETAILED EXAMPLE:

--- Event information... ---

Will you require IT support at your event?

I need my lecture recorded.
We will require someone on hand to assist with software installation.
Video conferencing
Special request

(multiple checkboxes)

--- More event information ... ---

If that EVENT node is submitted, approved, and later edited to change the value of that field so that one of the boxes is checked, I need to handle that.

I have a custom module to handle this in and have experience writing validation and submit handling, but I'm not sure what values of $form or $form_state are helpful to this task. I thought that I might store the value of the field as it was originally as a hidden field with a hook_form_FORM_ID_alter and then check that hidden value against the submitted value but it's hard to get CCK values in to hidden fields because you have to capture the value in an #after_build function and... I'm just getting stuck and thought I'd ask for help.

Thanks in advance for your time and consideration!

EDIT - My solution based on the suggestion from Jimajamma below:

function sitecustom_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  // If we are saving an EVENT node...
  if ('presave' == $op && 'event' == $node->type) {
    // If the node already exists...
    if ($existing = node_load($node->nid)) {
      // If the FIELD_EVENT_TECH_SUPPORT value has changed...
      if ($node->field_event_tech_support == $existing->field_event_tech_support) {
        // Log the change.
        watchdog('event_edit', 'FIELD_EVENT_TECH_SUPPORT value did not change');
      } else {
        // Notify people accordingly.
        // TODO: Notification of staff of changed tech support for EVENT.
        // Log the notification.
        watchdog('event_edit', 'Event edited with FIELD_EVENT_TECH_SUPPORT value changed. Staff notified.');
      }
    }
  }
  // Handle other nodeapi uses, validation, etc.
}

And I'm not exactly sure if it's correct to do if ($existing = node_load($node->nid)) because that block seems to execute even when an EVENT node is being created from scratch. I know that I could use if ($existing->created != $existing->changed) but I haven't thought through everything yet and exactly what I want to test, etc. For now, using what I've shown above won't trigger the notification in this case IF the node is new.

I guess I just wanted to get something up here in terms of a solution in case people find this in the future. I will move on to exploring how to make this easier to do/find with RULES and ACTIONS as time allows.

I haven't done this, but my first idea would be to do this in nodeapi() and do something along the lines of (this horrid pseudo code):

if ( $op == 'presave' and $node->type == 'event' ) :
   $existing = node_load($node->nid);
   if ( $existing ) :
       check your fields in $node against the $existing node
       if they are different do something

and take into account you may no longer need IT or catering, so that needs to be conveyed as well as if you need it afterall.


View of taxonomy terms that are used giving duplicates, even with distinct I am trying to make a view of taxonomy terms that are used in content.

I created a test content type with a taxonomy term field, and used devel to generate content.

I've created a view of taxonomy terms, and added a relationship to the content with that taxonomy field:

Edit As stated above, I created a taxonomy view. I don't think these symptoms are caused by nodes being the base table

And, naturally, it duplicated a row for the taxonomy term for each content that contains that term:

I just want a list of the taxonomy terms used, with no duplicates, which would be this:

rudusteueph
dacigiwucl

So I made the relationship required:

which got rid of spathew. Then I removed the title field from the view. However I was still getting duplicates of each content by each term:

Since I don't want any duplicates, I checked Distinct:

However, I am still getting duplicates. How can I get a true DISTINCT result set?

Try using aggregation. Turn on aggregation and try Group Results Together on your term name field.


How to save file uploaded with plupload integration module, and make it managed? As described here, I can use Plupload integration module to upload my files to server. They go there, I can see them in temp directory, and that's the point I'm stuck.

Code I'm using for a field is:

'DownloadFile' => array(
  '#title' => t("Download's download"),
  '#title_display' => 'invisible',
  '#type' => 'file',

  '#upload_validators' => array(
    'file_validate_extensions' => array( /* extensions */ ),
    'file_validate_size' => array(variable_get('max_size', 300 * 1024 * 1024)),
  ),
  '#upload_location' => 'public://mymodule/download',
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '10mb',
    'max_file_size' => variable_get('max_size', 300 * 1024 * 1024) . 'b',
  ),
),

In form validation function I get thus in $form_state['values']:

Since the Views for Drupal 7 got reasonably stable, I was using Drupal 7 and managed files. I have literally no idea how should I take this file and plug it into managed table for other functions to use. As you can see from the time difference, it been some time between the moment I was able to upload and now - all this time with no idea. Tried to treat it as '#type' => 'file', but functions for unmanaged don't get it. They require specific name and even if I add '#name' to plupload form element, it still fails.

Is there any way to add file to managed table knowing it's location in temporary://?

I didn't really checked all links in this email but I have used Plupload very extensively and worked very well.

<?php

  $form['upload'] = array(
    '#type' => 'plupload',
    '#title' => '',
    '#description' => t('Maximum file size allowed: 10MB'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('zip rar 7z odt doc docx xls xlsx png jpg pdf rtf txt'),
    ),
    '#plupload_settings' => array(
        'runtimes' => 'html5,flash', // Also consider the order of technologies.
        'chunk_size' => '10mb',
        'unique_names' => TRUE,
        'flash_swf_url' => file_create_url(_plupload_library_path() . '/js/plupload.flash.swf'),
      ),
    );

  return $form;

  // Submit handler:
  //function ..._submit($form, &$form_state) {
  if (!empty($form_state['values']['upload'])) {
    $form_state['uploaded_files'] = quotes_file_save_files($form_state['values']['upload']);
  }

  // }

function quotes_file_save_files($files) {
  $saved_files = array();
  $scheme = 'private://'; // Change to "public://" if you want to move to public files folder.
  foreach ($files as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = plupload_file_uri_to_object($destination);
      file_save($file);
      // Check the $file object to see if all necessary properties are set. Otherwise, use file_load($file->fid) to populate all of them.
      // $file = file_load($file->fid);
      $saved_files[] = $file;
    }
  }

  return $saved_files;
}

?>

I think the point is, plupload does not save the files to the managed files folder by default, but populates all the data in the $form_state array for you to process and save.

Edit: In relation to the other answer that mentions file object's status should be permanent. I'm sure you already know that the status must be 1. But plupload_file_uri_to_object function sets the $file object's status to 1, so it's not done in the example.

Good luck!


dynamic block title for block-view of referencing nodes I have a block listing nodes that all reference the same 'parent node' (etity reference). I would love to see the title of the referenced node as a title of that block.

Example: on a record label website there could be nodes for albums. Every album node references one artist. On an album page there would be a block listing "Other Albums of Artist XY".

I know my question is quite similar to this question
"Dynamic block titles" but the solution on that question suggests using Tokens in the block's body, along with some h2-tags, so that it would look like the block's title.

Sounds like a swell workaround – however – since the block I use comes from a view, there is no body I could place tokens in.

Another workaround that almost did the trick was to add the referenced content type to the fields of the view, hide the output, then use tokens in the header of the view (again with h2 tags). But I only could get the referenced node fully rendered, making it impossible to use as a fake block title.

How can this be done? I would gladly welcome any hints and/or pointers…

Thanks! t.

Add the content title a second time, but this time set the relationship so that the artist's name is displayed. Set the display of this title to hidden, and make sure it has a label which reads : 'Other albums by'.

Then in the Format section, select settings, and then group by this artist title field you have just added and hidden.

The title will get wrapped in an h3. If you want to wrap it in an h2 then you will have to override the views template, one of the suggestions in the Style Output of the provided theme information.


Ideas for notification of map events occurring in some user defined area? I'm in charge of a full stack D8 (customer requirement) based project. It's mostly a Leaflet's web mapping application. The Leaflet part itself is almost done and it looks beautiful, fast and powerful. I let you know the URL once it gets released to the public.

Ahead comes a sprint ... This is the basic requirement of this phase:

The map is made of several, user switched feature layers.
Some of these layers receives regular updates, for instance: parties in the neighborhood announced witin the last week, two weeks and a month.
The 'parties' entity is stored in several mapserver endpoints (typically a REST service throwing GeoJSON out). Each period (week, two weeks, month) have its own endpoint.
Users (not Drupal users, subscribers only) draw an area in the map and 'subscribe' to the events announced on that area. By 'announced' I mean: points occurring within the user selected area.
At some specific time, my application is going to check the interesting points in the user defined area to send that out to the subscriber.

I forecast lots of challenges here. This is what I came up with to this very moment:

Create a content type with at least an email field and geofield support to store the points of the location area drawn by the user and her email (sort of a 'subscription backend').
Compose a new view to expose these subscriptions in some serialized fashion.
Code a helper script (bash, php, python) that is going to consume this D8 view and get the updated data from the mapserver endpoint.
Using cron and possibly Message Stack (yeah, yeah, I know, still in dev for D8...) to deliver the message for the final recipient.

This is an example of the entire use case:

http://fires.globalforestwatch.org/map/

In the right toolbox, look for the exclamation sign icon. This is the alert function of that map. Draw a line, enter your email and bang!

There are lots of other requirements for this use case (mobile friendly html emails, screenshots of the map with the 'parties' points and previously drawn area overlaid and such), but for know I'm concerned only with the most basic functionality: to store subscribers, their location of interest and how to transform this in some useful data for their mailboxes.

So, what are your thoughts? Anybody out there already faced this task? Any tips?

I don't need code (nor rejects if you wish). Any insights on a elegant way to get things done right? Oh, the less 3rd party modules, the better. Core ones are ok.

EDIT: the new Courier module (D8 only) just came to my attention.  It looks like a good contender to Message Stack in the message delivery front.

I've managed to find a solution for this one by myself. Here's how I did it.

Step 1: New Subscription and Notification

Create a content type for 'alerts'. This content type features fields like: title (composed by first + last name), first name, last name, email address, alert type (party or police, for instance), status (inactive, optin, optout), plain text (no D8 Geofield module required) with two fields to store map bounding boxes, geocode name, geocode ID and subscription key.
I've implemented a UI dialog in the map that interacts with the user (so she inputs a geocode search or a map draw) and the 'headless' D8.
By using the wonderful D8's RESTful Web Services module, that dialog implements code to POST user input data to the alerts content type. This code is smart enough to deal with subscriptions from a geocode search or user draw, as their requirements are a bit different. It also handles form field validation according to certain business rules, takes care of the verification key generation and forwards the request via Ajax to an external, custom made email verification script.
The custom made email verification script (not a D8 module, just plain PHP code with PHPMailer lib) receives the request and resolves the query string sent there. This guy takes care of query string values validation to the very same set of business rules applied to the form. If everything is fine, an email with the requested data is composed and sent to the user by using a secure SMTP. If there are errors in the query string validation (e.g. user is trying to bypass the form or fake someone), it returns with the validation step error code. At this point, the dialog in 3 above redraws itself to let the user know what have just happened (success or error code translated into human readable language).
All fine up to this point, the dialog code in 3 effectively POST the new alert content and email is sent to the user. This email displays The Big Red Button™ saying something like 'Verify Now!' When a user click (or tap) on it, the second step in the process begins...

Step 2: Subscription Validation

Another custom made, plain PHP script (also totally apart of D8) is called by the last user action from the above step. This scripts also counts on D8 RESTfull powers, the amazing (Guzzle PHP HTTP Client) (*3) to perform various actions related to subscription activation. Here they are:

'Click Here To Verify' call the activation scripts with some query string (e.g. D8 node id and verification key). These are first and foremost validated do the same set of business rules we had before. Looks good? Move on. Fake? Redirect to a nice error page.
A (Guzzle client) (*4) is set with enough options to make it run smooth and secure, '(cookies => true) (*5)' is among then.
A (POST request to login) (*6) is fired. I've created a special user and a role just for D8's API usage. This is to prevent sneakers from the outside. Also, by having a custom made script, I can rest assured the it is always calling on localhost (127.0.0.1), so the Ops guys could set all sort of firewall, proxies and CORS rules to backend protection.
We're in, GET D8's (CSFR token) (*7) for the session.
(GET node content) (*8) and retrieve just the information we need to verify (e.g. status, verification key and such).
Perform validation logic. Fine? Move on. Fake? Redirect to a nice error page.
(PATCH node) (*9) to update the signature status.
(GET logout) (*10) to finish the session, close the Guzzle client by adding header headers => [cookies => true] in this request, and some further cleanup magic.
All set? Redirect user to a nice success page. Something went wrong? Catch exception and redirect to an error page.

During the whole runtime of the script, a specially crafted debug stream and a try/catch carefully listens to any exceptions. When debug is enabled, the page redirection is hold and debug information shows up so the Ops could inspect what is going on behind the scenes.

Well, it doesn't stop there. There are still the optout and the subscription delivery features. However, the above works pretty well as a base for all the remaining steps.

For the sake of completeness to the OP question, the above looks pretty elegant to me (i.e. decoupled, maintainable, secure) and uses no 3rd party D8 modules at all, just the core ones. As a plus, the custom scripts are implement relying on well maintained, open source projects.

For moderators:

Please add the URLs bellow to the places their belong in the text above to as I'm in lack of reputation to do so.

*3 http://guzzlephp.org/
*4 http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
*5 http://docs.guzzlephp.org/en/latest/quickstart.html#cookies
*6 http://dropbucket.org/node/6743
*7 https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AcsrfToken/8.1.x
*8 https://www.drupal.org/documentation/modules/rest/get
*9 https://www.drupal.org/documentation/modules/rest/patch
*10 https://www.drupal.org/documentation/modules/rest/javascript


upgrading from D6 to D7: Is lower version updated required? I have a doubt in upgrading a project from D6 to D7.

If I am upgrading a project from D6 to D7 is it neccessary to upgrade version by version or we can directly upgrade to D7.

For example if I am suppose to upgrade a project from version 6.20 do I need to upgrade it to version 6.22 first or I can upgrade directly to D7 ?

It is strongly recommended that you upgrade to the latest version of Drupal 6 before trying to upgrade to Drupal 7.  Make sure you read the text under "MAJOR VERSION UPGRADE" in the file UPGRADE.txtthat comes with Drupal 7 - it is also online.  You should be able to go from where you are directly to the latest Drupal 6 version (currently 6.27) - there is no need to go through intermediary minor versions.  And you can go directly from the latest Drupal 6 to the latest Drupal 7 (currently 7.18).

Before you start, disable and uninstall all contributed modules you don't need. Also disable and uninstall all modules (such as CCK) that say upfront that no upgrade path exists. If a module offer an export/import feature (e.g. Biblio), then use it.  Export all content from Drupal 6, then disable and uninstall the module.  Reinstall the module and import the data when your Drupal 7 configuration is stable.

For all contributed modules that remain installed at this point, make sure you upgrade them to their latest stable Drupal 6 version before you start.

Also make sure you make a backup of everything before starting.  You may have to go through the upgrade several times. In your first attempts you will discover contributed modules that break your site when you upgrade. You must disable and uninstall those, and then try again.  Repeat as many times as necessary.

Depending on the complexity of your site, you may want to fasten your seatbelts.  It's going to be a bumpy night.

Upgrading a stripped core configuration is fairly painless.  But not all contributed modules has a (working) upgrade path.  In particular, if you've used CCK, expect that some data does not make it into Drupal 7 automatically.  (I ended up writing my own DB conversion scripts using flat text files as intermediaries - and in some cases: scraping content and pasting it back into the upgraded site).


Show attribute widgets even if the Add to Cart form only represents one product I'm having problem with display option, of Product variation field as "Add to Cart form":

With that option it should show variation switcher, whenever there is one or more product variations.

But it does not:

Simply looks like "Show attribute widgets even if the Add to Cart form only represents one product." option doesn't change anything.

The above display shows teasers on the front page (I have trying manipulating default view in Manage Display as well).

I have trying clearing cache, running cron and changing my customized node--product--type.tpl.php and node--product--type--product--list.tpl.php  to oryginal ones and it does not help as well.

There are a few things you have to ensure you do right for this to work, as even in my little test environment to reproduce the error I screwed it up a couple different ways.

You must ensure the field you've added to your product type has checked the box to state that it should function as an attribute field on Add to Cart forms.
You must edit the field display settings using the form you've posted a screenshot of, but make sure you save the full form as the "Update" button on the expanded form doesn't actually save any changes to the database.
You must reproduce that for all relevant view modes.

With all of those things in mind, I was actually able to confirm the feature itself is working as advertised when properly configured:


How to create a suggested articles block that uses taxonomy? I've been trying to create a view that uses taxonomy to generate suggested articles to users.

I wanted these articles generated according to their relation with the taxonomy term of the current article the user is reading.

How can I make this work?

Have a look at the Similar by Terms module. Here are some more details about it (from its project page):

This Drupal module attempts to provide context for content items by displaying a view block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Views are available based on similarity within each of the defined vocabularies for a site as well as similarity within all vocabularies.
What does this really mean? How should you use this module?

Create a freetagging vocabulary called "Tags" assigned to the content types on which you'd like to display the "Similar" view block.
Enable the view block called "Similar entries from the Tags vocabulary".
Add keyword tags to the content.

You can also create own views and add similar by term Nid argument, sort handler and similarity as field. Now when you go to the page for a tagged content item, a block will show up displaying other content in descending order of common tags (terms).

Note: a stable version of this module is available for both D7 and D8!


How to access field values from an entity reference field in a custom module? I'm making a custom payment module for Commerce that references a Credit Card entity. I have the entity reference form field in there and working but I cannot pass on the selected Credit Card entity to the "message" field. If I could just print whatever the title of the entity reference they select, that would work, or if I could access one of the 5 fields in the entity itself, that would be ideal.

Here is my module: http://pastebin.com/373WDAzA and this is the error message I get:

  Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1559 of C:\xampp\htdocs\includes\bootstrap.inc).

$form['card_on_file' ] = array(
  '#type' => 'entityreference',
  '#title' => t ('Credit Card'),
  '#era_entity_type' => 'node', // Mandatory
  '#era_bundles' => array(credit_card ), // Optional (Any bundle by default).
  '#era_cardinality' => 5, // Optional (1 By default).
  '#required' => TRUE,
) ;

the warning corresponds to this replace this code:

'#era_bundles' => array(credit_card ), // Optional (Any bundle by default).

with

'#era_bundles' => array('credit_card'),

Link: https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7

$ids = array();

get $ids from $form_state['values'] of submit handler function.

use entity_load('credit_card', $ids);


Hook menu - title arguments I have those menu elements declared in hook_menu function:

$items['submission/%/id/%'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'page arguments' => array(1, 3),
    'page callback' => 'fr_form_node_object_id',
    'access arguments' => array('content access'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 100,
  );

  $items['submission/%/id/%/view'] = array(
    'title' => 'View submission',
    'title callback' => 'fr_form_view_submission_page_title',
    'title arguments' => array(3),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['submission/%/id/%/edit'] = array(
    'title' => 'Edit submission',
    'page arguments' => array(1, 3, 4),
    'page callback' => 'fr_form_node_object_id',
    'title callback' => 'fr_form_edit_submission_page_title',
    'title arguments' => array(3),
    'access arguments' => array('content access'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );

As you can see the first menu item has a fr_form_view_submission_page_title() function to set the title. And the function looks like this:

function fr_form_view_submission_page_title($id) {
  return t('View submission ID: @id', array('@id' => $id));
}

Second item makes the first one default.

Third menu item has a title callback function which looks like this:

function fr_form_edit_submission_page_title($id) {
  return t('Edit submission ID: @id', array('@id' => $id));
}

When I go to page /submission/10/id/1 I get the result. Two tabs next to each other with text on it:

first tab: View submission ID: 1
second tab: Edit submission ID: 1

And the page title is: View submission ID: 1

And if I go to the edit tab (/submission/10/id/1/edit) I get exacly the same, so:

first tab: View submission ID: 1
second tab: Edit submission ID: 1

And the page title is: View submission ID: 1

What I want to achive is to have tabs always signed:

first tab: View submission

second tab: Edit submission

And the page title depending on path, so for /submission/10/id/1 I should get:
View submission ID: 1

And for /submission/10/id/1/edit I should get:
Edit submission ID: 1

You can use single title callback by passing two arguments :

'title arguments' => array(3, 4),

and use same callback for both function :

function fr_form_view_submission_page_title($id, $type = 'view') {
  $type = ucfirst($type);
  return t('@type submission ID: @id', array('@type' => $type, '@id' => $id));
}


WYSIWYG only shows in administration theme Anyone having this issue where the wysiwyg editor is only showing when you are in admin mode?

This is happening because you have an input format associated with the editor that is only available to your admin users. You need to either make the input format available to other roles on your site or expand the formats that the WYSIWYG editor displays on.


Using xdebug to find out why a variable is mysteriously set to 0 Thanks in advance for your help! I'm new to xdebug and trying to figure it out. I have a situation I'm trying to debug where a variable is mysteriously set to 0.

I know from xdebug (I'm using PHPStorm) that it happens at this specific line:

// breakpoint here: $id_key is 'my_entity_id_key'
$e_entity_ids = my_module_fetch_col_keyed($query, $id_key, $created_column);
// breakpoint here: $id_key is 0

It's weird, because $id_key is not a reference, nor does the function take a reference as a parameter. Also, after the value has changed to 0, $id_key is blue in the variables pane of the debugger. I should note that $e_entity_ids comes out here with the proper value.

I've tried making a copy of the variable and using it to pass to the function instead:

$id_key2 = $id_key;
$e_entity_ids = my_module_fetch_col_keyed($query, $id_key2, $created_column);
// breakpoint here: $id_key is 0, and so is $id_key2

I'm wondering:

How could the value of $id_key be mysteriously changing to 0?
How can I create a copy of $id_key so that it's not changed when I pass the copy to my_module_fetch_col_keyed()?
What does it mean when a variable name is blue in the variables pane in PHPStorm?

When I step into my_module_fetch_col_keyed(), there's a line after which $column is mysteriously 0, as shown:

function my_module_fetch_col_keyed(Query $query, $column, $key_column = NULL) {
  try {
    $result = $query->execute();
  }
  catch (Exception $e) {
    return FALSE;
  }

  if (!isset($key_column)) {
    try {
      // breakpoint here: $column is 'my_entity_id_key'
      $column_results = $result->fetchCol($column);
      // breakpoint here: $column is mysteriously 0
    }
    catch (Exception $e) {
      return FALSE;
    }
    return $column_results;
  }

  try {
    $assoc = $result->fetchAllAssoc($key_column);
  }
  catch (Exception $e) {
    return FALSE;
  }

  $keyed = array();
  foreach ($assoc as $key => $result) {
    $keyed[$key] = $result->{$column};
  }

  return $keyed;
}

The key idea here is to use the "step into" functionality of PHPStorm to figure out when the second argument ($column within the function's declaration) gets changed.  $id_key shouldn't change at all if you're describing the calling conventions correctly, the second argument would have to be declared as &$column, i.e., as a reference to the variable.  So I'm assuming that's what you mean. Otherwise, PHP passes a scalar variable "by value", and won't let any changes made to the variable in the body of the function change the original variable outside of it.

And there's nothing inside of the function that will change it either.  Here J. Reynolds is right; you're passing the wrong thing to fetchCol(), which wants an integer. But fetchCol() doesn't modify its argument either.

Since you're using xdebug, this then raises an important question: how are you using it?  Is your php process running on the same server as PHPStorm?

I ask this because one thing can definitely go wrong using xdebug: you can be debugging a different file than you think you are, if you're "mapping" a file on your server to a local file. If the file isn't the same, weird things can happen like what you describe. You may not really be on the line you think you are, since xdebug will tell PHPStorm the file line on the server, which may be a different line entirely on your local file. And the values of variables, if they display at all, may have different values than what the code displaying in PHPStorm allows.

Without knowing how you've set up PHPStorm to get to your PHP process, it's hard to know what exactly's going on. But you should describe what technique you're using, so folks can give you a better answer.


Organic Groups - how to display a summary view of members of the group based on a "company" field added to the user profile I want to create a block to display on my organic group nodes that shows the number of members of the group summarized by a field in the user profile (company)  for instance:

Company 1 (4)
Company 2 (1)
Company 6 (3)

I have played around with relationships adding a few trying to get the field I need and using the "(OG group) OG group: Og group ID" as a contextual filter--  I can get the field label (Company) to show up in the block view but the values don't show up

I took the default OG Members view and cloned it (keep the original) and changed from user: name to my field user:company - added aggregation - in advanced settings in the other section - then had to change the contextual filter to use the GID from the active node. then played around with the aggregation to get it to work ... overall it does what I needed.

Lesson learned ... use the views you get from adding modules - smart people built them ;-)


Color palettes for content types We would like to give admin users of a custom theme the ability to set a color palette for each content-type for all visitors to a site.

The color module gives a way to allow admin users some control of a single color palette for the whole website but we want to let them set a palette for each content type (or leave the base color theme for each). Including any new content types, they may create in the future.

Is this feasible?

I have been poking around the color module but I am not sure how hard it would be to write a custom module that extended it in this way. Any ideas if this is even possible?

This is for a Drupal 8 site and theme.

Found this after 5 seconds of googling:

https://www.drupal.org/project/color_field
https://www.drupal.org/project/colorfield
https://www.drupal.org/project/jquery_colorpicker

The search query was: drupal color field.

Choose one,
add one color field per content type to the user entity type (users should be able to edit their profile),
then retrieve the current user and the selected values and add them as node class via template_preprocess_node.

  I may have been unclear. I don't want to let each user set their own
  color palette, I want users with the right permissions to be able to
  set the palette for an arbitrary content type for ALL users/anonymous
  users accessing the site. (I'll update my question) – tanbog

For that you need to create a configuration form. @see docs Working with Configuration Forms.

You can get a list of all content types to build your form. @see question Get the list of all content types.

You also may want to use the color FormElement. @see docs class Color.

In the end you probably still use template_preprocess_node, to get the stored config in there, and then set the CSS class according the current node type.


Move file storage to another server Consider this:

I have one fast server with a Drupal installation but this server does not have access to a lot of disk space.
I have another server that isn't quite as fast but does have access to lot of disk space.

My drupal server is hosting a blog and some photo galleries.
I would like my drupal server to use the file server to store its images and files.

How can I achieve such a thing?
The file server can be accessed through ftp or sftp.

I'm considering using the storage api for this, it seems like a good fit (?) but I'm not sure how to implement it. The documentation seems a bit off.

Also, the blog uses the wysiwyg module + the media module to allow for image uploads in the body field. How can I make this functionality work with the storage api?

Is there anyone with experience in this field that can help me out?

If all you're looking to do is offload your Files directory to a different server, and you have complete access to both servers, I would suggest you create an NFS (network drive) mapping to the storage server.

Then you can simply change your Public/Private files directory to /mynfs/drupal-files instead of /drupal/sites/default/files, which will pretty transparently offload storage to your other server.

You'll want to do some research into NFS and its alternatives that do the same thing.  I'm not familiar enough with the Storage API to know if it will work in your situation.  After researching it a little bit it seemed like you would have to do a decent amount of work as well.


Drush make and SVN: Leaving behind the .svn folders Maybe I am missing a parameter, but when I use the below code in my make file, the ".svn" folder is removed. I would like that folder to remain. How can I do this?

projects[module_name][type] = "module"
projects[module_name][download][type] = "svn"
projects[module_name][download][url] = svn+ssh://company.com/home/svn/drupal7modules/module_name

Use the --working-copy option.

Help tekst: Preserves VCS directories, like .git, for projects downloaded using such methods.


How do I check the current user session? In Drupal 7, I was able to use bootstrap.inc in an external PHP script, which was a custom set of pages that simply bootstrapped Drupal to check the user was logged in Drupal.

The following code is a very basic version that just returns the username of an active session.

require_once '../includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
echo $user->name;

I'm looking to implement something similar in Drupal 8. The same script returns a server error.

  Error: Class 'Drupal\Core\Session\AccountInterface' not found in core/includes/bootstrap.inc, line 63

How should I check for an active user session from an external script, in Drupal 8?

You can't really do something like that in Drupal 8.

The short story is that we use Symphony for the Request / Response flow, so actually bootsrapping Drupal is a lot more complex than simply requiring the bootstrap.inc file. If you look at the index.php file, you can see an overview of a request in Drupal 8:

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

Most of this happens in the DrupalKernal::handle call. You could probably make a custom script that hooks into Drupal, but it probably will be a lot easier and more maintable to actually have this code be part of your Drupal installation.


Why are URL encoded values in $_GET variables broken? I'm working with a payment gateway that returns payment feedback in the URL. One of the variables has a special character in it:

PM=Sofort+%DCberweisung

The %DC is Ü. However, it's coming through instead as �—and in case that doesn't display properly here, it's a black triangle with a question mark inside it. I confirmed this by replacing my menu callback with a simple print and die:

print($_GET['PM']); die();

The output is just (again: I'm not sure how that broken character might appear here on StackExchange):

Sofort �berweisung (DE)

I have confirmed that if I replace the %DC in the URL with Ü, it prints fine, so it's not a problem with that character: something is going wrong, somewhere, when the server tries to decode the URL-encoded value.

Does Drupal do any kind of processing on $_GET variables during bootstrapping? Could this be an Apache configuration issue?

Update: This is definitely something in Drupal. I moved my print-then-die to the very beginning of index.php and it prints the correct value. This tells me that it's not an Apache problem. Then, on a clean D6 install with no contrib modules, I added a small module that just adds a single menu callback to do that same print-then-die, and I got the invalid character there.

Sounds like your incoming data is ISO-8859-1, not the other way round. Drupal is always in UTF-8 (and utf8_encode converts from ISO-8859-1 to UTF8).

This is what I get when urlencoding Ü.:

$ drush ev 'var_dump(urlencode('ü'));'
string(6) "%C3%BC"

And when urldecoding and utf8 encoding %DC:

$ drush ev "var_dump(utf8_encode(urldecode('%DC')));"
string(2) "Ü"

Makes all perfect sense to me.


default value when adding new item of date field i'm using drupal 7 and in my content type there is a date field has start and end value with unlimited values, i set the default value to "Now".
but the problem is when adding new item of this field there is no default value in it.

is there a way to set a default value for new items?
thanks a lot.

Try something like this:

//this hook or general hook_field_widget_form_alter
function hook_field_widget_date_popup_form_alter(&$element, $form_state, &$context){

  //only when field is specific name and during node creation form
  if ($element['#field_name'] == 'field_date' && !isset($element['#entity']->nid)) {

    //if default value is not set, only for second and later elements, when first item value is set
    if (!is_array($element['#default_value']) && $element['#delta'] > 0 && isset($form_state['values']['field_date']['und'][$element['#delta']-1]['value'])) {

      //set value
      $element['#default_value'] = array(
        //advance by 24 hours
        'value' => $form_state['values']['field_date']['und'][$element['#delta']-1]['value'] + 24 * 3600,
        //same timezone
        'timezone' => $form_state['values']['field_date']['und'][$element['#delta']-1]['timezone'],
        'timezone_db' => 'UTC',
        'date_type' => 'datestamp',
      );

      //if second value (date to) is set (by comparing value and value2)
      if ($form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] != $form_state['values']['field_date']['und'][$element['#delta']-1]['value'])
        //set and advance second value by 24 hours also
        $element['#default_value']['value2'] = $form_state['values']['field_date']['und'][$element['#delta']-1]['value2'] + 24 * 3600;

      //#date_items needs to be same as #default_value
      $element['#date_items'] = $element['#default_value'];
    }
  }
}


'' a field on Manage display I'm using D7.

If you set a field <Hidden> on 'Manage display', and, unless you display it by views or something, you cannot see it anywhere on the site, right?

They say...

  Format
  The format column contains the options to show the field value
  in different formats. Hidden is the global value which is present in
  all the format option list, if you choose hidden then it will hide the
  whole field from showing on the content page.

  https://www.drupal.org/docs/7/nodes-content-types-and-fields/specify-how-fields-are-displayed

I understand it hides a field from View mode. But, you can also hide it if you don't try to do by using those modules, which are designed to output fields, like Views, right? Or, is there still any possibility that users can see the hidden field even if those modules are not used?

I'm sorry if this is a very basic question. But, I wanted to make sure what 'hidden' field means.

Thank you.

If you use (Manage display) format: hidden (not label: hidden), the field will not show for this display for this content type. The field could still show in another display (like for teasers). So you will need to set the field format to hidden for all displays.

It is still possible to make a view with the Views module that displays the field. It depends on how you set up the view. If you set up a view of teasers, the standard teaser display is used (and the field is hidden according to the display settings). If you make a view of fields, you just have to avoid picking the "secret field".

If this is an existing Drupal site where this content type and field is a part of many different views and/or other modules, you will need to test this out. Also if the field is searchable or hardcoded in some template.


hook_form_alter and fields in user_profile I know how to use hook_form_alter, but I'm little confused how to achieve this:

In user profile there are tabs "View" and "Edit".

In edit I can alter the form using switch statement on user_profile_form and adding a fields, but they don't appear when I click on "View" tab.

Let's say I'm adding a new field into the user_profile_form:

    <?php

    /*
     * Implements hook_form_alter().
     */

    function my_module_form_alter (&$form, &$form_state, $form_id) {
            switch ($form_id) {
            case 'user_profile_form':

    $form['account']['skype_title'] = array(
            '#type' => 'markup',
            '#markup' => '
Skype edit
'
            );

            $form['account']['skype'] = array(
            '#type' => 'textfield',
            '#title' => t('New Skype'),
            );

                  //krumo($form);
            break;

    }
}

How can I display this field into "View tab"?

Should I use another hook for this?

As Kaido24 mentioned, the profile view tab is not a form. You can add elements to it in hook_user_view_alter().


Drupal 7: Adding a save button to save content to user profile page I want a signed-in user to have the ability to save an image (that is being displayed in some kind of slideshow or gallery) and have it appear on that users profile page. So the image will be on the same site, maybe added by another user or the site admin and then any other user would be able to click a save button and have it added to their own profile. That image being saved (when being saved to the users profile) should have a link that returns you to the gallery from which you saved it.

How to do this?

For something really simple, you can use the Favorites module where users can add nodes to a "favorites" list. This is based off of the URL though, so a gallery of images rotating on one page wouldn't really work.

For a more robust system, you can configure a bunch of Flags, which can do many different things like bookmarks, favorites, etc.


Populate multiselect options onchange of dropdown using AJAX I have created a content type (Geological Locations) with 2 fields, Country and States.

The Country field is a select box, and States field is a multiselect. So if i select a Country, the States multiselect should be populated based on the selected Country using AJAX.

In my custom module, i used node_form_alter() to customize the node creation form.

I have tried the below code, but it is not working as expected.

function demo_form_geological_locations_node_form_alter(&$form, &$form_state, $form_id) {
    $form['additional_settings']['#access'] = false;
    $form['field_country']['und']['#options'] = array(''=>'Select', 'india'=>'India', 'usa'=>'USA');
    $selected = isset($form_state['values']['field_country']) ? $form_state['values']['field_country'] : '';

    $form['field_country']['und']['#ajax'] = array(
          'callback' => 'ajax_states_callback',
          'wrapper' => 'states-wrapper',
    );

    $form['field_states']['#prefix'] = '
';
    $form['field_states']['#suffix'] = '
';
    $form['field_states']['und']['#options'] = ajax_get_state_options($selected);

    return $form;
}

function ajax_states_callback($form, $form_state) {
    return $form['field_states'];
}

function ajax_get_state_options($key = '') {
    $options = array(
        t('usa') => drupal_map_assoc(
          array(
            t('Florida'),
            t('Georgia'),
            t('Atlanta')
          )
        ),
        t('india') => drupal_map_assoc(
          array(
            t('Maharashtra'),
            t('Gujarat'),
            t('Karnataka')
          )
        )
    );

    if (isset($options[$key])) {
        return $options[$key];
    }
    else {
        return array();
    }
}

Can anyone tell me where i am going wrong?
I am expecting the output like below screenshot, when i select the Country "India":

Have you tried one of the following modules?

Multiselect (this one suits the most)

Hierarchical Select (relatively easy to configure)

Conditional Fields (requires separate dropdown lists)

A combination of Multiselect and Hierarchical Select will mostly help you achieve what you have shown.

Regards,

Supriya Rajgopal


views expose filter by taxonomy I have this structure :

mobile

Lg

V10
V20

Samsung

A7
J5

Nokia

1100
1110

laptop ...
tablet ...

How can I create that with view expose filter? (step by step filter)

You can do this with the special type of filter Has taxonomy terms (with depth).

Add a new Filter Has taxonomy terms (with depth)
Select your Vocabulary in the new filter settings,
Selection type: Dropdown
Show hierarchy in dropdown
Depth 2 (this will include 2 levels of children of a chosen term)
Expose this filter to visitors, to allow them to change it and Apply

You will get a drop-down that shows your terms with hierarchy.

If you don't want a dropdown you can use a module like Better exposed filters to use radio buttons instead.


Retrieve the default image from an image field programatically Currently im using the following code to retrieve the uri of an image field:

$field = $paragraph->field_background_image_left;
$uri = $field->entity->getFileUri();

This seems to work fine when the field contains a value.
But when no value is set, '$field->entity' will contain null, even when a default image was set for this field.

How do I retrieve the uri of the default image from my field?

The default image is stored in field configuration. You can retrieve it as follows:

<?php

use Drupal\field\Entity\FieldConfig;

$field_info = FieldConfig::loadByName('node', 'article', 'field_image');
$image_uuid = $field_info->getSetting('default_image')['uuid'];
$image = Drupal::service('entity.repository')->loadEntityByUuid('file', $image_uuid);
$image_uri = $image->getFileUri();


Way to programmatically add string translations? is there a way (snippet) to programmatically add translations for strings (user interface translation), e.g. in hook_update_N()?

A way in Drupal 7 was http://dropbucket.org/node/323.

/**
 * Helper to manually add a single translation string.
 *
 * After adding strings use locale_clear_cache() for clearing caches.
 */
function locale_add_translation($source, $langcode, $translation, $context = '', $textgroup = 'default') {
  require_once DRUPAL_ROOT . '/includes/locale.inc';

  $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  _locale_import_one_string_db($report, $langcode, $context, $source, $translation, $textgroup, 'Manual import via helper ' . __FUNCTION__ .'().', LOCALE_IMPORT_OVERWRITE);
}

/**
 * Helper to clear the locale cache.
 */
function locale_clear_cache() {
  require_once DRUPAL_ROOT . '/includes/locale.inc';
  // Clear locale cache.
  _locale_invalidate_js();
  cache_clear_all('locale:', 'cache', TRUE);
}

Is there anything like this for Drupal 8?

Put the following helper function in your custom module:

use \Drupal\locale\SourceString;

function mymodule_add_translation($source_string, $translated_string, $langcode) {
  // Find existing source string.
  $storage = \Drupal::service('locale.storage');
  $string = $storage->findString(array('source' => $source_string));
  if (is_null($string)) {
    $string = new SourceString();
    $string->setString($source_string);
    $string->setStorage($storage);
    $string->save();
  }
  // Create translation. If one already exists, it will be replaced.
  $translation = $storage->createTranslation(array(
    'lid' => $string->lid,
    'language' => $langcode,
    'translation' => $translated_string,
  ))->save();
}


How do I use a jQuery version different from the default one used by core? I need to use a different jQuery version. Currently, Drupal is using jQuery 3.2.1, but I need a previous version.

In Drupal 7 you could easily change jQuery version with the jQuery Update module. How can I achieve the same with Drupal 8?

Add your custom jQuery library in your mytheme.libraries.yml:

jquery-custom:
  remote: https://github.com/jquery/jquery
  version: "2.2.4"
  license:
    name: MIT
    url: https://github.com/jquery/jquery/blob/2.2.4/LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery-2.2.4.min.js: { minified: true, weight: -20 }

Then override the core jQuery library in your mytheme.info.yml:

libraries-override:
  # Replace an entire library.
  core/jquery: mytheme/jquery-custom


Getting parents' terms of terms tagged into a particular content type nodes This is a bit confusing for me.

I am using Drupal 7 and Views 3.

I have a list of particular content type nodes tagged with a term (from a vocabulary "topic"). Vocabulary "topic" is 2 levels deep and nodes are tagged just with leaf terms. I have those same nodes tagged with another vocabulary ("level" vocabulary).

I'd like to get in a view all parent terms (exactly the term name) from the vocabulary "topic" whose children are tagged into a node which is tagged with a particular level (let's say beginners).

Let me show you an example:

Vocabulary "Level":

Beginners
Intermediate
Advance

Vocabulary "Topic":

Greek philosophy

Introduction to greek philosophy
First stage: Greek
Second stage: Greek

Latin philosophy

Introduction to latin philosophy
First stage: Latin

My content type nodes can be tagged with both vocabularies but in the case of "topic" they are only allowed to be tagged, as I said, with leaf nodes (i.e. Introduction to greek philosophy, first stage:greek, second stage: greek, Introduction to latin philosophy or first stage:latin).

In this context if one particular node  is tagged with "introduction to greek philosophy" and "beginners", I would get "Greek philosophy" on my view. If that same node is not tagged with "beginners" I wouldn't get it on my view.

I know it's a bit complex but I would really appreciate your help and orientation.

Thanks in advance.

OK, so this solution has many steps, but the good news is that this is possible.

Here's what you need to do in your view:

In your view that lists your nodes, add a relationship to the topic term reference field (called field_topic) in my case.  In the 'Advanced' section, add the 'Content: Topic' field, and rename it if you want in the configuration screen.  As you can see, I did!

Next, add one more relationship (the parent term of this Topic term).  I'm filtering to only see term fields, and choose the 'Taxonomy term: Parent term' option.  Make sure, when you configure this second relationship, to choose that you want the Parent term of the already selected Topic term field.

If you want - at this point you can select the "Taxonomy term: Name" field twice in your fields list (once with the 'Topic term' as the relationship and once with the 'Parent term' as the relationship to see that your two relationship are bringing up the correct terms).
Finally, you're ready to set up a contextual filter!  What you want is for this view (which I assume is a block view) to pull up only those nodes that share the same topic parent with the current node's topic parent.  Sooooo, in your Contextual filters section (under 'Advanced'), choose the "Taxonomy term: Term ID" option.  Under the 'Relationship' choose, 'Parent topic' (or whatever you named your parent term relationship).  After all, we'll be filtering exactly by that - the term id of the parent of the topic term.
Choose to 'Provide a default' value for this filter when it's not available.  The truth is, we have to get the parent term id from the current node ourselves (I don't know how else to do it).  Choose that we'll provide it with 'PHP Code' and type in the following:

$node = menu_get_object();  // Get current node
$topic_term_id = $node->field_topic['und'][0]['tid']; // Just gets first topic term
$parents = taxonomy_get_parents($topic_term_id);
reset($parents); // Make sure pointer points to first element
return(key($parents)); // Return first key

Here's what my contextual filter looks like:

Obviously, I'm not really doing many checks in my code to test for the existence of terms, etc, but this should just about get you there.  Let us know if it works.  I just tested it and it works for me!!!


How to create a unit test for a class which uses a trait? Simple as this:
class A {
  use StringTranslationTrait;

  public function something() {
    $b = 1+2;
    $this->t($b);
    return $b;
  }
}

I would like to unit test the something() method, but I can't since the StringTranslation trait uses a static container call:
Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$containe is not initialized yet. \Drupal::setContainer() must be called with a real container.

What do you suggest?

Following on Bedir's answer, here is an example.
I have a test that is using the class DurationService. DurationService uses the StringTranslationTrait as follows:
class DurationService implements DurationServiceInterface {
  use StringTranslationTrait;
  ...

To test this, I am doing the following (note, using a class that extends UnitTestCase):
$duration_service = new DurationService();
$duration_service->setStringTranslation($this->getStringTranslationStub());

This calls StringTranslationTrait::setStringTranslation() passing it the response from UnitTestCase::getStringTranslationStub().


Search API returning no results even though nodes have been indexed I have a very simple set up as described below.

modules:
Search API 7.x 1-1
Search Pages 7.x - 1.2
Database Search
Devel Generate

I’ve set up a database server and an index for indexing nodes. The nodes were created using the Devel Generate module. The nodes have been indexed as shown on the Search API ->View->Index Status. On the Nodes->Index->Fields tab I’ve several options like Node ID, Content Type, Title, Status, etc. In Structure->Blocks I’ve added the Search Index to the page in the sidebar.
I also set permissions so anonymous users can administer  search.

But when administering a search nothing is returned.  For test purposes, when entering in the same search term (‘Amet’) in the default search, results are being returned.

How do I troubleshoot this? What is the problem here? Anyone help would be appreciated.

What type have you selected for your indexed fields?
I think search_api_page only handles fields using fulltext indexing, and wouldn't be so useful for numeric fields like nid, or text fields indexed with the string type.

You could also try using Views with search_api


Use separately the links of $links How to separate the links of the variable $links (in nodes and comments) to be able to place them in various places?

You can add variables in hook_node_preprocess in the template.php file in your theme.  Something like:

function MY_THEME_node_preprocess(&$vars) {
  // EXAMPLE: add variable according to view mode.
  switch ($vars['elements']['#view_mode']) {

    case 'teaser':
    $link_text = t('Add new comment...');
    // Build render array for link.
    $link = array(
      '#theme' => 'link',
      '#text' => $link_text,
      '#path' => "comment/reply/" . $vars['nid'],
      '#options' => array(
        'html' => FALSE,
        // Make sure it jumps to the right anchor point
        'fragment' => 'comment-form',
        'attributes' => array(
          'class' => array('add-comment'),
        ),
      ),
    );
    $vars['add_comment'] = $link;
    break;
  }
}

And then in your node.tpl.php you can check for $add_comment and print it out using render():

    <?php if (!empty($add_comment)): ?>
        <?php print render($add_comment); ?>
    <?php endif ?>

You can probably split out the comment link from $vars if that is neater.


How do you add a input and a select field with webforms? I would like to add a select element that has an input field attached, so the user can input a value from the list without having to scroll through hundreds of options. Is this possible to do with the module webforms? I have researched it and the only thing I can find is the chosen module but I have no idea how the two integrate, and alot of people say it is incompatible in some browsers. Thank you for your help.

Welcome to the Drupal Answers Mel.
You can use the Select or Other module. When you enable it, you get another element called Select other. Please take a look at the below screenshots:

Hope that helps.


Drupal 7 Multilingual Site Search I have a drupal multilingual site (English and Arabic) . Arabic page site search gives me an extra value "English" in search result. I am using default drupal site search.

What it actually means? How can i remove this?

That is because of language switcher enabled.  Go the particular content type page, edit and in publishing options CHECK the check box Hide content translation links.


Suggestion tpl help for NiceMenu markup? I'm using NiceMenus to display my taxonomy tree. Since I chose no parent menu, the module displays the root items as separate hoverable menu "tiles", which is OK. They are however
 items enclosed in one
. Due to styling/layout issues, what I want is that each of the tiles have individual parent
.

So instead of having:

root item 1

root item 2

root item 3

I want:

root item 1

root item 2

root item 3

and then I'll be able to easily absolutely position each
.

So the question is presumably a piece of cake for you guys: how to change the markup - probably using a suggestion technique... Should I override the block? How should I name the tpl file so to force my markup?

Thanks,
Artur

Why can't you just position your li's absolutely? Generally, you should be able to position li's the same way as separate ul's using CSS.

Anyway though, to answer your question, have a look here: Customize Drupal 6 Nice_Menus Output

(Ok, you're asking for D7, but the general idea should be the same/very similar.)


How to load user via user email? I am going to import data from a csv file, specifically linking a node to a user. I see that I can link a node to a user via user id, however I won't know the user id on import. Is there a way I can link the node to the user via user email?

Thanks!

Ofcourse you can get user id by email, check this out: http://api.drupal.org/api/drupal/modules!user!user.module/function/user_load_by_mail/7