Altering (adding) field value when is unknown I have three content types (A,B,C). A and B have title, author, and field_version (a custom field), while C doesn't have field_version. Let's assume I have a method that gets the version value from a node. (The $node parameter is an entity object.)

function getLatestVersion($node) {
   $version = $node->get('field_version'); //for A, B is OK, but for C - field_version is unknown
}

How can I check the field exists for the node passed as argument without comparing the node type with an hard-coded list?

For nodes, like for every content entity, you can use code similar to the  following one to check if a Field API field(*) exists.

if ($node->hasField('field_version')) {
  // The node has that field; access it with $node->hasField('field_version').
}

A more generic code that would work for either Field API fields or non-field properties would be similar to the following one.

if (isset($node->field_version)) {
  // The node has that field/property; access it with $node->field_version.
}

* I am using the terminology used in a comment for code in ContentEntityBase::__isset().

// "Official" Field API fields are always set. For non-field properties,
// check the internal values.
return $this->hasField($name) ? TRUE : isset($this->values[$name]);


Kernel base test for media view displays is failing with: LogicException: Missing bundle entity, entity type media_type, entity id image I am trying to test media view displays via a test, which is based on the KernelTestBase class. I have also tried to inherit from Drupal\Tests\media\Kernel\MediaKernelTestBase, but got the same error from bellow:

  LogicException: Missing bundle entity, entity type media_type, entity
  id image.

My test class looks like this:

<?php

namespace Drupal\Tests\degov_image_and_crop_styles\Kernel;

use Drupal\Core\Extension\ModuleHandler;
use Drupal\KernelTests\KernelTestBase;

class ModuleInstallationTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'user',
    'migrate',
    'migrate_drupal',
    'system',
    'node',
    'taxonomy',
    'field',
    'file',
    'image',
    'media',
    'media_test_source',
    'text',
    'filter',
    'language',
    'content_translation',
    'image_widget_crop',
    'crop',
    'lightning_core',
    'responsive_image',
    'breakpoint',
    'degov_image_and_crop_styles',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installEntitySchema('node');
    $this->installEntitySchema('file');
    $this->installEntitySchema('media');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('taxonomy_vocabulary');
    $this->installEntitySchema('user');
    $this->installSchema('system', ['sequences']);
    $this->installSchema('user', 'users_data');
    $this->installSchema('file', 'file_usage');
    $this->installSchema('node', ['node_access']);
    $this->installConfig(self::$modules);
  }

  public function testSetup(): void {
    /**
     * @var ModuleHandler $moduleHandler
     */
    $moduleHandler = \Drupal::service('module_handler');
    self::assertTrue($moduleHandler->moduleExists('degov_image_and_crop_styles'));
    self::assertTrue($moduleHandler->getModule('degov_image_and_crop_styles'));
  }

}

Does anyone know, what I am missing here?

I could solve this via:

$this->createMediaType('image');

Also I inherited from MediaKernelTestBase.


TB Mega Menu Problem Reordering Columns I have a site using tb mega menu. The only problem I have with it is it will not allow me to place a column to the left of another column. It just groups the two with the one I want to move always at the bottom. This wouldn't be much a problem if I could reorder the structure menu and see it affected on tb mega menu pages. The only solution I found was deleting the database row of that menu and starting over.

I had this problem and it was due to weights I had on the menu links as well as the actual ordering in the menu admin page. I re-ordered them in the normal menu settings page, and then I was able to order them properly in the TB Mega Menu settings page.


Link image to another view mode with Media 2 and File Entity I'm trying to test Media 2.x and File Entity. I've edited the "Image" File Entity to add taxonomy terms and all and then I'm trying to leverage views to list all images in a grid in a page, and my end goal is to be able to click on a thumbnail and then get a larger image with more details.

I'm finding it complicated (impossible?) to link the images to another display (teaser to full content for instance). It works just fine with regular "Content" views but it seems that when you start with the "Files" view this is not an option.

Do you have any idea what I'm missing? Is there a way (relationship or anything) to be able to get the "Link this image to its content"-like option?

I'm not sure what you're asking. Normally you say "show title" and check "link this to content". Same thing here, Make your File view_mode whatever you want and link it to your content url. You may be asking for a Lightbox approach to showing a set of images.

If there's no option to "link to content" for this field, simply create a rewrite url in the Views Field settings to generate a link using tokens.

Now you may ask -- this isnt addressing the teaser -> full view_mode switch for the Entity (or Field?). Creating links in Views, or with the l() function has nothing todo with View Modes ... they're just links you're making.

I find it helpful to add additional view modes to entities, I have used Entity View Modes for that.

You either setup a custom URL to your content that forces the view mode, using for instance View Mode Page or you could try to set a context or something and hand code something that forces the view mode on your destination url yourself using a custom module, for a small example:

/**
 * Implementation of hook_entity_view_mode_alter().
 * Change the view mode of an entity that is being displayed.
 */
function MYMODULE_entity_view_mode_alter(&$view_mode, $context) {
  if ($context['entity_type'] == 'node' && $context['entity']->type == 'slang_word') {
    $view_mode = 'slang_dict_word';
  }
}

You could use a custom view mode to only show the Field in question -- with the custom view_mode set.

... maybe this rambling will help you or someone else :)


Javascript amateur's problem I have a function:

  jQuery(function($){
    $(document).ready(function(){
      $('.Testimonials').each(function(){
        var theContent = $(this).html();
        theContent = '-' + theContent;
        });
    }); // END doc ready
  }); // END function

Basically I wanted to add a text before an option (unable to do it by css). What am I doing wrong?

I tried like this as well:

$('.Testimonials').insertBefore($(this).html(), $('text'))

but it doesn't work either.

It can be done this way, i don't see any reason to to use each() function.

 $(document).ready(function(){
        $('.Testimonials').text('sample text '+$(this).text());

      }); // END doc ready

It will add text before each element having class Testimonials.


Content type 'Product Display' not available when creating new View I am working through the "Advanced Product Display Listing using Views" guide here.
When creating the new View, I do not have the option to select 'Product Display' as a content type.
Is there a configuration setting I have missed when installing Commerce from scratch?
Thanks,
Geoff.
Drupal 7.67,
Commerce 1

For D7, Commerce 1, unless you use Commerce Kickstart, you have to manually create it. Follow this tutorial.


Know if node is in view, edit, delete, etc. in page.tpl I need to verify, in page.tpl file, if page is currently showing a node for viewing, editing, or deleting purposes.

I found I can write arg(2)=="edit" to verify if it is in "edit mode", but how to do for delete (arg(2) is empty such as for view).

What is the correct way to get this information?

Thank you

Here's how to check against all paths related to nodes:

Node view:

arg(0) == 'node' && arg(1) && is_numeric(arg(1)) && !arg(2)

Node edit:

arg(0) == 'node' && arg(1) && arg(2) == 'edit'

Node delete:

arg(0) == 'node' && arg(1) && arg(2) == 'delete'

Node add "landing" page from where you choose which content type you want to create:

current_path() == 'node/add'

Node add page for a specific content type:

current_path() == 'node/add/YOUR_CONTENT_TYPE'

All node add pages:

arg(0) == 'node' && arg(1) == 'add' && arg(2)


assign permissions to a created role? i want to assign permissions to a role in my hook_install() , but the permissions that i'm adding are part of my modules hook_permission()
 don't exist yet?
so how to grant permissions role created in hook_install after hook_permission ?

NB :

i have D7.23
     -
my module create the role and his permissions .

Thanks.

the solution found in http://www.dibe.gr/blog/drupal-7-create-users-and-roles-programmatically in the author comment , so i'm set only the permissions array of my custom module in hook_install() user_role_grant_permissions($role_rid,array_keys(module_invoke('my_module', 'permission')));


Drupal 7 treat html 5 data attributes as text First I wound like to clarity i am not asking for code.

This code work on html 5.

I create basic page in drupal and implement same code:

Drupal treat data as text and print this:

data-top="opacity: 1" data--400-top="opacity: 0" class="abc"

Do I need any module to enable html5 data attributes?

I am using FULL HTML and I have no idea how to solve.

Many Thanks.

I am not using this module. Try once this module, hope you will get some configuration settings.

HTML5

  This theme will be the official back-port of the theme-related work
  done in the Drupal 8 HTML5 initiative. We want everyone to be able to
  preview what's coming in Drupal 8 from a markup and CSS perspective.
  We want anyone to be able to easily review our progress without
  needing to create another install of an unstable, or unfamiliar
  version of Drupal.

HTML5 Tools

  HTML5 Tools is a module that allows Drupal sites to be built using
  HTML5 ... smartly.

  One of our goals is to provide as much support for HTML5 markup in a
  set of Tools provided by a module so that you can use this module with
  any HTML5 theme you'd like.

HTML5 Media

  This project has one goal. To bring a standardized, Open Source GPL
  front end media solution to Drupal core. This project is completely
  open and has no other intentions other than to provide a standard
  front end media solution that will benefit the entire Drupal
  community, so therefore, whoever would like to help in this initiative
  is welcome to contribute!


How to create unique banner for each node and views page? What I am trying to achieve:

I want the unique banner image for each node and the views page, where the site administrator can simply upload the image and description to upload the banner for each node.

What I have done so far:

