node_load() in a form and display it in an attached form markup How can i show every node title which is related to the taxonomy term in a form field? I work a little bit around and think i'm really close for a solution, but thats a little bit too tricky for me. I get one node title, but if i related 2 nodes to one term, i still get only one with an error message. I think i need to built an extra array, but I didn`t know how to handle it with the $link[$data->tid].

        $terms = taxonomy_get_tree('1', 0, NULL, TRUE);
        $image_style = 'medium';

        foreach ($terms as $data) {
          if(!empty($data->field_term_image['und'])) {
            $output[$data->tid] = '<img src="'.image_style_url($image_style ,$data->field_term_image['und'][0]['uri']).'" />'. $data->name;
          } else {
            $output[$data->tid] = $data->name;
          };

          $term_nids = taxonomy_select_nodes($data->tid, FALSE);
          $nodes = node_load_multiple($term_nids);

          foreach($nodes as $node){
            $link[$data->tid] = $node->title;
          };
        }

        $form['step_1']['city_default'] = array(
          '#type' => 'radios',
          '#title' => t('Default category'),
          '#options' => $output,
          '#description' => t('The selected category will be shown by default on listing pages.'),
        );

        foreach ($form['step_1']['city_default']['#options'] as $key => $city_text) {
          $form['step_1']['city_default'][$key]['#description'] = $link[$key];
        }

Glad about every help.

You could do this with entity references and the views merge rows module.. An entity reference field to the taxonomy term and an entity reference view providing the term and all related nodes.. Here's a quick example I did up on a node add form. I can give more detail tomorrow if it's what you need.


use taxonomy term for reservations how to prevent overlapping I have a drupal site where reservations are available. We use fullcalendar module to visualize the room reservations. For a reservation the user needs to add a new content. The content uses taxonomy terms as rooms. Now I'd like to achive that once the user creates a new booking content and chooses the room, when it is not available, the user should be warned. I mostly use rules and i am a bit unexperienced with drupal, now I'm trying to learn.

There are a number of ways to achieve the booking features in Drupal, try comparing here: Comparison of Booking System modules

One way that comes to mind for your specific case is using Flag module because you can set a Flag to be global, once an entity is marked as "occupied" that status is valid across the site. It's well integrated with Views and Rules, so you could probably do a lot there.

Another way might be to use Views Entity reference display for the Field widget when the user is creating a reservation. The Views would make sure to exclude all the terms for the Vocabulary that are already being used, so only "free" terms would show up when creating a new booking.


Checkout settings are ignored I have configurations on store>configuration>completion messages. But they are not reflecting on the site. For example I have set the checkout page as a node I created but it's still using the default checkout page. I have cleared all the cache. What am I missing?

AFAIK the checkout page is dynamically generated by Ubercart, you cannot create a node for it. You can theme the dynamically generated page or alter it through custom modules if needed, see several very helpful Ubercart tutorials here: https://drupal.org/project/ubercart


how to create a taxonomy Views combining terms from 2 different vocabulary I have content types tagged from two different vocabularies (destination and category).

i.e. destination (main vocabulary, content must be tagged with of one of them)
- dest1
- dest2
- dest3
- dest4

category (content is tagged with at least 1 but could be more)
- cat1
-- subcat1.1
-- subcat1.2
- cat2
-- subcat2.1
-- subcat2.2

How can I create a view from these 2 different vocabularies?

i.e. dest1(term)/category(voc)/cat1(term)/subcat1.1(term)

By default, Views Taxonomy page allows you to select multiple terms.  If you click on the Contextual Filter "Content: Has taxonomy term ID (with depth)", one of the first choices you see is whether to allow multiple values.
Let's say that these categories have the following term IDs:

Destination Vocab:

dest1 [25],
dest2 [26],
dest3 [27],
dest4 [28]

Category Vocab:

cat1 [35]
-- subcat1.1 [37]
-- subcat1.2 [38]
cat2 [36]
-- subcat2.1 [39]
-- subcat2.2 [40]

If you want a page to show you all items in category 2 for destination 3, you'd have a url like this:  http://www.example.com/taxonomy/term/27+36.
To limit the allowed Vocabularies, open that same Contextual Filter "Content: Has taxonomy term ID (with depth)" and scroll down to the section "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED".  There is a validation section where you can check off the vocabularies that you want included:

taxonomy validation http://www.emijayne.com/sites/default/files/linked/taxonomy.jpg


Body field is not displayed in Comment Views I have a comments listing view. When I make the the row style as comments everything is displaying fine. But when I make the row style as fields and add the comment:comment field to the list, the comment body is not showing up.

Things I have checked

There is no field access for this field.
The field is using the default template, so it is not being overridden.
Checked the body field display settings, it is configured to show and format plain text is enabled.
I am previewing the view as admin so there should be no access concerns as well.
The view is showing other fields normally.
"Exclude this display" box unchecked.
Changed the theme to Bartik and also disabled the javascript to be double sure.
Comment related modules I have are ajax-comments and onecomment module. I disabled both, rebuilt permissions and cleared the cache :)

Well.. at this point you may have to resort to the following.

First of all, make a backup of your database.

Plan A) Disable views and uninstall it (so all the database tables are erased), then delete the views folder. Download it again, upload the folder and enable it. If this fixes your problem, you can use the view's export/import to quickly import all the view's you had.

Plan B) Disable every module you have in sites/all/modules folder except for Views. Then if it works now, enable them one by one to see which one is causing this.

Plan C) If A or B doesn't work, well... I hate to say it, reinstall Drupal :(


How can I show selected items without exposed filters? I have a views which contains block and page view with exposed filter with my categories/taxonomy.

This is a beginner page for my users, so I just want to Show some items before they apply any filter.
For this issue; I can add a checkbox to my content-type 'this is important'

Examples:
3 node added: 1,2,3. Node2 is important and needs to Show it without applying filters or like that. If a filter applyed, other node1 and 3 will be shown.

I'm using Drupal7 and latest version of Views, CCK etc.
Best regards.

Alternatively can you use "Promoted to front page" under "Publishing options" while adding content. This content will be the contents you need as important and will be visible to users.

Below that your view with exposed filter will be shown.
In View "Filter criteria" you can ADD "Content: Promoted to front page" option to show the non promoted contents, and also exposed filters.

You can apply this logic in your content type also, if you need specific fields such as "Mark as Important", give it some Boolean value and select it in filter criteria as mentioned above. If not can be added from "Contextual filters".


Separate classes in include file not loading? I have a peculiar problem... I'm trying to simplify my module by breaking up a ton of code into classes, and I have all of the classes in a separate include file that I'm registering in my .info file with the files[] directive.

However, when I go to use these classes in my module code, PHP dies.  It's like they're not being loaded.  I thought they were supposed to autoload at first use since I was using files[]?

module.info

name = Module
description = Module description
package = Module Package
core = 7.x

scripts[] = my_module.js
files[] = includes/my_module.class.inc

The files listed in files[] do get autoloaded, but Drupal's registry needs to "find about" about them first. The .info files aren't parsed & processed on every page load, but rather only during specific system operations. Go to the /admin/config/development/performance page on your site and clear the cache - this will rebuild the registry and your files should then get loaded as necessary.


Is there a way to add terms for the Spell Checker in editor to reference? There are unique terms related to the industry that the spell checker might flag as incorrect.

We are looking for a solution for the client team to add the unique terms so they are not flagged as incorrect when spelt correctly and suggest this term for when it is spelt incorrectly.

Please help.

Checkout the following modules:

Wysiwyg SpellCheck

  Wysiwyg SpellCheck module is a plugin for wysiwyg editor that enables TinyMCE spellchecker plugin.

Spell Checker

  This module supports spell checking of node content (including title, body and CCK fields).

Image from project page.


'Notify user of new account' checkbox to be selected as default What I am trying to do is have the 'Notify user of new account' checkbox selected as default when creating a new account.

I have been trying similar steps as to http://drupal.org/node/1059168 but the solution posted in the comments is for D7, I need it for D6.

Any ideas, on how I could change this code for D7

<?php

/* Hook form alter
 * Sets "notify user of new account" chosen by default
 */
 function YOURMODULE_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'user_register_form') {
     $form['account']['notify']['#default_value'] = TRUE;
  }
}
?>

to have it work with D6?

Or any helpful links I mat have missed would be greatly appreciated.

found here - http://drupal.org/node/1295268#comment-5060488

<?php
function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
    if ($form_id == 'user_register') {
        $form['account']['notify']['#default_value'] = TRUE;
    }
}
?>


When two rules attempt a page redirect, which will actually happen? I have a rule set up that redirects the user to a specific page after they edit a node.  I  have another rule that changes the value in a node, then redirects to a different page.  My problem: because the second rule makes a change to a node, the first rule is triggered and the user is sent to the first rule's URL (instead of the second rule's URL.)

When two or more URL redirects are triggered by rules, which one is performed?
Does this change if a rule is triggered within another rule?
How can I fix my problem?

try changing the order (weight) of each rule under its settings:

Weight

Order rules that react on the same event. Rules with a higher weight are evaluated after rules with less weight.

EDIT:
it's a little convoluted, but you could create a temporary variable within the node to control things - for example, a hidden boolean field or flag that is changed to true when editing - the rule checks for this as a Data Comparison in a condition. Have the change field and redirect Rule set the boolean but not redirect, then create two rules on save - one if the field is set, and one if the field is not. For the rule if the field is set, then add an action that resets the fields value.


Allow shipping that is calculated using a base rate plus a rate per item? I figured this would be built in, but it seems it is not. See here:

I have two options:

Flat rate: I can make it 9.99 USD, but then if it's 100 items, it's still 9.99 USD.
I can make it 1 USD per item, but I als don't want that.