I have created the custom paragraph (https://www.drupal.org/project/paragraphs type) with image and description field and attached it to the content type.

Then I have hidden the paragraph field from manage display and then I installed field as block module(https://www.drupal.org/project/fieldblock) to display my attached field, particularly attached with the node from block layout in the custom banner region.

Problem:
With this approach I successfully created a unique banner for content type; however, I am not sure how to achieve this in views page. Any other approach I could achieve this?

I'd suggest to use core's Custom content blocks to create blocks (similar to your banner paragraph for nodes). Then you've got two options:

You can either use Block Layout to place the blocks, but limit visibility of the block to certain pages/URLs. Pro: You can directly place the block in any region. Con: It will clutter up your Block layout page if you've got a lot of views.

Or you can go to Views UI and place the block in the header of the view (middle column, below Page settings). Pro: Block and View are tied together in the same part of the Admin UI, no clutter in Block Layout. Con:The block will not be placed in your banner region


Get the referenced node ID I have a content type (a) referenced to another content type (b) by url widget, how can I get the ID of the referenced node (b)?
Thanks.

You can get node id using :

$nid = $node->field_reference['und'][0]['nid'];

And you can check it out from this:

drupal_set_message($nid);


Determine whether module is enabled / disabled I am trying to write a Drush script to enable a bunch of modules based on a hook. If it's already enabled, I would rather skip enabling that module.

Is there a way for Drush to return whether or not a module is enabled?

This code will list all non core enabled modules:

drush pm-list --pipe --type=module --status=enabled --no-core


How to upload images via CKeditor 6.x - 1.3? is there any way to one click upload images with a CKeditor? Found this https://drupal.org/project/ocupload but sadly - its for 7.x version of Drupal :(

Have you tried IMCE it can be attached with a number of WYSIWYG editors like FCK Editor, CK Editor, Tiny MCE


How to save JSON with a node What would be the best way to store JSON content with a node? Can I just use a text field for this or will this destroy the data?

I do not need to query this data, only load it occasionally.

I'm using Drupal 7 and MySQL 5.5.

Text fields can store JSON data since JSON, by definition, is a serialized format. This is provided the JSON data fits the size of your text field. If you go this route, you should make sure your field is validated for valid JSON before saving and is under your storage limits.

If you want something more versatile, you might want to add your own custom field with the Field API. There's also the JSON Field module, but it only has a D8 release.


How do I get both published and unpublished records using entity query? How can I get both published and unpublished records for a content type using entity field query?

As per documentation we can filter records by status either published or unpublished. But I need all records irrespective of node status whether is published are unpublished.

 <?php $query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1) // only one value accepted here
      ->range(0, 1);

The propertyCondition allows three arguments. You could pass in an array containing the two values and as third parameter the operator 'IN':

->propertyCondition('status', array(0, 1), 'IN')

Note: As you have been asking for nodes, and nodes AFAIK only have the status 0 or 1, you could also just omit the status property condition entirely and would get all nodes.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->range(0, 1);


Image thumbnail styles are not created I'm moving a website in a production server and it appears that the image thumbnails aren't created from an Image Field in a content.

The images are uploaded correctly but no files are created in styles folder. I've already set to 0777 each folder in case of a permission problem, but it's not that.

The big problem is that I can't remove the images, probably because it raises a forbidden file as it doesn't exist. The only error log I can find is an access denied but nothing else.

Does anybody has the same problem ?

It works okay on local... maybe an Apache issue to look at ?

Solution for Drupal 8 that worked for me:

  create sites/default/files/styles folder manually
  set its permissions to 775
  create .htaccess file in this folder with following content:

<Files *>
  SetHandler none
</Files>


How can I display the vocabulary description? I have a View which displays content by taxonomy term from a particular vocabulary, and everything is going fine... except for one thing. I would like to display the Vocabulary description in the View header. I have succeeded in doing this by creating an attachment in the View which just does a select on the Vocabulary but this seems to me rather cumbersome and I wondered if there is a better way to do it.

Also, although I have succeeded in attaching my Attachment to the main Page in the View, I cannot see any way of controlling the order in which they appear. As it happens, things appear in the order I want but it seems to be more by accident than anything else.

An attachment is the cleanest way to do this using the Views Admin UI. Attachments can be re-ordered in the region they are placed in the parent view.

Another way to do this which requires code is to use hook_views_pre_view() and to create a blank Views Header Area in your views admin area -- then in code via hook_views_pre_view() set the content of that area using PHP to the description of your taxonomy term. But I would recommend trying to stick to the Views Admin for creating your views, as the more custom code you put in files/modules the harder your site is to maintain or change.


programmatically attaching file to file media I am trying to programmatically attach a file to a node, using the media module now included in core as of Drupal 8.5.0.

I wrote this drush script to stub out the creation of a new file media content piece.

<?php

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
use \Drupal\media\entity\Media;

$file = file_save_data(uniqid(), 'public://test' . uniqid() . '.txt');

$drupalMedia = Media::create([
  'bundle' => 'file',
  'uid' => '0',
  'file' => [
    'target_id' => $file->id(),
  ],
]);

$drupalMedia->setName(uniqid())
  ->setPublished(TRUE)
  ->save();

When I navigate to the site's media at admin/content/media, I see my media listed:

But when I edit the piece of media, my text file is not attached to it:

There are no error messages in watchdog.

What am I missing? What do I need to do to attach the file to the media?

The key for file needed to be field_media_file instead of file.


How do I customize an article URL alias? In Drupal 6 there is a possibility to customize URL alias by the help of [AUTOMATED ALIAS SETTINGS], but this will affect all the articles. I need to restructure my URL alias only for few paid articles.

Can we able to add /pro/ somewhere in the url only for few articles like as follows,

Original article url parameters:

www.example.com/{article}/{channel}/{year}/{month}/{nid}/{article_title}

Customised article URL:

www.example.com/pro/{article}/{channel}/{year}/{month}/{nid}/{article_title}

There are so many module for this you can check

Pathauto

Path redirect

Global Redirect


Youtube API module: Post videos to Youtube I need to upload videos of my site to Youtube. From Load video to youtube when node save a few modules are introduced that do this.

But I need to do this using an API. I mean I don't want to use the modules interface, I need to have a special interface which is a simple checkbox in the node page of a video to post the video, once a user checks the checkbox.

The Youtube API module seems to be the appropriate module to do this, But I really have no idea of how to use this module. Using the APIs I can use a simple .php  file, by calling it via AJAX, then post the video.

How can I do this? Is there any tutorial for Youtube API module?

Create a custom module, in mymodule.module use hook_node_update

function mymodule_node_update($node) {

  if (isset($node->field_checkbox[LANGUAGE_NONE][0]['value'])) {
  // If field checkbox is set (not empty), then...

     // youtube api code goes here.

  }

}

  The Youtube API module seems to be the appropriate module to do this,
  But I really have no idea of how to use this module.

According to the Youtube API module project page:

  This module is an API module, meaning that it in itself doesn't do
  anything

Therefore, all this module does is install libraries that you need in order to interact with the Youtube API, nothing more.

You need to read the Youtube API documentation from https://developers.google.com/youtube/documentation/
and learn how to code for youtube api.


I'd like to add a second "Save" button that saves the node as usual, but I can use a module to alter the node EDIT: Answered below.

Bit of a weird one. I'd like a second Save button that saves a node but that I could target with some php.

Save Save Progress Cancel

My use-case isn't as simple as using Autosave and I don't want to start installing WorkBench or any other module for a small feature.

I could have a taxonomy field above the save where users can choose, but really, I'd prefer a second Save button for UI reasons. I could also use jQuery and have psuedo-buttons that click the appropriate term and then the save button, but I'd rather do it programmatically.

Thanks.

I had to do this with a validate handler instead of a submit handler. I'm not sure of the implications of that but it works.

<?php

function custom_assignment_save_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == "assignment_node_form") {
        $form['secondsubmit'] = array(
        '#type' => 'submit',
        '#value' => t('Save Progress'),
        '#weight' => 100,
        '#validate' => array('node_form_validate', 'custom_assignment_save_form_validate'),
        '#submit' => array('node_form_submit'),
      );
    }
}
function custom_assignment_save_form_validate($form, &$form_state) {
    form_set_value($form['field_boolean'], array(LANGUAGE_NONE => array(0 => array('value' => 1))), $form_state);
}

This simply changes a hidden boolean value when the Save Progress submit button is used.


How to sort a View according to contextual filters? I have a view that filters nodes by a contextual filter that allows multiple values. So it gets a list of node IDs like 234, 235, 210, 56, 78.
Is it possible to sort the result of this view according to the order of the given IDs?
I tried to achieve that by deleting all sort criteria, but this leads to an arbitrary order of the results.

The Views Arguments Extras module (for Drupal 7) seems to do what you are looking for. According to the module page, it provides the following:

  Argument Order Sort

  a sort handler, that allows for the order of items to be based on
  their order in a multi-value argument

This particular component is ported to Drupal 8: Views Argument Order Sort:

  Using this module will give you a new sort type with a variety of
  options where you can choose what field to apply the argument values
  to for sorting.


D6 to D8 migrate new content I did a D6 to D8 migration in 10/2015 and I recreated the blocks and views not migrated.  But in the mean time 6 month later my D6 original site has been getting more content.

What is the best way to bring all of that content from the last 6 month from my D6 to my migrated D8?

You should use migrate module, it's in drupal8's core.

You can define migrations for blocks, nodes, comments, users ... and launch then when you need.

You can select "update" option to syncronize imported content on your new site with changed content on old site.

Here's the offical doc of migrate:
https://www.drupal.org/migrate


How to add a conditional billing field based in Country in "Commerce Kickstart"? I added a new billing mandatory field called "NIN Number" at admin/commerce/customer-profiles/types/billing/fields

But I only need to show this new field only if the selected country is United Kingdom

How can I do this?

Will the https://drupal.org/project/conditional_fields module be usefull to get it?

I don't think you can use conditional fields because of the internal structure of the addressfield module, you need to use some custom code here, using the #states property and checking against the value of the country.
Using hook_form_alter, you can edit that form, here's an example of #states coming from the examples module:

  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),
    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );


Drush site-install and extra settings for the settings file? We are developing a site with a make file, profile and drush-si.
Thus far it's great, but i cant find a way how to add some slightly more complex settings to the settings.php file. For the beginning, base_url and second database would be totally enough :). Memcache and proxy are other candidates.

Or is this something that could be done in an installation profile ? Where ?

Checkout the post about Collecting and writing configuration settings to setting.php from an install profile.

It describes how a custom task was injected into the installation profile and then details how drupal_rewrite_settings() was used to inject the custom settings into settings.php.