What I want is a base rate of 10 USD, and then 1 USD per item after that. Anyone know how to do that?
UPDATE
There is some information available for Commerce 1.0 here, but hardly any information on Commerce 2. This is basically all there is.
Can it be that Commerce 2 doesn't support this? I mean, nowhere can I see "shipping rules" or anything related to that that allows me to set up these rules?
(I miss UberCart)

Programmatically create your own custom shipping method in a custom module.
Example, custom module called "mymodule":
/modules/custom/mymodule/src/Plugin/Commerce/ShippingMethod/CustomRate.php
<?php

namespace Drupal\mymodule\Plugin\Commerce\ShippingMethod;

use Drupal\commerce_shipping\Plugin\Commerce\ShippingMethod\ShippingMethodBase;
use Drupal\commerce_price\Price;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\commerce_shipping\PackageTypeManagerInterface;
use Drupal\commerce_shipping\ShippingRate;
use Drupal\commerce_shipping\ShippingService;
use Drupal\Core\Form\FormStateInterface;
use Drupal\state_machine\WorkflowManagerInterface;

/**
 * Provides the FlatRatePerItem shipping method.
 *
 * @CommerceShippingMethod(
 *   id = "custom_rate",
 *   label = @Translation("Custom Rate"),
 * )
 */
class CustomRate extends ShippingMethodBase {

  /**
   * Constructs a new FlatRate object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\commerce_shipping\PackageTypeManagerInterface $package_type_manager
   *   The package type manager.
   * @param \Drupal\state_machine\WorkflowManagerInterface $workflow_manager
   *   The workflow manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, PackageTypeManagerInterface $package_type_manager, WorkflowManagerInterface $workflow_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $package_type_manager, $workflow_manager);

    $this->services['default'] = new ShippingService('default', $this->configuration['rate_label']);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
        'rate_label' => '',
        'rate_description' => '',
        'rate_amount' => NULL,
        'services' => ['default'],
      ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);

    $amount = $this->configuration['rate_amount'];
    // A bug in the plugin_select form element causes $amount to be incomplete.
    if (isset($amount) && !isset($amount['number'], $amount['currency_code'])) {
      $amount = NULL;
    }
    // A bug in the plugin_select form element causes $base_amount to be undefined.
    if (!empty($this->configuration['base_amount'])) {
      $base_amount = $this->configuration['base_amount'];
    }
    else {
      $base_amount = null;
    }

    $form['rate_label'] = [
      '#type' => 'textfield',
      '#title' => t('Rate label'),
      '#description' => t('Shown to customers when selecting the rate.'),
      '#default_value' => $this->configuration['rate_label'],
      '#required' => TRUE,
    ];
    $form['rate_description'] = [
      '#type' => 'textfield',
      '#title' => t('Rate description'),
      '#description' => t('Provides additional details about the rate to the customer.'),
      '#default_value' => $this->configuration['rate_description'],
    ];
    $form['base_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Base amount'),
      '#default_value' => $base_amount,
      '#required' => TRUE,
      '#description' => t('Charged once.'),
    ];
    $form['rate_amount'] = [
      '#type' => 'commerce_price',
      '#title' => t('Rate amount'),
      '#default_value' => $amount,
      '#required' => TRUE,
      '#description' => t('Charged for each quantity of each shipment item.'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);

    if (!$form_state->getErrors()) {
      $values = $form_state->getValue($form['#parents']);
      $this->configuration['rate_label'] = $values['rate_label'];
      $this->configuration['rate_description'] = $values['rate_description'];
      $this->configuration['base_amount'] = $values['base_amount'];
      $this->configuration['rate_amount'] = $values['rate_amount'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateRates(ShipmentInterface $shipment) {
    $base_amount = Price::fromArray($this->configuration['base_amount']); // create base price
    $amount = Price::fromArray($this->configuration['rate_amount']);
    $quantity = $shipment->getTotalQuantity();
    $ship_price = $amount->multiply($quantity);
    $ship_price = $ship_price->add($base_amount); // add base
    $rates = [];
    $rates[] = new ShippingRate([
      'shipping_method_id' => $this->parentEntity->id(),
      'service' => $this->services['default'],
      'amount' => $ship_price,
    ]);

    return $rates;
  }

}

Result


Change max length of link field link text In order to modify the length of a file field description field I put the following line in settings.php:

$config['file.settings']['description']['length'] = 512;

Now I want to do the same for the link field. How can I change the max length of the link text (without patching the module)?

I think the problem is that FileWidget.php gets the length from the configuration

'#maxlength' => $config->get('description.length')

whereas it is hardcoded in LinkWidget.php:

'#maxlength' => 255

If you go for module then you can check Maxlength module.

  Maxlength allows you to set maximum length of any field on any form
  making use of the form API. This includes fields created using the UI.
  (Example: any text field on a node)


Pressflow caching directives I have a setup with Varnish. Varnish decides when to clear the cache for a page according to the PHP headers. I want to force Varnish to regenerate the cache for each node every time it gets updated by an user. I am looking for the best place to do this. Ideally it would be in a Drupal/pressflow hook (if there is any available) implemented in a custom module.

What HTTP caching directives Pressflow sets?
In what function, file and line number?

Answers that don't address those two bullet points will be appreciated, but not accepted.

The varnish module handles clearing the cache for you when a node is update via a socket connection to varnish. It can also be configure to clear the cache based on a lifetime period. If you still need to clear the cache based on your own custom requirements the module also provides a helper function such as _varnish_terminal_run that allows you to send commands to varnish from your php code.

Also in regard to the bullet point checkout the drupal_page_cache_header_external in pressflows bootstrap.inc file

There is also more documentation of varnish with pressflow over at fourkitchens wiki


Using drush up with --gitinfofile I tried to manage drupal modules with the --package_handler=git_drupalorg which needed me to add the --gitinfofile option. Using drush dl this works but if I try to update my modules with drush up the version information is the same as of the drush dl version.
Is there a fix for this or a guide which explains how to use drush with the git version control system.
I am using the drush 6.2.0 version.

Update: As mentioned in the comments below, the actual answer here is that the git deploy module is required for --package-handler=git_drupalorg to work correctly.

If you just want to track the latest HEAD from some branch of some module, then you can use drush dl with --package-handler=git_drupalorg to download the file, and use git pull when you want to update your code.

drush pm-updatecode is best used in instances where you wish to track the latest stable release of the module.


How to send an eMail to registered users after they are invited using the Group module? I use the Group module and the "Ginvite" submodule on Drupal 7.52.

The module allows you to invite people (either registered users or users without an account) to become a member of the group that the invitation is about.

This is what happens after somebody is invited:

When I write an email in "Invitations by email" and the person is not registered on my site, then the person receives an email invitation.
when I write an email in "Invitations by email" and the person is already registered on my site, then the person receives an invitation message on the user's account, as shown in this screenprint:

However, I want people who already have a user account, to receive an email notification about that invitation in addition to the invitation (message) on their user account.

How to do this?

You can use the Rules module to achieve that "people who already have a user account, also receive an email invitation in addition to the invitation on their user account" (as in your question).

Here is the rule (in Rules export format) to actually do so:

{ "rules_send_email_after_inviting_a_registered_user" : {
    "LABEL" : "Send eMail after inviting a registered user",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "group" ],
    "ON" : { "group_membership_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "group-membership:status" ], "value" : "invited" } },
      { "NOT user_has_role" : {
          "account" : [ "group-membership:user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[group-membership:user:mail]",
          "subject" : "You have a pending group invitation",
          "message" : "Hi there!\r\n\r\n[site:current-user:name] has invited you to become a member of the group \u0022[group-membership:group]\u0022 on [site:name].\r\nIf you wish to accept the invitation, you need to login with your existing account first, which is \u0022[group-membership:user:name]\u0022.\r\nPlease visit the following address in order to do so: [site:login-url]\r\n\r\nKind regards,\r\nThe [site:name] team",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      },
      { "drupal_message" : { "message" : "You just invited existing user with name [group-membership:user:name] and eMail Id [group-membership:user:mail] to the group named [group-membership:group].\r\n\r\nAn appropriate message about this invitation just got eMailed to [group-membership:user:name] also." } }
    ]
  }
}

Some more details about the magic included in this rule:

Sending an invitation in the Group module's terminology is equivalent to inserting a new Group Membership with status "invited" (how easy can it be?). So that explains the Rules Event I'm using, and the first Rules Condition.
Since we only want to send such eMail to users who already have an account, the 2nd Rules Condition is to check that the invited user does NOT (!!!) have role anonymous.
The Rules Action is just to send an appropriate eMail, using specific tokens related to the Group Membership, etc.
For debugging purposes, the 2nd Rules Action shows a confirmation message about the triggered eMail (feel free to remove that action if you don't like it).

Just import the above rule (using the Rules UI) in your own site, with no customization (changes) needed to see it at work in your own site (don't worry, there is no spyware in the eMail being produced ...).

The eMail content is pretty close to the eMail delivered when inviting anonymous users (the only difference is that it has an instruction to login with their existing account, also included in the eMail body). Here is how a sample eMail body looks like:

Hi there!

Pierre.Vriens has invited you to become a member of the group
"Drupal for Sitebuilders" on www.example.com.

If you wish to accept the invitation, you need to login with your existing
account first, which is "Dries.Buytaert".

Please visit the following address in order to do so:
http://www.example.com/user

Kind regards,
The www.example.com team

Possibly you may want to finetune the eMail subject, or eMail body. But apart from that no other changes should be needed.

Voilà ...


Varnish doesn't cache first hit at all, only second hit I have Varnish 4 with Drupal 7. In Drupal settings.php I have:

// Tell Drupal it's behind a proxy.
$conf['reverse_proxy'] = TRUE;

// Tell Drupal what addresses the proxy server(s) use.
$conf['reverse_proxy_addresses'] = array('127.0.0.1');

// Bypass Drupal bootstrap for anonymous users so that
// Drupal sets max-age &lt; 0.
$conf['page_cache_invoke_hooks'] = FALSE;

// Make sure that page cache is enabled.
$conf['cache'] = 1;
$conf['cache_lifetime'] = 0;
// Set page cache max-age to 600 secs (10 min)
// Change this to the highest time possible for your needs
// Drupal will set a Cache-Control: "max-age=600" header
$conf['page_cache_maximum_age'] = 21600;

$conf['cache_backends'] = array('sites/all/modules/varnish/varnish.cache.inc');

$conf['cache_class_cache_page'] = 'VarnishCache';

In the varnish vcl file I have:

vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

sub vcl_recv {
    # Happens before we check if we have this in cache already.
    #
    # Typically you clean up the request here, removing cookies you don't need,
    # rewriting the request, etc.

 ## ADMIN PAGES ##

    # Here we filter out all URLs containing Drupal administrative sections
    if (req.url ~ "^/status\.php$" ||
        req.url ~ "^/update\.php$" ||
        req.url ~ "^/admin$" ||
        req.url ~ "^/admin/.*$" ||
        req.url ~ "^/user$" ||
        req.url ~ "^/user/.*$" ||
        req.url ~ "^/flag/.*$" ||
        req.url ~ "^.*/ajax/.*$" ||
        req.url ~ "^.*/ahah/.*$") {
           return (pass);
    }
}
sub vcl_backend_response {
    # Happens after we have read the response headers from the backend.
    #
    # Here you clean the response headers, removing silly Set-Cookie headers
    # and other mistakes your backend does.
if (bereq.url ~ "(?i)\.(css|js|jpg|jpeg|gif|png|ico)(\?.*)?$") {
        unset beresp.http.set-cookie;
    }
# Set cached objects to expire after 1 hour instead of the default 120 seconds.
    set beresp.ttl = 4h;
}

sub vcl_deliver {
    # Happens when we have all the pieces we need, and are about to send the
    # response to the client.
    #
    # You can do accounting or modifying the final object here.
if (obj.hits > 0) {
               set resp.http.X-Cache = "HIT";
        } else {
               set resp.http.X-Cache = "MISS";
        }
}

This is my header at isvarnishworking:

HTTP/1.1 200 OK
Date:   Fri, 02 Mar 2018 13:51:24 GMT
Content-Type:   text/html; charset=utf-8
Connection: keep-alive
Set-Cookie: __cfduid=dfac4e840061f192552b77dfd3430fcfc1519998683; expires=Sat, 02-Mar-19 13:51:23 GMT; path=/; domain=.mydomain.net; HttpOnly
X-Powered-By:   PHP/5.4.45
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control:  max-age=64800, public
X-Content-Type-Options: nosniff
Content-Language:   en
X-Frame-Options:    SAMEORIGIN
X-Generator:    Drupal 7 (http://drupal.org)
Vary:   Accept-Encoding,User-Agent
X-Varnish:  459087
Age:    0
Via:    1.1 varnish-v4
X-Cache:    MISS
Server: cloudflare
CF-RAY: 3f54567d343346ec-EWR
Content-Encoding:   gzip

I'm using Cloudflare, but I've already been try to shutdown Cloudflare for 2-3 days. Still, Varnish doesn't hit the first time, only the second time.

It looks like a normal behaviour :

first url hit : Varnish puts the page in cache with some id
only following hits will serve the cached id instead of querying the backend.

If you want anonymous users to be always served by varnish, you need to implement a cache warmer logic.

Setup a sitemap. Then create a cron task that will parse the sitemap with curl for instance,  and run that cron task at a frequency synced with your cache expiry time...


PHP code for Block visibility by Vocabulary ID I need to show a block for terms of a certain vocabulery. Drupal.org has this snippit for Drupal 6, but I cant find anything for Drupal 7.

http://drupal.org/node/69076

Im looking at PHP in the block visibility settings as Im assuming its the best way, but id be happy with any other solution. Thanks

If you want to do this on the term pages you should be able to use this code from Drupal.org. Just replace the function call taxonomy_get_term with taxonomy_term_load.

The code is copied below:

 <?php
  $desired_vocab = 1; // put here the vocabulary ID you're interested in

  if ( ((arg(0) == 'taxonomy')
    && (arg(1) == 'term')
    && is_numeric(arg(2))
    && ($term = taxonomy_term_load(arg(2)))
    && ($term->vid == $desired_vocab )) ) {
      return TRUE;
  }
?>


How to use feeds tamper to set default value from importer node? I've got a number of feeds that I want to be able to import regularly. I setup feeds and attached them to a content type, ex. "My Feeds" which imports into another content type, "Article".

I also need to make sure that when these feeds come in, that I can set the default values in the target node. The use case is that I will be importing from feeds in multiple languages and want them associated with an author so I have created a couple of new fields in my importer content type:

field_language
field_author

I want to be able to set the language and author value for each feed when I create the importer and have those associated every time I update but its not clear if any of the existing plugins do this.

I've also started writing my own custom plugin to pull in these values from the parent importer but I can't figure out how to access or load the importer object through a feeds tamper plugin.

Any pointers or is there a better way to acccomplish this task?

Currently, there doesn't appear to be any core method of achieving this, either through Feed's Tamper or core Feeds Module.

There's a patch here, but I'm still looking for a core solution.


How to use geofield migrate extras I can not understand how to use migrate_extras and for example how to use geofield migrate extra support.

I have create a Migration class that work. In my "source" I have 2 "fields" called latitudine and longitudine. I have follow the instruction that I have found in geofiled.inc:

$geo_arguments = array(
  'lat' => array('source_field' => 'latitudine'),
  'lon' => array('source_field' => 'longitudine'),
);
// The geometry type should be passed in as the primary value.
$this->addFieldMapping('field_coordinate', 'Point')->arguments($geo_arguments);
// Since the excerpt is mapped via an argument, add a null mapping so it's
// not flagged as unmapped.
$this->addFieldMapping(NULL, 'latitudine');
$this->addFieldMapping(NULL, 'longitudine');

But my "test node" is created (via migrate) without "geofileld" field (field_coordinate). But if I comment the lines above and insert this function:

public function prepare($node, stdClass $current_row) {
  $node->field_coordinate = array(LANGUAGE_NONE => array(0 => array(
    'geom' => 'POINT ('.$current_row->longitudine." ".$current_row->latitudine.')',
    'geo_type' => 'point',
    'lat' => $current_row->latitudine,
             'lon' => $current_row->longitudine,
             'left' => $current_row->longitudine,
             'top' => $current_row->latitudine,
             'right' =>$current_row->longitudine,
            'bottom' => $current_row->latitudine,
   )));
}

"geofield field" is "created".

Where is my error?

Using arguments is deprecated.

Now you can migrate geofields without migrate_extras.

$this->addFieldMapping('field_location', 'point');

And in your prepare row

public function prepareRow($row) {
 $row->point = 'POINT (' . $row->longitude . ' ' . $row->latitude. ')';
}


How to change the alias for the core forum landing page? Core forums sets the landings page to /forum. I need this changed to /another-page/forum. I know I can change the forum posts using pathauto, but I need to change the alias for the top-level forum landing page. Thoughts?

Why not just use the core path module:

http://example.com/admin/config/search/path/add


Adding panels to regions Is there a way where I can use the theme's default regions for displaying panels instead of a layout ?

or Without using page manager, Can I display panes in the sidebar ?

The Mini Panels sub-module of Panels allows you to create panels as blocks, which you could then place into any region on your site. There is an abundance of documentation, tutorials, etc. on using Panels and MiniPanels, but which resources to link you to would depend upon the version of Drupal you are using. There is an existing answer that will probably help you learn more.


Redirect for anonymus user doesn´t work from Controller Community,
i´ve got a simple COntroller for redirect my users by visiting a special path (localhost/drupal8/check). At the moment the redirect works for the administrator and for registrated user, if they are logged in, but not for the quests of my site (i know that it is only a local site).

namespace Drupal\testmodule\Controller;
use Drupal\Core\Controller\ControllerBase;

class EntityChecker extends ControllerBase {

  public function redirectToFront($bundle, $label) { return $this->redirect('<front>');

}
}

In the log i´m getting the following error:

  [30-Jul-2018 09:30:25 UTC] RuntimeException: Failed to start the
  session because headers have already been sent by
  "C:\wamp64\www\drupal8\vendor\symfony\http-foundation\Response.php" at
  line 1274. in
  C:\wamp64\www\drupal8\vendor\symfony\http-foundation\Session\Storage\NativeSessionStorage.php
  on line 141 #0
  C:\wamp64\www\drupal8\core\lib\Drupal\Core\Session\SessionManager.php(164):
  Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start()

Thanks a lot for helping me

Try this

<?php

namespace Drupal\testmodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

class EntityChecker extends ControllerBase {

  public function redirectToFront($bundle, $label) {
    $response = new RedirectResponse("/");
    $response->send();
  }

}


FieldPluginBase: How to test based on views field raw value? I know that the render method is not the right place to do conditional logic but I have no clue where I should implement my tests.

This is my render method I want to access the raw value of a field to do a test on it (conditional field):

  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }

The original_value object is returning the translation not the original string.

How can I access the original value of my field (not translated)?

For the untranslated field value get first the untranslated entity:

if ($entity = $this->getEntity($values)) {
  $untranslated_entity = $entity->getUntranslated();
  $untranslated_value = $untranslated_entity->field_example->value;
}


Mod rewrite enabled and working, urls contain index.php/ I have a strange issue: I have a drupal 8 instance on a subfolder in /var/www, I have enabled mod-rewrite in apache, I changed the apache.config file as in this post and the clean urls are working if I navigate directly to /drupal/admin for example.

I also added the RewriteBase /drupal in my .htaccess file.