Combining Drupal & WordPress on a Multi-Site Project This is going to be a tough question to ask without violating the "Questions with too many possible answers or that would require an extremely long answer" rule, but let me give it a try...

I have a variety of websites focusing on a variety of topics, from animals to politics. I'd like to combine them into a single mini-encyclopedia. However, I don't want to delete the existing sites; rather, an article about the aardvark at www.geozoo.org/Life/Aardvark would also appear in the new encyclopedia at www.geobop.com/Aardvark.

At the same time, I'd like to upgrade to a popular CMS, like Drupal or WordPress. (I created my current CMS myself.) Rather than choose between Drupal and WordPress, I'm thinking of using one for the main encyclopedia and the other for the satellite websites. There are two advantages:

Using two different CMS's will help me differentiate the sites, and
a special feature not available on one CMS might be available on the other CMS.

I'll have to find some forum where I can chat about this, but I wondered if someone could give me a short answer - is my idea a good one, is it a lost cause, or is somewhere in between?

One bridge I'll have to cross regards my series of database tables that hold all my content. I assume I'll have to modify them to work with Drupal and WordPress both, and that could be a steep learning curve.

Anyway, I'd just like to know if I'm on the right track or if I'm pursuing a dead end.

I would advise reconsidering your proposed solution and making sure any benefits are worth the potential extra effort/hassle, because I don't really see any pros for doing it and there is a very large con of complexity (for no real gain).

In terms of your current reasoning for wanting to do this:

Advantage 1: Using two different CMS's will help me differentiate the sites.

Why not just use different themes for different sites to differentiate them?
You could have different themes for admin, or front end, or both, depending on what you aim to achieve.
The themes could be totally different, or they could just be the same theme in different colours, or something in between.

Also, wouldn't it be easier if the editing/admin experience is the same for all sites instead of being different?
This also goes for any user interaction with the site from non-admins.
Consistency is an excellent thing.

Advantage 2: A special feature not available on one CMS might be available on the other CMS.

Both platforms are very mature and can handle most things. If you want to do something really different you're probably going to have to write code to do it regardless of the platform. If you have two different platforms and you want to do something custom on both that means you have to write both a drupal module and a wordpress plugin (or modify existing modules/plugins for both platforms), so you're making more work for yourself.

It also sounds like the special features you talk of are things you might think of in future.
If you are choosing platforms try to think of all the features you want first (and features that maybe you might want in future), then choose the platform that is best for implementing those features.
Obviously you might think of things in future that you didn't originally think of but there isn't much you can do about that so the platform you consider the most flexible, and the platform you prefer to do custom code for wins points in this regard if you think that complex new functionality might be required in future (remember here that a large amount of commonly used functionality is available on both platforms).