The problem is that any link generated by drupal still contains the /drupal/index.php/ part and I don't know how to get rid of that /index.php part.

I worked with Drupal 7 since it was launched but I never had this problem.

Is there a setting somewhere in db or in the config file where I should 'tell' drupal to use clean urls?

My server runs Apache 2.4.7 and PHP 5.5.

Thank you.

If you didn't append /index.php to the base URL (e.g. setting $base_url to http://example.com/index.php, in the settings.php file), then the rewrite rules in the Apache configuration files are wrongly adding /index.php to your links.
Check both of them, and you should find what is causing the wrong behavior.


Menu item with update text (title) in real time I have a menu where one of the items (menu links) is a link to a view where I can see all comments that I have to moderate. Which I need is (if it is possible) to have the title of this link that change in realtime (or every time I load a page/node).

Think to my situation where I don't know how many comments I need to moderate so in this moment every X minutes I reload the page with all comments that I have to moderate. But this is frustating. So my necessity is to have a menu item like "Comments to moderate: FOO" where FOO is a number (from 0 to infinite) that I can calculate in realtime at every page load or every BAR minutes.

M.

This is how I solved a similar problem:

You need implement the hook_menu() and use the 'title callback'

function YOUR_MODULE_menu() {
    $items = array();

    $items['perfil-usuario'] = array(
        'title' => 'perfil',
        'description' => t('User Profile'),
        'title callback' => 'change_title_profile_link',
        'page callback' => 'go_to_profile',
        'access callback' => 'user_is_logged_in',
        'expanded' => TRUE,
        'weight' => 100,
        'menu_name' => 'main-menu',
        'options' => array('attributes' => array('class' => array('perfil-usuario'))),
        );

    return $items;
}

In this function you can change the link title

function change_title_profile_link() {
    return rand();
}

Here you can redirect to the desire url, if the url change you can implement this function

function go_to_profile() {
}


How to set image style for media browser in node edit form? I am using the media browser that is part of the media module to upload or select images on a node edit form.
I an image is already uploaded it is shown in the edit form in it's original size. If the image is large this makes the whole edit form unusable. Where can I set the images style, that is used for the edit form?

Once you have chosen the image and clicked save and the overlay is closed, images are display in the "Media thumbnail" image style. Did you perhaps change the settings for that image style under admin/config/media/image-styles?


Use $base_url in a computed field? Using $base_url to build a link in a computed field, I get this error:

  Notice: Undefined variable: base_url in eval() (line 1 of F:\wamp\www\mysite\sites\all\modules\computed_field\computed_field.module(468) : eval()'d code).

Is it a way to get the site base URL in a computed field?

This is a global scope variable and you can access it by using $GLOBALS['base_url'] instead or calling the core base_path() function to pull it into your computed field definition.


Add Emoticon at my Simplenews Newsletter's subject I send newsletters from my Drupal 7 website using Simplenews. What I want is to add emoticons at the subject of the newsletter, like a Smiley or something like this.
Is it possible?

If you're talking text-based emoticon (e.g. ":)", ":D") then the answer is yes. If you're talking Unicode emoji-character based emoticons (e.g. ) then the answer is maybe. While Drupal sends out UTF-8 encoded emails, support for display of the emoticons depends totally on recepient's email client so your results will vary.


How to add a notification when a relation or friends publish new content? I want like Facebook notification add icon when a user relationships or flag friends ( User Relationships or Flag Friend module) published some new content.

I followed this good tutorial who is the closest to do that : How to allow users to manage their own Message Stack messages?. It works perfectly, but only for the current user and not relationships or friends. I also found How to implement Facebook style Notifications for Organic Group posts?.

I would use not only for the current user but for user relationships like a Facebook notification. I tried many ways: using Rules, Views or custom development (the most closest with hook_node_insert and user_relationships_load } but without success.

The problem is you need to notify individually each of the friends, so that they can manage there own notifications. If not each time a friend removes a notification, it's removed for ALL friends.

I add a custom field of user that is fill by one each time a new content is publish with a custom module this is working but I not find a way to JOIN the QUERY with the relationship table or friends tables.

function my_module_node_insert($node){
if($node->type == 'mytype'){
db_update('field_data_field_my_field_name')
->expression('field_my_field_name_value', 'field_my_field_name_value +
:amount', array(':amount' => 1))
->execute();
//or you also can use regular query
//db_query("UPDATE {field_data_field_my_field_name} SET
//field_my_field_name_value = field_my_field_name_value + 1");
}
}

Here is the screen of the views of list "all friends" default views of Flag
    friends module

When it comes to Facebook type notifications, the Message module is indeed very useful. I'll give an example below of using one view's results view_with_users in another view's contextual filter my_messages_view.

For this to work, in your main messages view, you have to go into your contextual filter's settings (probably Message Author or something), then scroll to the bottom and click Allow multiple values. Instead of the usual Provide default: Current User, we will send all the friends to the view with a module.

Note: In the below example, I've sent the current user's uid to the additional view as an example, but your screenshot doesn't have that contextual filter so it's either not needed, or you may need to tweak the friends view to work programmatically.

custom_views_args.module

<?php

function custom_views_args_views_pre_view(&$view, &$display_id, &$args){
    global $user;
    // Target our Messages view
    if($view->name == 'my_messages_view') {
        // Get users from our friends view
        $friends = views_get_view_result('view_with_users', 'view_display_name', $user->uid);
        // Add each uid to array
        $friends_array = [];
            foreach($friends as $friend){
            $friends_array[] = $friend->uid;
        }
        // Add current user's uid to array as well
        $friends_array[] = $user->uid;
        // Create + separated Contextual Filter
        $messages_con_filter = implode("+", $friends_array);

        // Send the filter to the Messages view
        // $args[0] is the first filter in the list in the view
        $args[0] = $messages_con_filter;

    }
}

See this thread for more info about Facebook-style notification. There may be other useful threads but I happened to answer that one. OP's question should give you some useful pointers. My answer there is quite specific but might give you ideas on how to make messages "seen".

Pierre wrote this in the comments above.

  for each of those friends such notification can be marked as read by each friend individually

If you use a non-global Flag for "seen", then it will do the above.


What options do I have for changing CSS depending upon context? I would like to change CSS for different site areas and page layouts depending upon contextual information such as the user role or the type of content being displayed.  The types of changes would include font, color, and background options.  I can think of several ways to approach this, but could really benefit from the experiences of others.

Some options:

Use Views or panels to identify context and then associate styles with them.  This is limited because some of the elements are not directly associated with content, such as menu background, colors, etc.
Create a custom module to identify the user, content type or other context criteria and then modify the render array.  This sounds feasible, but the render array is pretty cryptic, and I'm not clear on what needs to change.  IF you've tried this, what have you done.
Create custom code in a theme to identify the context and then assign div class values to isolate the affected sections.

If you have tried this or other options, what did you do and how effective was it?

We have been using the theme key module to switch between different styles and (sub-) themes for different situations.


While developing a custom module, which function creates table in database? While developing a custom module in Drupal 7, which function actually creates tables in the database?

I have implemented hook_schema in mymodule.install, mymodule.info, mymodule.module file and defined the Controller class and creates an StdClass object, but still I can't seem to find my tables in my database.

Can anybody tell me what I could be doing wrong?

First things first, you are using the correct hook.

If your module is already enabled, then the implementation of hook_schema() won't get called.  This is also the case if the module has been enabled, and then disabled without uninstalling.

I would try disabling your module, and then ensuring it is uninstalled by either heading to admin/modules/uninstall/ or (if you have Drush installed) run drush pm-uninstall mymodule

From the documentation:

  The tables declared by this hook will be automatically created when
  the module is first enabled, and removed when the module is
  uninstalled. This happens before hook_install() is invoked, and after
  hook_uninstall() is invoked, respectively.

I'm not sure why you'd be defining a controller class though, or even which one you're defining.  Drupal 7 does this with an array, it's not very OO (Drupal 6/7 is array soup).

If this doesn't solve your issue perhaps you could paste a munged version of your implementation of hook_schema.


Close commenting after X comments have been posted I would like to ask if anyone knows how I can set a limit to the number of comments that can be made on a node with Drupal 7.

Perhaps what I'm asking isn't the best solution for what I'm trying to achieve.
I have created a content type (Event); each event will have a guest list which people can sign up to on a first-come-first-served basis. I would like each event to have a limit (ranging from 10 - 100) to the number of people who can register for the guest list position.

Any advice would be much appreciated.

You could use the drupal rules module to set up a system to close your comments after X amount of comments. In combination with the views bulk operations module, you could set up a rule for "new comment has been posted."

For the condition compare the number of results from a VBO created that counts the number of comments on the node the comment was posted to and compare it to the number of comments you want before closing. If there are 20 comments posted and the number you want to close at is 20 the rule will move on to the action.

The action would be a custom php snippet to set comments from read / write to read only. The snippet I was using for Drupal 6 was

$node->comment = '1';
return array("node" => $node);

so it may need to be modified slightly for 7.

With that all being said, if you are looking to set up an event registration setup where a certain number of people can sign up, you are actually looking for the entity registration module.

From the drupal.org website

  Entity Registration does lots of things you are expecting from a
  registration system (like allowing you to restrict the number of total
  registrations for a given event), and other stuff you are crossing
  your fingers and hoping for (like building in automated reminder
  messages for your registrants).


VIEW COUNT comments total per node I have found code to show the total:

How To Show Node Comment Count in node.tpl?

Unfortunately I need to have this value available via VIEWS because I want to list 5 nodes based on total comment count. Short of caching the total as a field in the node (intercepting comment post and incrementing the number) -- what are my options?

There is a field available in views called "Comment count" - just add this field and your done.


Drupal 6: Feeds mapping node taxonomy term I using feeds module for import data from xml to node.

I have XML:

<root>
<item>
<title>Example 1</title> <!-- map to node title-->
<body>Body of example 1</body> <!-- map to node title-->
<term_name>My_term</term_name>
<term_tid>15</term_tid>
</item>
</root>

SELECT tid, vid, name FROM term_data;
tid vid name
15  19  My_term

If I map <term_name> to my node taxonomy term (and term name exist) its working.
But If i map <term_tid> to my node taxonomy term (and term tid exist) it's NOT working. Why?

Thanks for helping

before importing nodes from a site that contains taxonomy terms , try first to import all taxonomy terms ( you can use taxonomy manager ).

Feeds will add a term with a new tid if It not exist , not the same as tid of the site from where you export


How to programmatically register a user with Mailchimp API I have a contact form with a checkbox "Register to the newsletter". If this checkbox is checked, I want to register the email adress (a field in the contact form) to the Mailchimp list, which works fine with the Mailchimp block.

I want to do this in my contact_form_submit fonction in my module, but I can't find a way... Does anyone know how to do this ?

Thanks.

EDIT: I use this code :

if ($values['newsletter'])
{
    $list = array_shift(mailchimp_get_lists());
    mailchimp_subscribe_user($list, $values['mail'], array());
}

This code put the user in the table "cache_mailchimp_user" but not in the mailchimp list subscribers, even after I run the Drupal cron manually... Any ideas ?

Drupal 7, Mailchimp module 3.4

$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = 'some_email@gmail.com';
if ( mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
    ),
    false,
    false
)) {
    drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
    drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
}

NOTE: If mailchimp will deside that your email is invalid module will only put watchdog error. To grab that error and display you can patch mailchimp.module
find function mailchimp_subscribe_process and goto approx line 412. and add drupal_set_messaga or whatewer you want.

Approach without patching module (but it's too hacky)

$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = 'some_email@gmail.com';
if ( mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name,
        'LNAME' => $last_name,
    ),
    false,
    false
)) {
    drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
    // Get last watchdog mailchimp error
    $query = db_select ( 'watchdog', 'w' );
    $query -> fields ( 'w' );
    $query -> condition ( 'w.type', 'mailchimp', '=' );
    $query -> condition ( 'w.timestamp', time() - 10, '>' ); // check for message in last 10 seconds
    $query -> condition ( 'w.message', 'An error occurred subscribing @email to list @list. "%message"', '=' );
    $query -> orderBy ( 'w.timestamp', 'DESC' );
    $query -> range ( 0, 1 );
    $ans = $query -> execute();
    if ( $wd = $ans -> fetchAssoc() ) {
        $wd['variables'] = unserialize ( $wd['variables'] );
        $message = $wd['variables']['%message'];
        // Get only error message
        if ( preg_match ( '#Internal\sServer\sError:(.+)$#si', $message, $m )) {
            $message = $m[1];
        }
        drupal_set_message ( $message, 'error' );
    } else {
        drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
    }
}


Display comment form without the comment thread What are some ways of rendering a comment form without also displaying the comments?

What about creating a block contains the form?  If that's possible, what are some links to documentation touching on that?

To display comment form without comments list, you need to override field--comment.html.twig template, and remove the following lines:

  {% if comments and not label_hidden %}
    {{ title_prefix }}
    <h2{{ title_attributes.addClass(title_classes) }}>{{ label }}</h2>
    {{ title_suffix }}
  {% endif %}

  {{ comments }}

to override it:

From your theme, just create one of the following twig file in you templates folder, and put in it field--comment.html.twig content without the above section.

   * field--node--comment--article.html.twig
   * field--node--comment.html.twig
   * field--node--article.html.twig
   x field--comment.html.twig
   x field--comment.html.twig
   * field.html.twig

Note: the above suggestions for article content type, you may have different suggestions.

From your module, implement hook_theme for one of the suggestions like the following:

/**
 * Implements hook_theme().
 */
function MODULENAME_theme($existing, $type, $theme, $path) {
  return [
    'field__node__comment__article' => [
      'base hook' => 'field'
    ],
  ];
}

And make your changes in MODULENAME/templates/field--node--comment--article.html.twig


How do I group elements in a view? I have 8 articles: Article 1 (Gaming), Article 2 (Local News), Article 3 (World News), Article 4 (World News), Article 5 (Gaming), Article 6, Article 7, Article 8.

In a view I would like to group the articles by: "News," "Gaming," and "Other." Combining the world and local news under one category, and moving anything that doesn't have a category to "Other." I didn't want to create a new vocabulary for just this view. I tried to accomplish this using the group by field, but I can't figure out how I could accomplish this using that method.

In your content type, you can create a "list" field called, say, Category, with the categories News, Gaming and Other. You can then categorize the content that should appear in your View using that field.

In your View, under Format, choose "Settings." There should be an option to choose a Grouping Field. Select the "Content: Category" field. Your view should now show up grouped according to News, Gaming and Other.

Was that what you had in mind?

UPDATE
The above wasn't quite what you were looking for. No problem.

You say you have articles like Article 1 (Gaming), Article 2 (Local News), Article 3 (World News), Article 4 (World News) etc. Is it right that the word in parentheses is a taxonomy term? If not, the below won't be relevant, but I'll assume for now it is.

If so and you want to 'chunk' these terms into three categories, you could certainly modify the Views query or write your own.

Alternately (which is probably easier) you could change your existing vocabulary into a hierarchical taxonomy with News as the super-category and Local News and World News as the subcategories.

So now your vocabulary looks like:

News

Local News
World News

Gaming

Other

If your content was already tagged with the existing categories, you shouldn't have to change anything.

You could then create a View that displays the fields you want. Add a filter "Term Name," and enter "News." Then, add an attachment display, and attach it to your current View, overriding the filter and setting it to "Gaming." Finally, add a second attachment and override the Filter, changing it to "Other." This should give you the result you want.


Render media url in node--page.html.twig I have an Entity reference field field_video. It's a core Media field with a Reference type of Remote video.

Because I use this field_video in my Hero section I need some additional markup here.

From the admin node/add/page, the editor can insert a Youtube remote video (url).

When I debug the page I see the following variables (see screenshot).

How do I render the media url in node--page.html.twig? Then I am able to build the correct HTML markup and styling around it.

To get the uri of remote video in node--page.html.twig try with:

node.field_video.entity.field_media_oembed_video.value


How to solve the "No file was uploaded." when trying to use custom form field? I get "No file uploaded" when I try to use a custom form in drupal .Below is the code which I have used to upload a file in drupal custom form.

    function mobiae_custom_purchase_order_form(&$form,&$form_state) {
      // Merge default values into the default array.
        $form = array();
          $form['#attributes']['enctype'] = 'multipart/form-data';

          $form['file'] = array(
            '#type' => 'file',
            '#title' => t('Image'),
            '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
          );

      return $form;
    }

function mobiae_custom_submit_form($payment_method, $pane_values, $checkout_pane, $order) {
  module_load_include('inc', 'mobiae_custom', 'mobiae_custom.purchase_order');
$form = array();
$form_state = array();
  // Default to a known test credit card number. For valid numbers of other card
  // types see: http://www.rimmkaufman.com/blog/credit-card-test-numbers/09112007/
//$form['#submit'][] = 'mobiae_custom_submit_form_validate';
  return mobiae_custom_purchase_order_form(&$form, &$form_state,$order);
}

/**
 * Payment method callback: submit form validation.
 */