Now there are the disadvantages, which include but are probably not limited to (I don't know exactly what your plan is for these sites to work together or interact with each other but these things are still likely relevant):

Possibly doubling effort when you have to write custom code (as mentioned above).
Adding effort when doing maintenance, like module/plugin updates.
Added complexity, which could make it harder to develop the new features you come up with in future, could make it harder to track down problems when they occur, could make it harder to use the sites (or understand how they work together) in general.
System requirement mismatches. These two platforms require basically the same things but sometimes to do something on a given platform you need a specific version of PHP, or MySQL, jQuery versions etc. Getting two platforms sorted out with specific library versions will be harder than one (if they have to match, maybe they don't).

Basically I think it is best to achieve what you want in the simplest way possible.
Sometimes adding complexity is necessary for the requirements, or you may be able to create something that much better and it will be worth the effort/hassle but if not, and you are adding complexity and gaining nothing of value in return (or the potential value doesn't outweigh the potential troubles), then you are losing out.


jQuery error "C is undefined" while making ajax call for pagination I am using Ajax for pagination for a form in Drupal 6 project. It is working fine on my local machine with default theme but on live server it gives me an error and generates another pagination links below original one.

When I click on Next, Previous or page link it gives me an error "c is undefined
http://siteurl/sites/default/files/js/js_2ebf7f4036f86f9133a99317ed832acf.js/eval/seq/1
Line 1". Every time I click on link, it gives me the same error.

I have searched for some solutions, like http://drupal.org/node/846026, but they are not useful

Finally I fixed it. But I think there should be better way of doing that. All I did was, I added latest jQuery file from Google CDN in the module itself as it was clashing with Drupal 6 dynamically added jQuery 1.2.x and giving me error.

 drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

I used some ajax calls for pagination, due to which old jQuery was giving me an error. It is fixed with newer version of jQuery. I also tried http://drupal.org/node/1058168 but it was also not useful.

Please suggest if there is any better way of doing the same.


Theme the “save” button in a profile page, on a Drupal 6 installation? How do you theme the "save" button in the profile page (user/uid), on a Drupal 6 installation? I´ve tried and when I try to theme it, it theme all "save" buttons on the site.

Thanks!!

Rosamunda

Found it! I thought I would post it here just in case anyone wonders the same...
HOOK_FORM_ALTER!

Yay, it was sooo easy with that. With hook_form_alter you can add a prefix and a suffix with the css classes, and that´s it.

This video podcast of mustardseedmedia helped me A LOT.

Cheers,

Rosamunda


Programmatically delete field collection items Is there any way to delete field collection items programmatically in Drupal 8?

I have created a field collection item and attached it to the user entity in the following method.

$user_id = \Drupal::currentUser()->getAccount()->id();
$user = User::load($user_id);

$fc = FieldCollectionItem::create(array(
  "field_name" => "field_hobbies",
));

$fc->set('field_name', 'Watch TV');
$fc->setHostEntity($user);

It works fine and the field collection item got created successfully. Now I want to delete this field collection item. That means, I want to delete the hobby from the user. Is there any way for doing this?

Copied from (and then tested):

https://www.drupal.org/node/2757827#comment-11398243

$user = User::load($user_id);
$storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
$fc_items = [];

foreach ($user->get('field_hobbies') as $item) {
    $fc_items[] = $item->value;
}

if (!empty($fc_items)) {
    $items = $storage->loadMultiple($fc_items);
    $storage->delete(items);
    $user->set('field_hobbies', array());
}

$user->save();


Is there a stable way to fill a filefield/imagefield via bulk upload in D7 OK, here's the deal. I've implemented image gallery nodes in D7 the straight-forward way, i.e. create node type 'gallery' and add an imagefield with unbounded number of values. Nice markup via Views/EVA, done.

Now, to make the image upload convenient, I tried the following ways and got the respective results:

Multiupload Filefield Widget: The uplaod goes through, images appear on server side, but php runs out of memory while computing the ajax response for the upload.

Plupload widget: Upload works, but side crashes on save. I get lot's of visible json instead of the saved side.

Plupload via Fielfield Resources: Upload goes through, after that no visible response. On save, I get a long list of copy/rename error messages above the actual side.

The problems are present for pure file fields, on a otherwise pure D7 installation, so image processing is off the table as well as memory polluting modules (up to the ones mentioned above, appearently).

So the question is, why is it so memory consuming to compute a not so lengthy ajax response? The side shall collect several galleries containing each around 200-400 pics, so a nice way to bulk upload those jpgs would be great.

For completeness, the only stable way I found (and it's still not perfect, though) is to use plupload in combination with block_upload to get a PLUpload widget on the content site once it is created. It still is not the perfect workflow, but it currently allows me to dump 100s of photos/files into one filefield. Using PLUpload during node creation didn't work, btw.


Proper approach to two different address data sets on the system I have a certain design problem here. The web site I'm working on will need to have 2 sets of address details

under user account, as an indication of user's business address
at the commerce checkout, as billing address

For commerce checkout I've been using built-in customer billing profile and it works ok. But I'd like to maintain a similar format for user address. The plan is to populate the billing address form during checkout with user's business address by deafult but also allow to modify billing address without changing business one

At the moment I'm concerned that I'm mixing different structures too much. I have billing profile for commerce, profile2 for users but also couple of custom fields created under Account Settings. What approach would you suggest to setup the user account fields so it's clean, easily referrable to each other and not confusing?

I'd just use Commerce Addressbook, it would allow you to have a set of addresses in your user account, from project page:

  Commerce Addressbook is a module that allows authenticated customers
  to reuse previously entered addresses during checkout. They can manage
  all entered addresses in their user panel (user/%user/addressbook).

Seems exactly what you're looking for and is way less complicated that dealing with the addresses and defaults yourself.


Module release date and commit date? I can't understand somethings about commits.

For example, for the Webform module, in its project page it is written that last version is "7.x-3.15 2011-Dec-08," but in the commits page, it is written that there is commits to 7.x-3.15 in 25 February 2012.

I also checked the releases page; one of them has been released on December 2011, and another has been released on February 2012.

Does it mean that these versions were commited to git, but not released?
So it was an unstable version?
Is this usage common for Drupal module releases?

It is common in pretty much every software project. It makes no sense to release a new version for every single change unless it is critical enough (e.g. security fix). So releases are e.g done on a regular schedule (Drupal core does one every month now).

It is common practice to list the issues that where implemented/fixed as part a release in the release notes.

There are usually multiple commits every day on Drupal core, imagine there would be a new version every time.

What's somewhat uncommon with Webform is that it they don't list their development snapshot releases on the project page. Those are automatically updated twice a day if there have been any commits. In case of Webform, that snapshot still exists, but, according to the description, should only be used for testing recently fixed issues: http://drupal.org/node/730862.

The quality of development snapshots can heavily vary between projects so it's generally not recommended to use them. One exception for example is if you encounter a bug in a module then it often makes sense to test the snapshot first if there is a newer version than the last release.


How do I add rel="nofollow" to links in blocks/menus/etc? I want to add rel="nofollow" attributes to links that point to login/ToS pages in my Drupal 7 site. How can this be accomplished?

I think this is the module you are looking for:

http://drupal.org/project/menu_attributes

With Menu Attributes you can set the rel attribute (among many) on the admin section.


How to arabic emails are right aligned In my drupal8 site iam using arabic email  for signup,login,forgot password etc.I have get arabic email content.The email content is left aligned.I am using PHP Mailer in my site to sending emails.When i have tried with Mail Systems+Mime Mail+SMTP,then showing an error like "reply-to" is not set.Is there any possible to align arabic email content from right to left using default PHPMailer?

You can install Mime Mail or HTML Mail module to enable HTML emails in your Drupal instance.
Then, through configuration translation, you can add dir="rtl" to the container enclosing your Arabic email message.


Check if user is online I need to display an image when a user is online. Like the button of skype that it say if the user is online on skype's system.

How can I "check" if a user is online ? Is there a light module or I need to create a new one ? I don't need any type of block o stats about this user, only know if he is online or not.

Thanks.

For readability, and simplicity, I like to use the core API:

Check if current user is authenticated

user_is_logged_in()

i.e:

if (user_is_logged_in()) {
  // User is authenticated
  print $content;
}

You can also use

if (!user_is_logged_in()) {
  // User is anonymous
  print $content;
}

though there's even a user_is_anonymous() function

if (user_is_anonymous()) {
  // User is anonymous
  print $content;
}

Check if particular user is logged in

If you want to check if a particular user is online

You can use Rules, or hook_user_login to respond to login event

EXAMPLE_user_login(&$edit, $account){
  /* do stuff */
}

or query the session table for that user session uid

// Check if user $uid is online in the last 10 minutes
$online = db_query("SELECT uid FROM {sessions} WHERE uid = :uid AND timestamp >= :time", array(':uid' => $uid, ':time' => (REQUEST_TIME - 600)))->fetchField();


How to discard changes in Rules module Depending on a condition I want a node's changed content not to be overwritten on the old content. That is old content should be retained and new one discarded so that node does not change.

Which action should I add?
I've tried many but everytime a user saves a node, it is permanently changing the node's content.

Create a rule for the "Content is going to be saved" event, and add a "Execute custom PHP code" action.
The code you write have access to some variables by reference: $node, $node_unchanged, $user, $author, $author_unchanged, and $user.

For example, you can use the following code to set the title as it was before the node was  edited.

$node->title = $node_unchanged->title;

return array('node' => $node);

Similar code is usable in the version for Drupal 7 of the Rules module; what changes is the variables to which the code has access.


Repeatation of class while adding class in twig template I want to add CSS class to

 as shown in the following code. There are three

 codes where I have added calss using {{attributes.addClass('')}}

from book-navigation.html.twig

{% if tree or has_links %}

    {{ tree }}
    {% if has_links %}

{{ 'Book traversal links for'|t }} {{ book_title }}

      {% if prev_url %}

          {{ '‹'|t }} {{ prev_title }}

      {% endif %}
      {% if parent_url %}

          {{ 'Up'|t }}

      {% endif %}
      {% if next_url %}

          {{ next_title }} {{ '›'|t }}

      {% endif %}

    {% endif %}

{% endif %}

The output I am getting is with above code is,

But, I want as following,

Am I missing something, or there is other right-way to do that? Very Thanks.

If you don't want to add a class, but to replace the existing classes, you can use setAttribute().

<li{{attributes.setattribute('class', 'page-previous')}}>


Drupal 8 Development - How to Loop Through Field Formatter Elements All-- I'm trying to wrap my head around Drupal 8 development, and I'm trying to create a very simple field formatter.  It's being applied to a multi-file field, and I'm just trying to display information for each file uploaded to a custom content type that uses this field.

But-- I'm having issues figuring out exactly how to properly pass data from my PHP files to my Twig template. The code and Twig template below are displaying info about the two files uploaded to a page just fine, but as you can see, I'm not looping through an array of items; I'm just inserting the variable names for some metadata I'm trying to display for some file objects, yet it's looping through and displaying the info for each file uploaded to the page even though I'm not doing a Twig loop.  Also-- if I add HTML above or below the Twig template placeholders ({{uri}} and {{filename}}), the HTML is being duplicated for each file that has been uploaded to the page.

So long story short: how should I massage my code to pass data to Twig such that I can loop through it with a Twig loop (e.g., {% for item in items %}) and also prevent any additional markup in the Twig template from being duplicated?

NOTE: here is the original viewElements() function that I was using, and that was causing my issue; all the code after this block is the final code that actually works:

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $element = array();
    foreach ($items as $delta => $item) {
    // Render each element as markup.
      $element[$delta] = array(
      '#items' => array(
      'uri' => file_create_url($item->entity->get('uri')->value),
      'filename' => $item->entity->get('filename')->value,
      '#theme' => 'video_file_display',
    );
   }
   return $element;
 }

From FieldFormatter PHP file:

public function viewElements(FieldItemListInterface $items, $langcode) {
$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
 $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}
return $element;
}

From .module file (hook_theme):

function field_formatter_test_theme(){
  return array(
    'video_file_display' => array(
      'variables' => array(
        'items' => array(
          'uri' => NULL, 'filename' => NULL),
        ),
      'template' => 'video-file-display',
    ),
  );
}

Twig template:

Here is my page

{% for item in items %}
  {{item.uri}}

  {{item.filename}}
{% endfor %}

{{ kint() }}

Sample page output:

Here is my page
Twig context array(15)

(and examining the kint output shows null values for 'uri' and 'filename')

You define N #theme render arrays, if you want to be able to control the output in a single template, you need to define only one #theme element and pass it either two array of values or an array of arrays with a uri and filename key each.

$element[0] = array(
  '#theme' => 'video_file_display',
);
foreach ($items as $delta => $item) {
  $element[0]['#items'][] = array(
    'uri' => file_create_url($item->entity->get('uri')->value),
    'filename' => $item->entity->get('filename')->value,
  );
}


Zoom and center a GMap according to its markers is not working? Zooming and positioning the map to the center was not working in (Google map)
So we come up with small change in the code by adding time delay to it, then it was started working, may be it will use for someone.
  (fitbounds method googlemap api v3  for drupal 7 gmap)

jQuery(document).ready(function() {
  // time delay for the maps to initialize.
  setTimeout(function() {

// Loop through all gmap instances.
jQuery(".gmap").each(function() {

  // Get a map reference using the element ID.
  gmapID = jQuery(this).attr("id");
  var gmap = Drupal.gmap.getMap(gmapID).map;

  // Ensure map exists.
  if (gmap) {
    alert(gmap.toSource());
    // Create a new map boundary.
    var bounds = new google.maps.LatLngBounds();
    // Iterate though the current maps marker collection.
    jQuery.each(gmap.markers, function(index) {
      // Find the current markers position (latitude, longitude).
      var data = gmap.markers[index];
      var pos = data.getPosition();

      // Extend the new boundary so the new marker/pin will be in view.
      bounds.extend(new google.maps.LatLng(pos.lat(), pos.lng()));
    });
    // Set the current maps bounding box to our new defined boundary.
    gmap.fitBounds(bounds);
  }
  else {
    // GMap was not initialised in time.
  }

});

 }, 100);
});

This is what the code We added time delay on top of it. https://stackoverflow.com/questions/3520810/zoom-and-center-a-google-map-according-to-its-markers-javascript-api-v3

Instead of a delay, wait for a map loaded event. I could not find a direct one so used a mutation event.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
  var target_id = mutations[0].target.id;
  var map = Drupal.gmap.getMap(target_id).map;
  if (typeof map != 'undefined') {
    var initialLocation = new google.maps.LatLng(old_lat, old_lon);
    map.setCenter(initialLocation);
    // map.vars.zoom
    map.setZoom(12);
  }
});

jQuery(".gmap").each(function() {
  var gmapID = jQuery(this).attr("id");

  observer.observe($("#" + gmapID)[0], {
    subtree: false,
    attributes: true
  });
});

Subtree = false should mean that once the map is loaded this doesn't get triggered again. Add another test if needed.


Can I use drupal_get_form and drupal_render within a custom Drupal 7 input filter? As the title says:  I've got a custom input filter in Drupal 7 which replaces a token with a custom drupal form. Without showing the complete code, which might just confuse things, The main essence is the following:

function _my_filter($text, $filter = NULL, $format = NULL, $langcode = NULL, $cache = NULL, $cache_id = NULL) {
  $rendered_text = $text;
  preg_match_all(MY_CUSTOM_REGEX, $text, $matches);
  if (!empty($matches[0])) {
    foreach ($matches[0] as $match) {
      $custom_form = drupal_get_form('my_custom_form');
      $replacement = drupal_render($custom_form);
      $rendered_text = str_replace($match, $replacement, $rendered_text);
    }
  }
  return $rendered_text;
}

For some reason when the node is being saved this times out.  I've narrowed it down to being something in my drupal_get_form (but this form renders fine without any problems outside of an input filter).

Can I use drupal_get_form and drupal_render within an input filter like this?

I believe you can do this, but not by default. You'll need to disable caching. This is because the filtered data is cached, so your form will only work the first time. To disable caching, you need to set cache to FALSE in your hook_filter_info() definition.

If it's timing out, then it may be a problem in your form definition itself - does the for work in non-filter context (ie embedded directly into a page)?


Default sort order on the other table columns I render a table with theme_table() and use tablesorting (sql) for that. It all works fine.

Except for the intial/default sort on the other tables. No user sort option defined yet. Example:

Name | Age ▼

Sort by "age" is defined in the $header. User clicks on "Name". That now gets sorted ascending. Regardless! I need descending.

Click:

Name ▲ | Age

But I need/want:

Click:

Name ▼ | Age

Studying the code that determines the default sort order, in tablesort_header, I come across the following:

else {
  // If the user clicks a different header, we want to sort ascending initially.
  $ts['sort'] = 'asc';
  $image = '';
}

I see no way to avoid this. Do you? Did I miss some parameter, option? I refuse to believe that Drupal makes such a silly assumption without letting developers override it.

No, it isn't possible at this point.

There is an issue for that, I suggest you try that out and report back so that it can be commited soon: http://drupal.org/node/109493


Rewrite output in a view using CCK fields I'm trying to rewrite the output of a field. I have 4 fields and in the last one, I have rewrite output enabled:

[title]

[entity_id_3], [entity_id_1]

[entity_id]

The fields that are included in this output have "Exclude from display" checked so that's not a problem.

The problem is that the output turns into this:

Mr Speaker

Manager, Hotels

,

Hotel Inc.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et libero vel mi fringilla commodo ac ac felis. Proin fringilla tempor diam, ut semper dui vestibulum in. Vestibulum arcu tellus, elementum ac consectetur ac, tincidunt non eros. Nunc tempor ipsum eget erat fringilla tempus ut a enim. Donec posuere luctus mauris id ornare. Fusce at est lorem, et consectetur sapien. Pellentesque ac purus ac augue dignissim aliquet a rutrum turpis.

The fields that are part of the rewritten output are still wrapped in an HTML wrapper or label wrapper. I have no idea how to remove this and display just the field value.

In D6, you would look for the HTML Element, Label HTML Element and Wrapper HTML Element dropdowns in the Style Settings of the fields and set them to none. I am assuming (there I go again) that something similar is there in D7.


Filter the nodes by language output by the view Before I have i18n module and some modules that does the translations but we decided to stop doing translation but still preserve the translated nodes.

After disabling translation modules my views which are using content negotiation says "Broken/Invalid handler" so I removed this filter.

Now all the views are using nodequeue which has a bunch of multilingual nodes.

My question is, how can I filter views to display nodes based on page language. I mean I want to display english articles only when I'm in English pages, korean articles when viewing Korean pages, japanese articles when viewing Japanese pages, etc.

Ex. nodes(eng) for English pages, nodes(korean) for Korean pages, nodes(japanese) for Japanese pages, and nodes(chinese) when in Chinese pages

one work around is to re-enable the i18n module, to access the filter again, then use some hooks ( like hook_form) to hide and set the default values for the i18n options in the node form if you want to remove those options from the user interface.


Why are my prices showing up as unformatted (minor units) in a view on a search index? Bit of an odd one here, I am experimenting with the Search API, Search DB and Views. I have a view based on Commerce Products. The view works, along with most of it's facets (but that's another story).