function mobiae_custom_submit_form_validate($payment_method, $pane_form, $pane_values, $order, $form_parents = array()) {
  // Validate the credit card fields.file_save
 drupal_set_message('fgh');
 $file = file_save_upload('file', array(
      'file_validate_is_image' => array(),
      'file_validate_extensions' => array('png gif jpg jpeg'),
  ));

  if ($file) {
    if ($file = file_move($file, 'public://')) {
      $pane_values['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('No file was uploaded.'));
  }

//  module_load_include('inc', 'commerce_payment', 'includes/commerce_payment.credit_card');
  if (form_get_errors()){
    return false;
  }
}

For saving file u can use

    $form['test_picture']['file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Test Picture'),
        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => variable_get('picture_upload_location'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('pdf'),
            'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
        ),
    );


Duplicated modules and drush During an update process of Open Atrium I ended up with the Organic Groups module (og) duplicated in sites/all/modules/og an profiles/openatrium/modules/contrib/og. I checked the 'system' table in the database and the one that's enabled is in sites/all/modules, however if I update the record in the 'system' table in order to use the module in profiles/openatrium/modules and afterwards I run the drush command

drush pmi og

and the output still reads:

Path: sites/all/modules/og

so where does drush get this value from?

Drupal caches the system table with all the module locations, so you'll need to run:

    drush registry-rebuild

or use the Registry Rebuild module in order to flush that cache after manually updating the module paths in the system table. Alternatively, you could also just manually delete the system list from the cache bootstrap table:

    DELETE FROM cache_bootstrap WHERE cid='system_list';

Sources:

Overriding and Removing Overridden Modules included in a Distribution - https://drupal.org/node/1974964

Disabling or Enabling modules manually in the database - https://drupal.org/node/157632


Drupal 7 - Retain checkbox values across pages In Drupal 7, I am using tableselect theme with PagerSelect to generate table with checkboxes and pagination. Any thoughts on how to retain checkbox values on pagination?

Store the selected checked box in a database. Load each check box as the pagination goes and check the #default_value

example if I had 3 checkbox in a table select for my pagination:

$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

Obviously there is more to this, like pagination, but it should get you on the right track.


How can I insert search box in page.tpl? How can I insert search box(search block) in my theme programmatically?

According to your tag, you're looking for a D7 solution. The Drupal 7 page.tpl.php doesn't have the $search_box variable anymore. However you can add it in a preprocess function in your template.php:

<?php
/*
 *  Preprocess page.tpl.php to inject the $search_box variable back into D7.
 */
function MYTHEME_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

Then you just need to print the variable in your page.tpl.php:

<?php print $search_box; ?>

You could also use module_invoke, but you shouldn't have php logic in template files:

<?php
  $block = module_invoke('search', 'block_view', 'search');
  print render($block);
?>


views_get_view() not accepting arguments? Code without arguments works, but with arguments I run into an error of EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. Value at commerce_line_item()->commerce_product: . in EntityDrupalWrapper->set()

This does not work:

    $array = array('228');
    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->pre_execute($array);
    $view->execute();
    print $view->render();

This works:

    $view = views_get_view('commerce_wishlist_page');
    $view->set_display("default");
    $view->execute();
    print $view->render();

Did they changed something? Because according to documentation this should work. I can confirm view work in views UI, also with handwritten contexual filters in UI. How can I solve this?

View "commerce_wishlist_page" was created by module itself. There appeared to be some problem with the view configuration itself, because when I re-created the view with exactly same values the error is gone. I think this is the module problem and possible typo somewhere in hook_install()


login form without registration link How can I get rid of the link for registering a new account in the login form/popup?

I want my new users to register through a page but not through the login form.

Another idea for this that you just create your custom module and form_alter function to modify or change the template for login/register/forgot password form. With this way you can handle everything but just in case you want to build your own module. If you want to do this way. I can give you the example code right here.

By the way which drupal version do you use


in ckeditor plugin, why isn't my getConfig returned array affecting editor? I'm including the wordcount plugin to CKEditor in D8. I'm including some configuration (maxWordCount) through the configurable interface. The issue I'm having is that no matter what I return from getConfig there's no affect on the editor.

class WordCount extends CKEditorPluginBase implements CKEditorPluginContextualInterface {

  public function isEnabled(Editor $editor) {
    return TRUE;
  }

  public function isInternal() {
    return FALSE;
  }

  public function getFile() {
  return drupal_get_path('module', 'ckeditor_maxlength') . '/wordcount/plugin.js';
  }

  public function getConfig(Editor $editor) {
  // just return a hardcoded maxWordCount.
    return [
      'maxWordCount' => 10,
    ];
  }

  public function getButtons() {
  // No buttons needed.
  }
}

To be clear the counter works as expected, but I don't seem to be able to override the default configuration.

Inside the core ckeditor module the getConfig function has this notation:

* @return array
*   A keyed array, whose keys will end up as keys under CKEDITOR.config.

When I inspect CKEditor.config in the console I don't see the configurations, and infact, the wordcount plugin is buried in CKEditor.plugins.externals.

It turns out I was just formatting the array improperly. In order to return the configuration to my wordcount plugin I did this:

 return ['wordcount' => ['maxWordCount' => '10']];


views filter problem Filters on Views only give the possibility for static values. I want to show only nodes with a node ID that is an odd number.

Using PHP code, this is what the filter should do:

if ((nid % 2) == 1) {
  return TRUE;
}

Can anyone tell me how to do this?

The Views PHP module would work for this.


Create a related content block which sorts the nodes of related content by how many tags they share? The options in a views Advanced tab seem to only allow:

Multiple-value handling
Filter to items that share all terms
Filter to items that share any term

and I'd like to show items that share any term but sort by showing the items sharing the most terms at the top. Sort of like a "relevant" sort filter?

You can do this with Aggregation, but you have to be careful about some details.

The first thing to do is to create a block listing your desired content, with contextual filters that will restrict the results to only nodes that are tagged with the same terms.

A very popular method of doing that is through Has taxonomy term ID contextual filter set to Provide default value of Taxonomy term ID from URL (with other options appropriately set).

I haven't been able to achieve the Sorting through Aggregation that way. Perhaps someone will come along and shed some light on this, whether and how it can be done.

I have been able to do it with a different strategy, the one that is usually necessary when dealing with Entity references in general. It relies on Relationships to introduce sibling nodes, and ID as contextual filters. Here are the steps to create it:

List nodes tagged with the same Taxonomy terms

Create a View of type Content, Filter it as usual to Content types, the taxonomy field not empty etc. Show fields Title and the field containing your terms, show Multiple values in the same row although that won't matter later, format as Table simply for readability, you can change it later.
Add a Relationship (search for your field name) Taxonomy term referenced from field_yourtags.
Add another Relationship Content using field_yourtags,
it will be set by default to use the Relationship from the previous step
Add a Contextual filter ID (from Content Category) and set it to use the second Relationship (the one from the previous step, it will actually be the only choice next to "Do not use a Relationship") with other options:
When the filter value is NOT available:
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
[your appropriate types]
Add another Contextual filter ID  but this time Do not use a Relationship:
When the filter value is NOT available:
Provide default value
Content ID from URL
More: Exclude

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter 14/14.

Don't worry about the multiplicates, we'll turn them to the best use with Aggregation ;) They are listed the number of times that the tags match between them and the current node!

Aggregate results according to common terms count
Turn Aggregation on (Use aggregation option in the third column set to Aggregate), don't worry about the red message in Preview. All fields and filters now have Aggregation settings. You only need to change the one on your taxonomy field:
Click on Aggregation settings for the "Content: Yourtags" field and change it to Count DISTINCT. Notice how your tags are now replaced by numbers indicating how many common terms those nodes have with the current node!
Now we just have to sort the View using this data: Add a Sort criteria:
Content: Yourtags
Do not use a Relationship
Sort descending
Aggregation settings: Count DISTINCT

Now you can Place your block in a Region and check the count on nodes.

Additional perk of this approach is that it won't list anything if the current node isn't tagged with any terms, while with the "Has taxonomy term ID" method you get all results.


Any idea on how to include a an option in display handler in views I want to include a check box below pager options i achieved it with form alter  . The problem is how can i retrieve or store the value which user has selected and use that value for further process in views

Since you want to add the configuration of the display (which is a plugin), you have two options:

Create a new display plugin
Change the class of the existing page plugin.

The two options are essentially the same, in the sense that you need to create a custom plugin class for views display. The only difference is if you alter what the plugin manager has stored or if you define a new one.

You should extend the existing \Drupal\views\Plugin\views\display\Page class.

Most of the stuff, you don't need to worry about, but you need to extend the following methods:

defineOptions
buildOptionsForm
submitOptionsForm

A very simple implementation of a new plugin class (totally untested code, but should work with small alterations)

use Drupal\views\Plugin\views\display\Page

/**
 * Custom page display to add more options.
 *
 * @ViewsDisplay(
 *   id = "custom_page",
 *   title = @Translation("Custom Page"),
 *   help = @Translation("Display the view as a page, with a URL and menu links."),
 *   uses_menu_links = TRUE,
 *   uses_route = TRUE,
 *   contextual_links_locations = {"page"},
 *   theme = "views_view",
 *   admin = @Translation("Custom Page")
 * )
 */
class CustomPage extends Page {

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['custom'] = [
      'contains' => [
        'checkbox' => ['default' => FALSE],
      ],
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    // A bit tricky, since views uses a concept of sections. Either you need
    // to define your own section or you can just add your config to an existing
    // section. If you use an existing it will be a lot easier.
  }

 /**
   * {@inheritdoc}
   */
  public function submitOptionsForm(&$form, FormStateInterface $form_state) {
    parent::submitOptionsForm($form, $form_state);

    switch ($form_state->get('section')) {
      case '?':
        $values = $form_state->getValue('?');
        $this->setOption('custom', $values);
        break;
    }
  }
}


Code working normally in a fresh HTML file but not in a Drupal block Just wondering if someone would be kind enough to help me with a problem i am having.

This is the code that i am currently using for my E-junkie View Cart button on my Drupal site:

When i use this code on a normal HTML page the pop up is very nice and clean. However, when i try to use this code in a block on drupal the pop-up still works but there is no banner and the tables for the shopping cart all messy and etc.

Another thing that I am wondering about is my twitter feed doesn't work.

I have tried enabling the PHP module and set the input filter to PHP code and the twitter feed now shows but i am unsure if this is an efficient way to fix the problem. When i did this for the code above the banner of my cart started showing but the tables and etc. were still messed up.

I've been reading some FAQs and some people are suggesting that I should make exceptions in my theme's CSS files so that it does not affect the pop-up cart on my site but I do not know how to do this.

Apologies for the chunks of text, thank you in advance for any help.

Inputing PHP or Javascript through the UI is almost always a bad idea, and can happen to be impossible in some cases, for security reasons.

I recommend another approach, for example creating a block in a custom module with the various block hooks.

This way, you won't bypass Drupal security and you'll have a much more versatile and robust solution.


Why does pagination create duplicates in Google's results? I created multiple views to display different types of nodes on my site. On each of these views, I added a pagination, which creates duplicates in Google's results. Why?

I think this is bad for the SEO of my site. How can I avoid this?

This is definitely bad for SEO.

You need to set related links on the each page of the view so that google doesn't crawl all of the variations via parameters. Example:

<link rel="next" href="http://example.com/view?page=2">

Apparently the metatag module will help with this, or you can find some discussion about how to do it on this issue.


How would I create conditional fields on install? I am creating a content type in a module so that it gets created on install.

I got the fields and field instances in separate files and include those files in the .install file. I then call field_create_field() and field_create_instance() in the install file.

However, I also have conditional_fields for this content type. I have the code to create the conditions, what I need to know is what function do I now call from the .install file like I did with the other two field functions?

I ended up getting this to work by creating a feature for the node and copying the array to the module.

To get the 'ID' of the dependee and dependent, I used field_info_instance. After I had that I could pass that info to conditional_fields_dependency_insert.

I did all this in hook_install.


Display Suite node field in layouts Well it might be a simple solution but I don't get it.

I have a field in my content type "field_color". I can get the value of that field in my page.html.twig with {{ node.field_color.value }}

It works really good.

With Display Suite I created several layouts, but how to I access the field value within the layout.

I already tried:

{{ node.field_color.value }}
{{ ds_content.field_color.value }}
{{ ds_content.field_ }}
{{ ds_content.0 }}
{{ ds_content.1 }}
{{ ds_content.3 }}

nothing works.

Drupal 8, DS 2.5 stables

In my layouts.yml

sw_default_text:
  label: 'Text 1col Collapse'
  category: 'my cat'
  class: '\Drupal\ds\Plugin\DsLayout'
  template: layouts/sw_default_text/sw-default-text
  regions:
    middle:
      label: Content

My sw-default-text.html.twig:

{#
/**
 * @file
 * Template for a 1 column layout.
 *
#}
<div {{ attributes.setAttribute('id', settings.css_id).addClass('row shrink', 'sw-default-text', settings.css_classes) }}>
  <div class="small-12 columns">
    {{ content.middle }}
  </div>
</div>

My suspicion is you are having an issue because you are trying to access this in a Display Suite template, rather than from a page template.

You can probably access it via {{ ds_region.field_color.0 }} in the ds-3col.html.twig file. Some notes:

Replace ds_region with the name of the ds_region you want - e.g. middle.
The 0 will mean it prints the first item in the array - if you only have one item, this should be enough
You will need to have the field in the region on your Manage Display page.
Once done, you can then print {{ left|without('body') }}.
Make sure to clear your cache

I hope this helps.

You could also try to {{ dump }} the variables and see what is available for you (or better still {{ kint }} if you have the devel module installed), that will help you drill down through the options to get the one you need.


Authorize.net - Multi-currency - disabling currency code when sending money I have a issue processing multiple currencies in Drupal 7 Commerce with Authorize.net Gateways (version 1.0 stable).

I have Canadian store and have 2 currencies setup for my site: US and CDN funds.

Our processor is Bluepay and I have established separate US and CDN accounts.

I have noticed there are no problems processing US payments during check out. However when checking out in Canadian Currency using a Canadian Credit Card Authorize.net rejects my transaction.

Authorize.net is stating I must turn off 'currency code' in order for Canadian funds to be accepted with their gateways.

Is there a way to disable currency code in Drupal 7 Commerce? Is this even recommended if using more than 1 currency? How do most people go about processing multiple currencies in Drupal 7 Commerce via Gateways and Processors?

Are you sure the issue is that the currency code value is included or is it simply wrong? i.e. are you submitting a USD currency code to a CDN account? Note that in the 1.0 released earlier this month we fixed a couple of issues pertaining to multi-currency usage. Does updating to this version allow transactions to process as expected?


How to speed up Drupal 7 compiling PHP to C++? I would like to improve Drupal 7 performance with HipHop or any other similar solution transforming the code from PHP to C++ or C.

What steps are needed to properly do the scenario below ?

I would like to :

maintain @development environment as not-compiled php, adding and
testing contrib and custom modules.
after testing @development, I do rsync @development to @staging
...
... and compile @staging
test @staging
rsync @staging to @life

I think it is a bit oversimplification but should bring an overview.

If it is not possible, are there any other options ?

Following the chain from a comment on this great Wordpress tutorial on the new HHVM, I was led to Nick Veenhof's blog where he posted very recently about his unsuccessful efforts to get hiphop-php working with Drupal.

For what it's worth, the awesome maintainer of hiphop, Sara Goleman, said in the comments that she was interested in supporting Drupal and was going to try to reproduce the issue.

I'm working at building a vagrant VM to help reproduce the error and get everyone on the same page as easily as possible. The plan is to [use a patch that supposedly worked against Drupal 7.4, and hopefully move forward from that working state :)

https://github.com/patcon/vagrant-hiphop-drupal


Make Conditional Field work with Price widget I would like to know if there's a way to make the Conditional field module here work with the Price widget. For example, I want to allow the user to input a price when he checks something with a checkbox.

Conditional field module is base on the States API. You can probably do this via a hook_form_alter in a module.

The example below will make the field 'my_field_price' visible and required when 'my_checkbox' is checked.

  $form['my_field_price']['#states'] => array(
    // Show and make the field required if 'my_checkbox' is checked.
    'visible' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
    'required' => array(
      ':input[name="my_checkbox"]' => array('checked' => TRUE),
    ),
  ),


testing scheduled file deletions Long story short, is there a correct way to override DRUPAL_MAXIMUM_TEMP_FILE_AGE?
I'm working on testing a fix to a module I wrote a while back that handles some uploaded files. I neglected to call file_usage_delete and set file_managed status to 0. To test my changes more quickly, I'd like to schedule files for deletion after doing some operations on them. To do this reasonably I had to reduce the turn around time on deletions to something on the order of minutes than hours. I went ahead and edited system.module where DRUPAL_MAXIMUM_TEMP_FILE_AGE is defined as 6 hours, but the comments immediately preceding the defines indicate:

@file
Configuration system that lets administrators modify the workings of the site.

I checked the places where this value is used, and it doesn't look to be actually configurable besides editing system.module directly. Maybe I'm missing something?
Is there a correct way to set this that doesn't involve "hacking core"?

It isn't configurable. You would be better served writing your own routine that executes on a regular interval and searches for temporary files whose creation age is greater than 10 minutes ago.
The DRUPAL_MAXIMUM_TEMP_FILE_AGE constant is specifically intended to inform Drupal on when a file that has not yet been set to permanent should be removed.
If you take a look at system.module, the relevant code is contained in a hook_cron() implementation. The code reads:
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));

My recommendation is to simply implement your own hook_cron() and use the same code, but calculate for files older than 10 minutes.
You will also need for cron to execute on a 10 minute interval. For this, you'll need to add a crontab and install either ultimate_cron or elysisia_cron. I prefer ultimate_cron.
Please see my answer to this question for more information on setting up crontab on a 60 second interval for maximum timeliness. You'll then use elysia_cron or ultimate_cron to control the actual job execution interval.


Organic Groups let users with a particular role Edit/Delete content only in the group(s) they belong to I am using Organic Groups and have a custom role say "A". I want users with "A" role to be able to "edit/delete" any content only in the groups they belong to.

I have tried setting up with base System and OG permissions and also using Field Permissions, OG Role Override modules, but can't get exactly what i want.

Any direction on this is appreciated.

Thanks!

Mark a content type as og group and the rest as og group audience


Add class to form-tag in in views exposed form via template_preprocess_views_exposed_form() I wonder how I can add a class to the form tag (of the _search_content_ view's) exposed form using template_preprocess_views_exposed_form() (or even better template_preprocess_views_exposed_form__search_content()). The form is exposed as block.

It works so far using the following code in MY_THEME.theme:

function MY_THEME_preprocess_form(&$variables) {
  if ($variables['element']['#form_id'] == 'views_exposed_form' && $variables['element']['#view_id'] == 'search_content') {
    $variables['attributes']['class'][] = 'row';
  }
}

But I can't get it work for:

function MY_THEME_preprocess_views_exposed_form__search_content(&$variables) {
  // I tried:
  // $variables['attributes']['class'][] = 'does-not-work';

  // and also:
  // $variables['attributes'] = new Attribute($variables['attributes']);
  // $variables['attributes']->addClass('does-not-work');

  // and also manipulating $variables['form'], but this didn't work either.
}

The function gets called, but it's not adding the class to the form tag. Is it possible to get it work with template_preprocess_views_exposed_form()?

Screenshot of kint($variables) output, for each function:

Is it possible to get it work with template_preprocess_views_exposed_form()?

Short version: You cannot use hook_preprocess_views_exposed_form() to modify the <form> tag. The <form> tag is independently rendered by a form theme hook set through the #theme_wrappers render property. Which means that it is completely disassociated from the actual views_exposed_form theme hook that renders the (internal) content of the views exposed form.

Long version:

views_theme() defines the views_exposed_form theme hook as returning a form render element. That means that it will eventually be using (unless somehow overridden) the definition provided by the Form render element. If you take a look at that, you will see that that definition  sets the'#theme_wrappers' property to ['form']. No surprises so far. :-)
At some point during the theming of a views page (or block), the theme hook views_view comes into play; this theme hook contains the exposed render variable that is essentially the exposed form you are interested in. The render array of exposed holds the following two relevant properties:

#theme => views_exposed_form (and other more specific ones like views_exposed_form__search_content): This is the theme hook that will provide the content of the form, i.e. everything inside the <form> tag. This is what you get access to and given the option to modify when calling template_preprocess_views_exposed_form(). This theme hook is not responsible for rendering the <form> tag and does not allow you to change it.
#theme_wrappers => ['form'] : This is the #theme_wrappers list of theme hooks; form will provide the actual <form> tag. It will essentially enclose the markup generated by the #theme theme hook into a <form> tag. This is what you get access to when calling template_preprocess_form(). This theme is responsible for rendering the <form> tag and does allow you to change it.

Implementation suggestion

If you would rather let hook_form_alter() implementations handle form-related logic, you could still use another preprocess hook to implement the functionality you want, namely the preprocess_views_view() hook.

function MY_THEME_preprocess_views_view(&$variables) {
  if ($variables['id'] === 'search_content') {
    $variables['exposed']['#attributes']['class'][] = 'row';
  }
}

Good luck, this is a really good question!


Incorrect string value: '\xF0\x9F\x92\x99' for column "'comment_body_value'" How can I fix the following error I get from a Drupal 7 site?

Incorrect string value: '\xF0\x9F\x92\x99' for column "'comment_body_value'

I read it is about users posting emojis that cannot be handled by Drupal/MySQL.
I don't care if the comments are being stripped off the emojis, or converted as long as it does not trigger an error to the end-user. The simpler the solution the better.
I found a few modules, for example the Emoji Scrub module that isn't covered by the security advisory policy.

This explains how to solve this issue: https://www.jeffgeerling.com/blogs/jeff-geerling/solving-emoji-problem-drupal-7


Comment subject field too large breaks the page layout I activated a contributed theme and I am doing some little customization. At the moment I have a 2 columns layout (content + second sidebar). Originally the theme was designed with a much larger content column hence after reducing its size I realized the comment subject field was too large for the content column.

Looking in the theme style.css file was of no help. I am trying to reduce the size of the comment subject field from 60 to 40 in the following portion of HTML code:

<input id="edit-subject" class="form-text" type="text" maxlength="64" size="60" value="" name="subject">

but I do not understand where/what part of drupal php code generates it. I am also afraid I will meet the same problem once the contact form is enabled.

Any help?

All right I got it. I fixed it in the style.css file

WAS:

.form-text {
    border: 1px solid #ACACAC;
    border-radius: 3px 3px 3px 3px;
    color: #949494;
    padding: 4px 5px;
}

IS

.form-text {
    border: 1px solid #ACACAC;
    border-radius: 3px 3px 3px 3px;
    color: #949494;
    padding: 4px 5px;
    width: 75%;              /* <-- added line */
}