I'm running into a strange issue. I have a view based on a search index using Search API and Search_DB. I have access to all the fields that I indexed, but price is presented as the unformatted price in minor units. It is pulled in as "Indexed Commerce Product Price>> Amount (Price >> Amount)"

The issue I'm having is that it's displaying price as 98,000 rather than $980

Why is the formatting changing? and what's the right way to pull that info into my search view? D-Commerce wants the prices in minor units for it's own internal formatting. I have a regular non-search view which has the correct price...

To start, if it's a Views view, check you field formatter within the view admin page.  You could also hook into it somehow (I'm not entirely sure how, possibly alter the query), to divide the price by 100, but only for formatting.


How can I dynamically set the site URL (in Drush9+)? In Drush 8 I had that neat little reusable line in my drushrc.php:
$options['l'] = getenv('MY_SITE_URL_VAR');

I know that I can hardcode my site URL in a drush.yml file, but that does not fit my configuration workflows, where each server knows its URL.
So how can I set the l option from an environment variable?

I don't see how you can easily reproduce that (nice) configuration setup since the yaml files are indeed static.
The only solution I see is to write a little wrapper script that always calls drush with the --uri option, like:
drush --uri $MY_SITE_URL_VAR $@

Recommended solution
A much simpler solution is to use the shell variable DRUSH_OPTIONS_URI.
export DRUSH_OPTIONS_URI=http://example.com

I wasn't able to find any documentation for this, but it seems to work.


What is the correct syntax to embed JS from Jquery UI website in Drupal 7? I'm trying to get simple JS to work on my site for testing, but having a hard time with the syntax.

The script I want to enable is simple hide script, html is:

Click anywhere to toggle the box.

JS is:

$( document ).click(function() {
  $( "#toggle" ).toggle( "slide" );
});

Example is here:

https://api.jqueryui.com/slide-effect/

What should I put in JS file to make this work with Drupal 7?

What should I put in JS file to make this work with Drupal 7?

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $( document ).click(function() {
      $( "#toggle" ).toggle( "slide" );
    });
    //code ends

  }
};
})(jQuery);

See Working with JavaScript and jQuery for in-depth info.


custom template file based on form type I'm using Omega's sub-theme creativpink. I put my site on web for testing purpose. Basically I want to customize page-user-reset page (user-pass-reset is form id). Now I click Request new password link enter my mail id to send password reset link. When I click on that link from my mail it redirects to page-user-reset page and it shows the following information:

Site Name

  Home

Reset password

This is a one-time login for username and will expire on Fri, 11/01/2013 - 20:41.
Click on this button to log in to the site and change your password.
This login can be used only once.
Login(button)

Powered by Drupal

Currently it includes header, breadcrum, content and footer regions. But I want only content region and the user password reset form inside content region. So I would like to write a template file based on this user-pass-reset form. Guide me what I want to do this? Thanks in advance.

You should be able to create a page--user--reset.tpl.php template in your theme directory alongside any other page reset templates and just include the content region inside there.  More information about template and theme hook suggestions can be found here (or at least after drupal.org comes back from its upgrade :) but the basic idea is to override the internal path of user/reset/../.. and Drupal is smart enough to ignore the rest of the path and just use the template given the base here.


How to set the default theme programmatically I've tried to set a theme as default theme in drupal 8 using the following code

> $config = \Drupal::configFactory()->getEditable('system.theme');
> $config->set('default', 'test_theme')->save();

On installing the module the code is not setting the theme as the one I've entered.
The code is written in hook_install().

The current advice is to set this via config:

\Drupal::configFactory()
  ->getEditable('system.theme')
  ->set('default', $theme)
  ->save();

The previous method using ThemeHandlerInterface::setDefault() is now deprecated.

You might need to install it first too, I'm not sure. In case you do:

\Drupal::service('theme_installer')->install(['test_theme']);


why doesn't system_menu() return the option I am expecting If you go to this website: https://api.drupal.org/api/drupal/modules%21system%21system.module/function/system_menu/7

You will see what system_menu is supposed to output. My Drupal 7 has a jquery update under the development menu in the configuration tab. Why doesn't the jquery update option show up? Is there another function that I should be looking at?

Thanks!

It's hard to know what you mean, but at a guess you're expecting system_menu() to be responsible for all of the paths you can visit in the system, and therefore you're expecting to see a listing of all paths in that function?

If so, that's not quite how it works. Drupal is extended by way of a hook system, one of those being hook_menu(), which allows modules to define menu items and page callbacks.

So in the case of jQuery Update, this is its implementation of hook_menu():