Link to images(thumb) in a (block)view to the image(original) in another (page)view I have a  unlimited multivalue field image gallery.

Using views i created a page for file entity and got the list of files in the field. The page displays the default original images one by one with a pager.

Created a block for the same view with the files shown as thumbnails, so the user can view all images in the gallery and click on the image he/she wants to see. I can link the thumbnails to content or file which takes me to the original file.

Is it possible i can link them to the corresponding image in the page view.

In your block view, if the "Link image to " option doesn't give you what you need for the thumbnail image field, you can build your own link using "Rewrite Results". You would do something like this:

Add content:path or nid to your view, and exclude from display
Make sure content:path or nid is first in you list of fields
For the thumbnail image field, enable "Output this field as a link " under Rewrite Results
use the token for nid or content:path (i.e. [path]) to construct the link you need

Note: if you use content:path, you will probably want to enable "Use absolute path" for it's field settings, even though it is excluded from display.


How to create groups and assign users to them using Organic Groups? I have downloaded the Organic Groups module for my Drupal project and am currently trying to create groups and assign users to them.

I don't want anything fancy. I just want to be able to create groups, have the user assigned to them by the main administrator (not allow the user to register themselves) and have the assigned 'leader' of the group be the only one within the group with edit/etc permission.

I am unsure how to start. I found the resource Organic Groups: Enable users to create collaborative groups that looks really good, but I think it is for an older version of Drupal because the OG sections I have found are in a different location than the site says.

How do I do this?

Have you read the readme file in og module folder, it shows basic instruction to create a group, assign content to the group.

Basically, after enabling OG module, you need to create a content type, if you want it to be a 'group', select the "Group Type" option, then each instance of this content type will represents a group.

Below are some links will help you start:

Basic OG Documentation: http://drupal.org/node/483234

Amitai's presentation of OG7: http://www.archive.org/details/GrouptheNewOrganicGroups-BuildingSocialNetworksInDrupal7    (I recommend you watch this video, very informative. I am sure you will sort it out)


How to count the node a user has created in a View? I created a view to show Users. These users can create nodes of the "Questions" content type.

The view has to render a table to show how many (the total number) Questions the user has created. Something like:

User +++ Questions created
John --- 10
Ted  --- 4
Alf  --- 19

you have to use the Aggregation setting and active it in your view.

Activate Aggregation. (It's in the "advanced settings" of the view)
As your view is a view of users, add the relationship "User : content authored". If you set the option "Require this relationship", you'll skip users with no nodes created (can be useful)
Add your user name field, don't use aggregate
Add a node field, let's say Node : nid with the relationship set
Use Aggregate for this field, "Count DISTINCT".

Have fun !


different views for different taxonomy vocabularies at taxonomy/term/% I have two different content types: cars and boats. each one has a taxonomy vocabulary of the same name associated with it. I have two views, one for each, that shows listings based on this content type.  I have to use the taxonomy/term/% to use the taxonomy term or id as an argument.

My problem is that this would work if both views had the same fields, but they don't they are quite different.

How can I get views to show results based on my taxonomy term as well as show different fields for each view? I would prefer not to use an existing module to handle this. Maybe I can configure the views differently or use a php snippet?

Best Solution is using  the : Taxonomy Views Integrator  allows you to choose which view to associate with which taxonomy through a very handy and intuitive drop down menu.

More Detail are Found here:


How do I make multilangual content synchronization between two sites? I'm trying to figure out how to synchronize content between 2 sites. Before migration to D8 I was using views data export on site1, and feeds import on site2. My problem is, that in D8 I'm not able to create view where on one row will be English and French content - they can be only two separated rows. But this way I don't know how to set up feeds, to consider these 2 lines as translations of 1 node.

On the source site:

Make sure that your view has a column that contains an unique identifier for the item. This value must be the same for every language of the item.
Add a column to the view that contains the language code. For English this would be 'en' and for French this would be 'fr'.

On the target site:

On the feed type, map the unique identifier either to:

A non-translatable field;
Feeds item: GUID.

And mark that as unique on the feed type.

Map to all the fields that you want to map to.

Map the langcode value to the "Language" target.

Known issues
Note that there are some known issues with importing multilingual content using Feeds. I'm doing my best to resolve them.
You can currently run into the following errors:

this field cannot hold more than 1 values.
Patch available at https://www.drupal.org/project/feeds/issues/3155046

A translation already exists for the specified language
https://www.drupal.org/project/feeds/issues/3126351
No patch yet, but you could help by confirming or correcting the steps to reproduce the issue.

Column cannot be null (SQL error)
https://www.drupal.org/project/feeds/issues/3169398
You can help by describing the exact steps to reproduce this issue.


Getting parent enitity of enitityreference field Is there a function to get parent enityinfo to which entityreference field is attached. Similar function is hostEntity() provided by field_collection.

I created the content type which has enityform as enitityreference field.Enityform contains basic contact field with additional computed field.
In that field I need nid of node to which entityform is attached.Using entity_metadata_wrapper I am able to get info about entityform object using below code.

$wrapper = entity_metadata_wrapper($entity_type, $entity);
$info=$wrapper->entityInfo();

Any idea how to further backtrack and get parent node id?

Update : Entityform is attached to a node(ref).
1.Node contains entity reference field, to which enitity form is attached.
2.Enityform contains computed field.
3.In computed field when the above mentioned code executed, field $wrapper gets the details about enitityform object(should be because computed field belongs to this entity).
4.As there will be no relation between node and the attached entityfrom after submission, I am trying to capture the NID of node during the form submission.

Something like this should work:

// Load wrapper
$wrapper = entity_metadata_wrapper($entity_type, $entity);
// Load parent entity
$parent = $wrapper->field_entityreference->value();
// Get nid
$nid = $parent->field_computed_field->value();
// Debug output
drupal_set_message(t('Parent NID: @nid', array('@nid' => $nid)));


How to check how many times a user has logged in? I want to know how many times a user has logged in until a given date in Drupal 7. Is this possible?

I don't think drupal keeps that data as standard. You might want to look at User Stats Module which does it for you.

  Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics are:
  1. days registered;
  2. join date;
  3. days since last login;
  4. days since last post;
  5. post count;
  6. login count;
  7. user online/offline;
  8. IP address;


Can I use 'drupal_add_library' inside an ajax call? The title is pretty self-explanatory, I would like to do something like this to display a jQuery UI dialog:

function my_ajax_page_callback() {
  drupal_add_library('system', 'ui.dialog');
  drupal_add_js('jQuery.dialog(...)','inline');
}

Specifically, I would like to include the library on-demand, not on every non-ajax request. Is that possible in D7?

drupal_add_library() under the hood ends up putting things into the same array as drupal_add_js() and drupal_add_css().

These get called by ajax_render(), so your function should work (so long as you are using ajax_render).

However this will add the library load to every ajax request. This will slow them down some what, and most of the item you are using ajax for speed so that may not be such a good idea. Your html JS should be cached and it should only include the ui.dialog on pages where you need it. So I think you may be better off using the standard JS caching.

In simple cases you may be able to use ajax_command_alert() in stead.


cannot track view with features I'm using Features to create a feature called foo which tracks content types and views so they can be described in code, committed to my repository and eventually pushed into the staging and production servers.

Some modules (e.g http://drupal.org/project/nodequeue, http://drupal.org/project/views_bulk_operations, http://drupal.org/project/admin_views) create some views as part of their functionality. The problem is that I can't include those views into my foo feature. So for those specific views I have to repeat (by hand) any customization I did locally to the staging and production servers.

Any ideas?

What I've tried:

1) I tried manually adding the view name in the foo_features.info file:

features[views_view][] = admin_content_node

but when I do drush fu foo_features -y that line is removed and the .info file and the view definition is not being included in the foo_features.views_default.inc file.

2) I had a look into the database:

mysql> select vid, id, display_title, display_plugin, position from views_display;
+-----+----------+---------------+----------------+----------+
| vid | id       | display_title | display_plugin | position |
+-----+----------+---------------+----------------+----------+
|   3 | default  | Master        | default        |        1 |
|   3 | page     | Page          | page           |        2 |
|  30 | block    | Block         | block          |        2 |
...
|  46 | default  | Defaults      | default        |        1 |
|  46 | system_1 | System        | system         |        2 |
+-----+----------+---------------+----------------+----------+

That last row (vid: 46, display_plugin: system) seemed suspicious so I've changed (directly via SQL) system to page. I then did drush cc all and retried the process at [1] for including the view into the feature but without luck. I tried this because I thought that "system view displays" (whatever that means) cannot be included in features.

This is bypassable by cloning the views you need from the four views that the module provides, disabling the original views, and doing all your work in your clones which are 100% trackable.