function jquery_update_menu() {
  $items['admin/config/development/jquery_update'] = array(
    'title' => 'jQuery update',
    'description' => 'Configure settings related to the jQuery upgrade, the library path and compression.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('jquery_update_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

And that's where the jQuery Update admin menu item and link come from.


Drupal Commons, can't break-contact error I am using Drupal Commons (7.x-3.46).. Whenever trying to  "break contact" of a trusted-contacts, I get an error:

  An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /batch?id=19&op=do StatusText: Service unavailable (with message) ResponseText: EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at og_membership(): . in EntityDrupalWrapper->set() (line 756 of C:\Users\USER\Sites\commons-7.x-3.46or\profiles\commons\modules\contrib\entity\includes\entity.wrapper.inc).

An authenticated user can't break-contact at all. Trying as an administrator, it throws the error, but does complete the operation, and does breaks the contact.
This seems (to me) to be a crucial issue. If users can't remove a contact, I dare-not give them the possibility to add contacts in the first place..

At some point I thought it was all about VBO, so (I think) I uploaded the dev version of it, but I'm still getting the same behavior.
Also, changing the php version as suggested somewhere, made no difference.

In my search for a solution I've come across many similar issues, some of which I've listed below. But I haven't found the very same issue I'm facing, and with so many different solutions I'm not sure where to start. In some posts it's about views-bulk-operations. In others it's about the Entity module. Or about Organic Groups. Or indeed about the Trusted-Contacts module itself.
As I'm no patching-guru, I'm uncertain of how to proceed

Similar but not identical issues:

Views bulk operations interrupted due to insufficient rights
https://www.drupal.org/project/commons/issues/2588155
https://www.drupal.org/node/1925412
https://www.drupal.org/project/views_bulk_operations/issues/1871702

to resolve this problem, two patches are needed:

1  patch for the trusted contacts module as discussed in comment #2 here:
https://www.drupal.org/project/commons/issues/2588155

2... and a patch for the membership-delete-action
 .../profiles/commons/modules/contrib/og/includes/actions/membership_delete.action.inc
as discussed here
https://www.drupal.org/project/opigno_lms/issues/2953675

works for me...
d


How to change stylesheet ordering of base and child theme? I have downloaded Drupal Commerce and started playing around with it. I have a new theme created using Commerce Kickstart as base. My theme is in sites/all/themes. Any styles that I put in the stylesheets of my new theme are being overridden by the base drupal commerce stylesheet.

How can I make sure my styles get applied on top of the default?

First of all, if you look into the  section of your code, can you find the css file? If not, it can be that the css is aggregated (in this case you'll find a random alphabetic css file), then clear your cache. If there is no aggregation, and you can't find your file, it is most probably set wrong in your theme.info file.

If the file is there, but not working, check in your browser (via fe element inspect) if and why the selectors are overridden...


How to show the values on the bars of a stacked bar graph in 3D? I have created a Stacked Bar Graph (in 3D) using the Forena reports module, which looks like so:

I was able to successfully create this graph. But I am having problems in showing the corresponding values on the bars. The values I want to show on the graph are:

colombia_blue:0.75
colombia_red:0.25
LATAM_blue:0.57
LATAM_red:0.43

I searched for the frx attributes. I found attributes to change the color of these 2 graphs, but not the label.

Here is the relevant part of my report specification (frx file):

Option 1 - Try another chart type

I recommend you experiment a bit with some of Forena's other Supported chart types, as documented within the "FrxSvgGraph" section of the "Custom Renderers"chapter (located with /reports/help.renderers#frxsvggraph of your site, and similar to this online equivalent).

More specifically, you seem to be using frx:type="StackedBar3DGraph". I think you will get way better results (to show the corresponding values) if you try with some of the other chart types, especially these ones:

MultiLineGraph
GroupedBarGraph
GroupedCylinderGraph

Option 2 - Add specific SVG Graph settings

If using another chart type is not what you want (= it has to be a Stacked Bar Graph in 3D), then you need to find the appropriate SVG Graph setting(s) (there are dozens, if not hundreds, of them ...) and pass such setting(s) as extra FRX attributes.

In that case, you may want to use some of the SVG Graph general settings. I haven't experimented with them, but I think you may want to try with these settings:

show_data_labels, which is a boolean (default = false), to "display labels for bars, markers or pie slices". In Forena, if you want to set this option to true, you'd specify it in your frx file like frx:show_data_labels="yes".
any of the settings starting with data_labels_... (there are dozens of them ...), to tune the data labels, like their fonts, positioning, etc.

Note: SVGGraph data labels explains some of the options related to labels, and how to use them.


$user->uid is false even when logged in I have this code:

global $user;

if (!$user->uid) {
  drupal_set_message("You must log in to view this content.");
  drupal_goto('node/153', array('query'=>drupal_get_destination()));
}

$user->uid evaluates correctly when logged in as admin and editor, but users that don't have admin or editor roles have NO UID. Immediately before and after this code resolves to false, I visit site-root/user, and sure enough, I'm logged in.

What setting causes this?  I've used this code many times to see if a user is logged in, and I can't find any setting that would cause this behavior.

Try using

global $user;

if(!$user->uid) {
  drupal_set_message("You must log in to view this content.");
  drupal_goto('node/153', array('query'=>drupal_get_destination()) );
}


What is wrong with this code returning error I am using this function to return metatag on front page of my drupal site

<?php
  if ($is_front) {
    echo "<META NAME="KEYWORDS" CONTENT="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">";
    echo "<META NAME="DESCRIPTION" CONTENT="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">";
  }
?>

But it throws the following error:

  Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /public_html/techiestuffs/modules/system/html.tpl.php on line 52

Anyone know what is wrong with this code ?

PHP can define a string with ' or ". Whichever one you choose, you can't have those characters in the string without escaping them: echo "need to escape any \" in this string"

You can use this instead to avoid PHP strings altogether:

<?php if ($is_front): ?>
<META NAME="KEYWORDS" CONTENT="Geek community,stuffs for geeks,geek contents,tech updates,electronics stuffs,tech geeks">
<META NAME="DESCRIPTION" CONTENT="Get articles related to Drupal,wordpress,design tips,Electronics,Web designing,Linux and Programming.Join our Tech community where you can share and get answers for your queries.">
<?php endif; ?>


How to run a batch process in regular interval I need  to Unpublish the nodes which are all not Updated for more than some specified time.

I'm having the query to fetch nodes and by using a batch process I will Unpublish those nodes one by one.

Now I want to schedule this operation to be run every day. How can I achieve that? using drush or something.

I have cron running at regular intervals. I need to run these scripts apart from the cron job i.e as a separate one.

You can use cron to do this, set a cron time in admin/config/system/cron for your site.

there is a hook_cron() is available in your drupal . using that hook you can configure your batch process to invoke.


View of all users and their relationship(s) with the current one I've been trying to create a view of all users, showing their relationship to the current one. I can't figure out a way to display all of them. By adding the Contextual filters User UID or Requester user, the views results are restricted only to users having a relationship (with the current one), therefore not showing the ones not having one...

I have also been trying to use the Relationship "Requester user is current user", but without success.

Here an example of the expected result: http://i.imgur.com/UbvupO8.png

Am I missing something? thanks in advance for your help

A contextual filter does not limit the results, it only adds additional input to the view based on certain situations.

It may be a problem with the relationship.

Please check that Require this relationship is not ticked. If  it is then by its description "Enable to hide items that do not contain this relationship".

If you just add the relationship but not require it, a field taken from the relationship will only display as a blank space in your rendered view.

Hope this helps. I had the same problem before.

Update 2014/06/20

I'm assuming the view displays users.

Contextual Filters

add User:Uid -- When the filter value is NOT in the url, provide a default value -- User ID from logged in user.

This filter will set it to display based on the current user.

Relationships

User relationships: Requester user -> use the contextual filter on this

You'll have to play around with this as I'm not sure.

Sort Criteria

UID ascending

Fields

UID: (this will display all the user IDs)
(check first after adding this that ALL users are displayed.)
Relationship Type
UID: (use the relationship)

Try adding the first field first then adding all the contextual filter, relationship stuff. It has to display ALL the users.


Use the panel for layout with multiple columns I created my own content type. I would like to further customize it by adding columns. I installed the module panel. Can I use the same panel layout to include my content type? Also, how do I put a picture in a field of the panel?

I would use panels for layout of a page which contains various bits and pieces from other pages. For layout of the display of a single page or node type I would edit the templates page--content-type.tpl.php and node--content-type.tpl.php.

In node--content-type.tpl.php you could then do something like:

<?php
  // Hide fields so that we can render them later.
  hide($content['field_image_main']);
  print render($content);
?>

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


Conditional fields on content type with paragraphs I saw this question repeat in a few places without an adequate answer.

I have a D8 site that has a certain contain type ('deals') which contains an array of 'deal' paragraphs.
Each 'deal' contains a 'deal_type' field and then a few content fields ('image', 'text', 'banner', etc.).

I would like to conditionally show the paragraph fields, according to what the user selected in the 'deal_type' dropdown.

I saw some answers mention a MODULE_form_alter() hook but this didn't seem to be called when I load my 'edit content type' page.

Can anyone help with this?

Yes you will have to hook form alter.
Make sure that you have done the following to make sure it's working.
1- create a module say it's called deals
2- add the deals_form_alter(...add the default params here ) In the deals.module file.
3- clear the cache
4- add your edit form is in an if condition then right the following logic. (You can get the form is by dumping the $form['#id'].
5- use the states functionality or Ajax callback to hide and show the fields you want.

https://www.drupal.org/docs/8/api/form-api/conditional-form-fields
And https://www.drupal.org/docs/8/api/javascript-api/ajax-forms


Unable to change the author of content using views/action I want to change the author of multiple nodes. I have set up a new action by going to /admin/config/system/actions and then selecting "CREATE AN ADVANCED ACTION" and then "Change the author of content..."

In my view of the content type I have added the "Node operations bulk form" field.

My problem is that when I try to update any content using this method I get the error "No access to execute Change the author on the Content [TITLE]'. The user has a role giving permission to edit the content.

I have looked at the code that generates this error - it is in core/modules/system/src/Plugin/views/field/BulkForm.php

        // Skip execution if the user did not have access.
    if (!$action->getPlugin()->access($entity, $this->view->getUser())) {
      $this->drupalSetMessage($this->t('No access to execute %action on the @entity_type_label %entity_label.', [
        '%action' => $action->label(),
        '@entity_type_label' => $entity->getEntityType()->getLabel(),
        '%entity_label' => $entity->label()
      ]), 'error');
      continue;
    }

Anyone any idea what I can do to get this to work? I need to change the author of thousands of nodes, so I need to work this out.

I just created a module for this, which allows you to change the Author as a batch operation on /admin/content, with a custom selection step to pick the new author.

Module: change_author_action


"Illegal Choice has been detected" I am dynamically populating <select> throught javascript in Drupal 7. The system gives me an error on submit:

"Illegal Choice has been detected"

How to mark, that this <select> must skip this error?

To solve the problem set '#validated' => 'TRUE' in your form element definition.

Example:
 form['my_dynamic_select'] = array(
 …
 '#type' => 'select',
 '#validated' => TRUE
 …
 )

Reason:

If we are using a dynamically populated SELECT (dropdown) via AJAX this error will pop up. When a value is not present in options array, Drupal will consider it as illegal. So the user couldn't inject an illegal value into the database.

But in our case it's totally ok, so we need to use the attribute 'validated' => TRUE to skip the validation.

Source: An illegal choice has been detected. Please contact the site administrator.


Getting data from a view to populate a select drop-down I am trying to implement a feature of a fancy drop-down select box. I am going to use the Chosen module to get the functionality I want for the select box. I have a view that lists the data that I want to populate the select box. All I need to do is render a plain old HTML select box with the fields and rows from this view.

How can I do this? Is there a style plugin or anything out there? I personally haven't found one after searching.

Going off of argiepiano's excellent suggestions, this is what I came up with: a module that provides a block with the select box populated by the view.

/**
 * Implements hook_block_info
 */
function my_module_block_info() {

  $blocks['my_module'] = array(
    'info' => t('Puts the values of My Taxonomy Term view into a select box')
  );

  return $blocks;
}

/**
 * Implements hook_block_view
 */
function my_module_block_view( $delta ) {

  $view_name = 'my_taxonomy_term_view';
  $display_name = '';

  $content = '<select>';

  $results = views_get_view_result($view_name, $display_name);

  foreach ( $results as $result ) {
    $content .= '<option value=\'' . $result->tid . '\'>'
      . $result->taxonomy_term_data_name . '</option>';
  }

  $content .= '</select>';

  $block['content'] = $content;

  return $block;
}


How to effectively remove module created fields? During the installation procedure of a module one may create some fields and corresponding instances and attach them to a content type. What is the best practice to clear up what we have created after module uninstallation?

It seems that removing fields created by a module is not yet implemented in D7 (see field_modules_uninstalled docs.). What would be the best approach then to remove module fields?

field_attach_delete_bundle

OR

field_delete_field

NOTE:
the comment module removes the field upon uninstallation (see here).

This is the code snippet I usually use to remove fields created by a custom module:

if (field_info_field('my_field_name')) {
    field_delete_field('my_field_name');
    field_purge_batch(100);
}

Hope this helps


How to create a custom node template in drupal8 rendering a view within a node page? I am trying to create custom node template in Drupal8. I would like my users accessing "tag" node to be able to view all related content. Therefore I have already created a view presenting all content relating to given tag. Now I want to render this view in a "tag" node page.

Following the https://www.drupal.org/node/2165673 I have create a custom theme. I have created themes/bartikUzbrojeni directory with the following bartikUzbrojeni.info.yml:

name: bartikUzbrojeni
type: theme
description: Modifications to the default Bartik theme
core: 8.x
base theme: bartik

I have also created templates directory within themes/bartikUzbrojeni with file node--tag.html.twig (being generally copy of node.html.twig from bartik directory).

This seems to more or less work (modifications done within node--tag.html.twig are visible within the page) but I have following problems:

The page does not look like Bartik one (the bartik theme does not
seem to be used even though I have marked it as a "base theme"). Please see screen below.
I don't know what is the proper way to edit  node--tag.html.twig so that it renders a view.

Here is how you can add the view, use a block view.

Then go to Blocks, and place a block in content.

Select your view block

In configure click on pages, then type the url of the pages you want it to show. So you put your tags url here. Use the * so it shows in all of them.

Just noticed I missed a / at the start, so it should be /taxonomy/term/*


Importing a bunch of users from csv spreadsheet file into Drupal 8 I have a large csv spreadhseet list of users with name, email, phone and username. The passwords can be the same for all as they will be blocked anyway.

I know there is an old tutorial of importing users via the migrate api in drupal 8 from here: http://www.metaltoad.com/blog/migrating-users-drupal-7-to-drupal-8

But that article is from 2014. Is there a new upto date way of doing this without the need to create a custom module? Is there a simple gui interface to get this imported? Or is there no choice but to make that custom migrate module?

Check out the Migrate Source CSV

I know that it uses drush and can import nodes through mapping it in a twig file and I'm pretty sure that it supports users too.

Full steps located here.


How to upload files which are other than English names? In Drupal, how to upload files which are other than English names?

The problem I am facing is that when I upload files for which their name is other than English their name changes to an unknown format in the file directory, like:

áˆ¾áŒáˆ®á‰½áŠ“ áˆ¨á‹³á‰µ á‹¨á‰µáˆá áŠ á‰ áˆ  áŠ¨áŒá‰¥áˆ áŠáƒ_2

Any help?

Have a look at the Transliteration module. Here is a quote from its project page:

Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

Here is a sample of what this module does for "file names":


ajax update block on click to link I am using jQuery Ajax Load module in my site to load some contents from url to show on specific div which has a required class. With this module I am able to fetch the Page content from URL through ajax & displays on specific block. I need to replace the blocks when click on the link. for-example I have a block A displayed on content area, also I have block B & C which are hidden for now. when I click on link B the block A should be replaced with block B & so on using AJAX.
Please help me?
Thanks

What have you already tried?
Having a look at the module JS, there is a function jquery_ajax_load_load(el, target, url). Have you tried calling it?

EDIT
To load block content you could either use another module specifically for it (search "drupal block ajax load") (ajax blocks) or you could create your own module that just returns block content when navigating to a url. This should be quite easy by implementing hook_menu and returning the value returned by block_load()


How do I use arguments with the Path Breadcrumb module? I am using the Path Breadcrumbs module to create breadcrumbs. I don't fully understand how to use arguments and selection rules, and thus I'm not sure how to create the following breadcrumb:

On the gallery node page (/gallery/%node), I want to use home > events >[event-name] > schedule as breadcrumbs.

Every Event node contains a node reference to a gallery node. I am trying to add this event name to the breadcrumbs. I already have retrieved the event name from $variables, following  How do I retrieve node data for a referenced node in a template file?

As an last option you can implement theme_breadcrumb() in your theme template.php

Something like below sample code.

function themename_breadcrumb($variables) {
  if (arg(0) == "galery" && is_numeric(arg(1))) {

    // Get event title of the  event
    $event_nids = mymodulename_get_back_refernce_value(arg(1));

    // Note since a gallery can be referred by multiple event nodes so you have add logic which one you need to pick here, for now I am picking with array index as 0
    $event_node = node_load($events_nids[0]);

    $links[0] = l(t('Home'), '<front>');

   // inplace of 'events' add internal link path to events page.
    $links[1] = l(t('Events'),'events');
    $links[2] = l(t($event_node->title),'node/'.$event_node->nid);
    $links[3] = t('schedule');
    drupal_set_breadcrumb($links);
  }
}


Heartbeat module comments collapsed by default I set my user's profiles with Heartbeat. At first moment they just look fine but when I open the web to the private beta I realized that when users started to comment nodes, the heartbeat logs of their profiles began to show too much information, they started to look overcrowded. So I have been asking to implement an option to the module core to show the log comments collapsed by default but none has replied.

There is another thread (Display a comment link instead of all the textareas.) on Drupal forums referring to something similar but I don't know how to use that information because I'm a rookie in Drupal hooking & custom modules writing.

Hint: maybe using this code (default option when clicking on Heartbeat comment count)

javascript:Drupal.heartbeat.comments.toggleComments(this, COMMENT_NUMBER); return false;

In this case you can use Collapsible Comment module. This module will help you to collapse the threads of the comments.

Now if you want to collapse entire comment region in collapsible form then you can do this using javascript.

Create a js file and add below javascript in a js file and add it to your theme or module.

(function($) {$(function() {
      var $comments = $('#comments');
      if (!$comments.size()) return;
      var count = $comments.find('.comment').size();
      // if (!count) return; // Do nothing when there is no comment.
      var label = Drupal.formatPlural(count, '1 comment', '@count comments');
      var $legend = $(document.createElement('legend')).html('' + label + '');
      var fsetclass = 'comments collapsible' + (location.href.search(/#(comment|new)/) == -1 ? ' collapsed' : '');
      var $fset = $(document.createElement('fieldset')).addClass(fsetclass);
      var $fsetwrap = $(document.createElement('div')).addClass('fieldset-wrapper');
      $fset.insertBefore($comments).append($legend).append($fsetwrap);
      $fsetwrap.append($comments);
      var attach = function() {Drupal.behaviors.collapse.attach($fset.parent(), Drupal.settings);};
      Drupal.behaviors.collapse ? attach() : $.getScript(Drupal.settings.basePath + 'misc/collapse.js', attach);
    });})(jQuery);

The above code will help you to collapse comments. Enjoy!!! :-)


How to wildcard cache clear in Drupal 8? In Drupal 7, we used to be able to do this:

cache_clear_all('state:', 'cache', TRUE)

which would delete any cache bin entires that started with the string state: (matching cache IDs such as state:info and state:nebraska).

The change record at https://www.drupal.org/node/1272696 even notes this use case in the Drupal 7 example, but does not actually provide an example of how to replicate it in D8.

It seems that we're supposed to use cache tags, which seems like a more more expensive conversion considering the simple use case. I don't see any matching methods that would apply in CacheBackendInterface. Note, this is not about deleting all items in a cache bin, which is clearly covered by deleteAll().

Not sure why the existing answer was deleted, it was (almost) correct.

Wildcard cache clears was removed. It was extremely complicated to support in backends like redis and memcache, which have no wildcard support.

Cache tags is the replacement and it is not that complicated to use. You just pass along a list of strings as the 4th argument (a bit annoying that you have to set the default timestamp argument, a separate method would be nice):

\Drupal::cache('default')->set('state:info', $your_data, Cache::PERMANENT,
['state']);

and then call:

\Drupal\Core\Cache\Cache::invalidateTags(array('state'));


Pass an argument to a Rules Action using VBO If I create a Rules Action to set the value of a CCK field, and point to that action from VBO, is there a way to add user inputs to the VBO form on the views page to pass parameters to the Rules Action?

I would prefer a way to do this through GUI if possible.

Explaining how to create Rule that accept arguments (user can enter any value) and adding VBO field in Views: The Power of Rules with Views Bulk Operations (and Commerce)

From Joren comment:

 function modulename_form_views_form_test_view_page_alter(&$form, $form_state, $form_id) {
    $form['#submit'][] = 'modulename_vbo_submit';
    $form['select']['arg'] = array( '#type' => 'textfield', '#title' => t('Whatever') );
 }
 function modulename_vbo_submit(&$form, $form_state) {
   $nids = $form_state['selection'];
   foreach ($nids as $nid) {
     $node = node_load($nid);
     rules_invoke_component('rules_test', $node, $form_state['values']['arg']);
     drupal_goto('test-view');
   }
 }


Architecture for login in. Accessing Drupal serivces from a phonegap mobile app I want admins login in a drupal website to create nodes that are specific to clients.
And clients login in using a mobile app to retrieve the node's info.

I'm not a 100% sure of the best architecture practice for this. Any suggestions or tutorials?

For the website, I've got Drupal 7 with services 3 using Rest and I'm creating some nodes.
I've got the Oath module set up but using session could be easier.

For the app, I followed the phonegap tutorial until it showed the phonegap hello word, then I just started modifying index.html.

PS:JQuery's AJAX Post probably not a good idea because the requests can not successfully retrieve data from a different domain, subdomain, or protocol.

PSS: If it's possible, maybe I should include Drupal for the mobile part too instead of just the website that creates the services. This way I can use drupal_http_request

PSSS: Looks like I could use php's curl but would it work with a simple phonegap env

You are right to be using services.

I guess you've got this bit but i'll write it all the same: You need to obtain an anonymous user session via services and then use those details in the user login call.

Re the not being able to access across domains, its not jquery but actually the browser stopping this on your computer. But when you are using the webview component in your app it won't stop it.

Sounds like you are on the right track, just crack as your main problem shouldnt occur :)

Edit: On reflection maybe that isnt totally helpfull

You could consider using Sencha Touch for this purpose. http://www.sencha.com/products/touch/

It kind of pitches itself as something you could use instead of native code, but ibuilt some pretty chunky ipad stuff on it and it begun to chug. Don't expect all transitions to be as smooth etc.

However, it does give you some great data/store tools

Sencha 2 is just about out
check the documentation for the rest proxy
http://docs.sencha.com/touch/2-0/#!/api/Ext.data.RestProxy

this would make handling lists and viewing content very easy

a good example from sencha 1.1 is http://dev.sencha.com/deploy/touch/examples/oreilly/ as it shows how you might extend a 'panel' to be a node view equivalent for the webapp. The syntax will be different in 2.0 but its a good way of thinking

I'm beginning to ramble now. Take a look and i'll dig out some code snippets if you choose it


How to redirect a newly registered user to a custom URL after signing up? By default after a new user signs up, a redirect to the home page happens.

But in such case I want to redirect such user to another page like node/35.

In this node/35 I then want to display some content.

Consider using the Rules module to do this.

Here is how such (fairly basic) rule would look like, based on your extra comment in my answer (= new users that register do NOT need admin approval):

Event: After saving a new user account.
Condition: None
Action: Page redirect (with value = Node/35 in your case).

The above is just a basic rule. You might want to enhance it in various ways. E.g. add a 2nd action to the very same rule to just set a special welcome message (near the top of the main content of your pages).


how to automatically fill in an entity reference field using rules in Drupal 7? Since I'm not a coder I'm using the Rules module to automatically create a node of type B when a user creates a node of type A. That works. I used 'create new entity' of 'type B' 'after saving new content of type A'. It also sets a unique name for the title of the newly dynamically created entity. And that's works great. In addition, I've also set the author of the 'entity-created' to a 'generic author' by simply using a specific uid (I just used a specific number as the value so they will always have the same author, that's fine).

So this all works.
In my next step of actions I want to fill in the entity reference field in the node created of content type A with the title of the 'entity-created' of type B. And here's where I'm stuck.

I tried:
set data value: node:field-entityref:title
new value for the specified data: [entity-created:title] (that should be different from the [node-created:title])
But that doesn't work. I tried many different things as well but it seems that I can't grab that title of that new entity that was dynamically created by Rules.
I tried to 'fetch entity by property' but that also doesn't fill in the title in my entity reference field on the node of type A. I don't know why. I hope someone can help me out in my last step. Cheers!

All is well. It works. (finally) I had to recreate my sandbox site and it worked. I installed only the necessary modules.
So beneath the steps in my rule.

After saving new content of type 'story'
Create a new entity
Parameter: Entity type: Node, Content type: article, Title: article related to nid..., Author: 2
Provides variables: Created article (article_created)
Save entity
Parameter: Entity: [article-created], Force saving immediately: true
Set a data value
Parameter: Data: [node:field-myref], Value: [article-created]

(if I didn't have the action 'save entity' it would override the node that was originally used as the default setting in the reference field on the management of the story content type, just so you'd know)

So what was the problem?
I'm not sure, it was probably a conflict with a certain module. I was thinking of the 'clone module'.


Generating URL to taxonomy term (tag) I am trying to insert tag url and page title in breadcrumb path. With page title everything is Ok, however I can't find any info how to get tags, or how to generate url for them. I think I am getting tag how I am supposed to, but this returns object of Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem without id (?). So How could I gennerate Url from this object?

function theme_preprocess_breadcrumb(&$vars) {
  $node = \Drupal::request()->attributes->get('node');
  $title = $node->getTitle();

  $tag = $node->field_tags->first();

  $vars['breadcrumb'][] = [
      'text' => $title
  ];
}

Yes, I agree with Ivan.

Here is a blog post that recommends creating a new breadcrumb builder service. https://www.palantir.net/blog/d8ftw-breadcrumbs-work

The key pieces are extending BreadcrumbBuilderBase and defining the service in a yml file.

 # mymodule.services.yml
 services:   mymodule.breadcrumb:
   class: Drupal\mymodule\NewsBreadcrumbBuilder
   tags:
     - { name: breadcrumb_builder, priority: 100 }

While data can be manipulated in the preprocess layer it should be used for visual changes rather than behavioral changes.

Now to answer your more direct question of how to actually generate the links. I think what you want is something like

$node->field_tags->referencedEntities()[0]->id();

I recommend looking at BookBreadcrumbBuilder both for the Breadcrumb specific parts and the link construction. There you'll see links constructed like this:

$links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', array('node' => $parent_book->id()));


What API function do I use for redirecting to external URLs? When writing a module, for redirecting to Drupal paths, one uses drupal_goto.

Is there some API function that I should use for redirecting to external pages?
Or is setting the Location with drupal_set_header the way to go?

PS I have to do some processing on the request; mod_rewrite/mod_alias on Apache-level or the Drupal Path redirect module, don't solve my problem.

You should use drupal_goto() for internal and external redirections.

Use 'external' option for external redirections:

drupal_goto($url, array('external' => TRUE));

  drupal_goto($path = '', array $options = array(), $http_response_code
  = 302)

$options: (optional) An associative array of additional options, with the following elements:

'query': An array of query key/value-pairs (without any URL-encoding) to
append to the URL.
'fragment': A fragment identifier (named anchor) to append to the URL.
Do not include the leading '#' character.
'absolute': Defaults to FALSE. Whether to force the output to be an
absolute link (beginning with http:). Useful for links that will be
displayed outside the site, such as in an RSS feed.
'alias': Defaults to FALSE. Whether the given path is a URL alias
already.
'external': Whether the given path is an external URL.
'language': An optional language object. If the path being linked to is
internal to the site, $options['language'] is used to look up the alias
for the URL. If $options['language'] is omitted, the global $language_url
will be used.
'https': Whether this URL should point to a secure location. If not
defined, the current scheme is used, so the user stays on HTTP or HTTPS
respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
only be enforced when the variable 'https' is set to TRUE.
'base_url': Only used internally, to modify the base URL when a language
dependent URL requires so.
'prefix': Only used internally, to modify the path when a language
dependent URL requires so.
'script': The script filename in Drupal's root directory to use when
clean URLs are disabled, such as 'index.php'. Defaults to an empty
string, as most modern web servers automatically find 'index.php'. If
clean URLs are disabled, the value of $path is appended as query
parameter 'q' to $options['script'] in the returned URL. When deploying
Drupal on a web server that cannot be configured to automatically find
index.php, then hook_url_outbound_alter() can be implemented to force
this value to 'index.php'.
'entity_type': The entity type of the object that called url(). Only
set if url() is invoked by entity_uri().
'entity': The entity object (such as a node) for which the URL is being
generated. Only set if url() is invoked by entity_uri().

$http_response_code: (optional) The HTTP status code to use for the redirection, defaults to 302. The valid values for 3xx redirection status codes are defined in RFC 2616 and the draft for the new HTTP status codes:

301: Moved Permanently (the recommended value for most redirects).

302: Found (default in Drupal and PHP, sometimes used for spamming search engines).

303: See Other.

304: Not Modified.

305: Use Proxy.

307: Temporary Redirect.

Drupal 8

Drupal 8 has removed drupal_goto function, for redirect to external URL see this answer for the question: How do I redirect to an external URL?.


How to alter a custom text field in a block with AJAX We have a block on a basic form listing several items and each item has a number of PDF files on the server to show by a users request.
Each item has an Id (nnn) which is displayed in a text field wrapped as
item nnn

the object is when a user clicks the link, the div should be replaced by a list showing the links to the corresponding PDF files to download.
There are lots of Ajax examples that create their own form, but none so far that comes close to our application in replacing a div in a block.  We could do the Ajax request in a direct way but prefer to use the Drupal api's for stability and manageability, the only question remains is how to..  so examples or ideas are appreciated.

You have some examples in "Examples for Developers" https://www.drupal.org/project/examples

If you see in ajax_example module, you have "Ajax Link" which points to the url ajax_link_callback,  (defined by  menu hook ajax_link_callback in file ajax_example.module, line 181).
This menu hook has a callback function (see file ajax_example_misc.inc, line 102), which does the magic.

You can see that the ajax response is made with a few components. First the $commands array with the target div and the content to output. Then this array is wrapped in another array ($page), and delivered by the function: ajax_deliver.

Note that the original link ( which is produced by the menu callback ajax_example_render_link() in file ajax_example_misc.inc, line 22), has a use-ajax class attribute and previously the drupal.ajax library is added to the page.


Does Entity Translation hijack i18n's operations? I'd ideally like to use i18n to handle backend translation but use entity translation to maintain multiple language versions for each content node.

Does this require a lot of extra work or lead to caveats? I'm hoping they just handle different sides of the translation puzzle.

It's not that difficult or complicated, you just need to know what to do, where and using what. Have a look at Drupal 7 Multilingual Sites book, it has pretty good explanation of the whole process. Essentially, yes, Entity Translation plus i18n modules would take care of most of the things for you.


Getting a list/array of all organic groups a user is part of I have been searching online for awhile and so far I have been unable to find any og functions that will give me an array or list of all groups a user is a member of.  Does such a function exist?  If not, is there a sql query I could run that would give me this?

Assuming you are using Drupal 7 and latest OG you can use og_get_groups_by_user().

  Get the group IDs of all the groups a user is an approved member of.


I am learning Drupal 7 and want to know the way to learn modules I am learning Drupal 7. I have read the docs about modules.

But still want to know the correct way to learn modules eg. how to use it, how to install extended modules etc.

I think the most important is experience. Just installing and enabling some modules, trying them out gives you a feeling of how things work. There are many youtube videos that show you exactly what to do. But I can't stress this too much: experience is what we need. Don't make the same mistake as I did in the beginning when I studied more than I tried.

Don't be afraid to try things out, even if they don't seem to work in the beginning. Be persistent and follow the guidelines out there. Should you need specific advice on a module, feel free to ask here or in drupal.org where you should become a member. (if you are not already!)

I don't think there is an "officially correct way to learn". If there is, then I bet it is called persistence! So get involved and see you out in the field :D.