Custom image style used on image upload causing errors The site is running in a Windows Server environment.

I have a custom content type, which has a single "image" field.

I have created a image style, called "slider" with the dimensions 800x480

Images uploaded have some issues:

The original file names are kept but all uploads stored in the same folder. Ideally these names would be timestamped or hashed to prevent duplicate collisions
The file dimensions do not seem to be applied in resizing the image, does this only apply if the uploaded image is larger? Do I add a "scale" filter if I want to enlarge the image to fit the dimensions?
Uploaded images go to:

http://www.mydomain.local/sites/default/files/park/pics/BHP_beach.jpg (this exists)

but the preview:
    http://www.mydomain.local/sites/default/files/styles/slider_desktop/public/park/pics/BHP_beachjpg?itok=lR2G_oG3 (this does not exist)

This latter path is not valid, rather there is no image by this name in this directory??? Why are no files being written here? I just noticed another error which is probably related to the last point I make:

  Warning: imagejpeg() [function.imagejpeg]: Unable to open
  'public://styles/slider_desktop/public/park/pics/BHP_beach.jpg' for
  writing: Invalid argument in image_gd_save() (line 270 of
  C:\mywebsite\modules\system\image.gd.inc).

How do I enable public:// stream wrappers???

Lots of questions I know...but all related to the same thing I think.

Files will be renamed to prevent collisions. Off the top of my head it adds something like _1 to the filename.
Yes that's correct. I'm not sure about the scale but that sounds like it would work. If the image is too small, it will get scaled up. If the image is too big, it will be resized down then scaled and the scaling shouldn't have any effect.
That all sounds like it's working as intended. You have a simple problem with directory permissions within your sites/default/files directory. If you're in a dev environment try doing chmod -R 777 files (Then you know it's a permissions problem and you can set them properly). Problems like this are usually either because the file cannot be read or written, in your case it looks like writing. The PHP stream wrappers mentioned in the error message are enabled and working, don't worry about that, it's standard PHP. If chmod doesn't work, try changing ownership with chown.


In Drupal 8, how do you add attributes to a link generated by the core Link field? (or, generally a render array with #type set to "link") So I have a situation where I have a core Link field on a node. I wanted to style that link with custom attributes, so I created a field.html.twig override to do that, only to find that the link itself is printed elsewhere. There doesn't appear to be a template or theme hook for the link; given that the core Twig debug functionality doesn't report a child template being invoked.

I tried pulling the URL out directly and rendering my own link, but that class (Drupal\Core\Url) isn't on the Twig whitelist, so getting the URL out will just cause a WSOD. There doesn't appear to be an Attributes object that I could add things into.

I could use theme_preprocess_field to call Drupal\Core\Url->toString() directly and store it in another variable, but I'd be throwing out whatever attributes are generated by default. I'd rather participate in however Drupal is rendering this link directly; or, if it's not extensible, at least know how to replicate what core does.

(For the record, the solution recommended in another question of using theme_preprocess_field to write attributes into #options does not appear to work.)

EDIT: As requested, here is the code I tried for a preprocess hook to add attributes:

function MYTHEME_preprocess_field(&$variables) {
    $element = $variables['element'];
    if ($element['#name'] == 'field_extra_links') {
        $variables['items'][0]['content']['#options']['attributes']['class'][] = 'Button';
    }
}

Answering my own question: the original suggestion was actually a valid solution; the way I had my theme configured meant that the hook wasn't loading. Stupid mistakes!


how to identify when a user is viewing their profile? I'm relatively new to Drupal and have created a module that among other things uses hook_menu() to add a link to a user navigation "my gallery" this all works well except this link appears when a user views another user's profile. So what i want to do is add some code to tell Drupal not to display this link when a user is not on their own profile.

I'm guessing I need to change the access callback from user_access to a custom callback that carries out this check. Any help would be greatly appreicated.

My code so far is the following one.

global $user;
// get name of current user
$currentUser = $user->uid;
// get profile url
$profileUrl = arg(1);
// compare usernames to determine whether the user is on their own profile.
if ($currentUser == $profileUrl) {
  // user is on their profile, display link
  $profileUrl = "i'm home";
}
else {
  $profileUrl = "away";
}

$items['user/%user/gallery'] = array(
  'title'            => $profileUrl,
  'page callback'    => 'drupal_goto',
  'page arguments'   => array('gallery'),
  'access callback'  => 'user_access',
  'access arguments' => array('access content'),
  'type'             => MENU_LOCAL_TASK,
);

return $items;

The problem is it seems to get fixated, so if I start on the admin profile it correctly displays "I am home"; however, if I view another profile this doesn't change as it should. How can I fix this?

You can try 'title callback' attribute of hook_menu function.

$items['user/%user/gallery'] = array(
  'title callback' => 'get_title',
  'title arguments' => array(1),
  'page callback' => 'drupal_goto',
  'page arguments' => array('gallery'),
  'access callback' => 'user_access',
  'access arguments' => array('access content'),
  'type' => MENU_LOCAL_TASK,
);

And now you can call the function

function get_title($user_id) {
  global $user;
  $currentUser = $user->uid;
  //get profile url for that you can use $user_id as user id
  $profileUrl = arg(1);
  // compare usernames to determine whether the user is on their own profile.
  if($currentUser == $profileUrl) {
    //user is on their profile, display link
    $profileUrl = "i'm home";
  }
  else {
    $profileUrl = "away";
  }
  return $profileURL;
}


Using select expressions or derived field in Views2 as fields? Is it possible to use a select expression or a derived field as a field in Views2 in Drupal 6?

The advanced help documentation seems to indicate that perhaps it is possible:

  though it is very common to use
  non-fields to display data that isn't
  directly in a field, such as data
  arrived from formulae...

But they don't provide examples there.

What I mean is I'm looking for some way to indicate that the query should be

SELECT field1, CONCAT(field3, ', ', field4) AS alias1, IF( field5 > 10, 1, 0) AS alias2 FROM table ...

Can I specify the expressions alias1 and alias2 in native views2 functionality? If so, what is the syntax?

Or do I need a separate module?

It looks like what I need to do is create a Custom Field Handler. From the linked article, a definition such as this

<?php
class scheduler_handler_field_scheduler_countdown extends views_handler_field {
  function query() {
    $this->ensure_my_table();
    $this->node_table = $this->query->ensure_table('node', $this->relationship);
    $this->field_alias = $this->query->add_field(NULL,
      'IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
        publish_on - UNIX_TIMESTAMP(), NULL)',
      $this->table_alias . '_' . $this->field);
  }
}
?>

adds this to the query

SELECT node.nid AS nid,
       node.title AS node_title,
       IF(publish_on AND publish_on > UNIX_TIMESTAMP(),
           publish_on - UNIX_TIMESTAMP(),
           NULL) AS scheduler_publish_countdown
    FROM node node
    LEFT JOIN scheduler scheduler ON node.nid = scheduler.nid
    WHERE node.status = 0


How to specify the default installation profile I want to specify my custom installation profile as default one, like acquia profile in acquia drupal.

For example when installing acquia drupal, acquia profile will be selected by default thus choose profile and language will be skipped. Now I need to overcome this, because I'm, writing my installation profile in the acquia drupal. So I should set my custom profile as the default one instead of acquia profile.

How can I achieve this?

oops its my mistake.

D7 by default doesn't consider standard and minimal profiles, so its selects acquia profile by default.

I had problem with my custom installation profile, that's why it doesn't showed up in the profile list.


Modifying HTML of menus In my Drupal 7 template, this one line of code spits out all my menues:

<?php print render($page['header']); ?>

I want to remove extraneous wrapper tags from my menus; for example, Drupal 7 prints out one of my menus as:

Top menu

Membership

Calendar

Newsletter

Contact Us

I want to simplify it to something like:

Membership

Calendar

Newsletter

Contact Us

How do I remove unnecessary wrapper tags?

I'm not sure if there are template hints that work exactly with this, but you can place block.tpl.php and region.tpl.php (in modules/block/ and modules/system/ respectively) in the theme directory, and then use conditions to sort through which areas you want to be marked up the default way and regions you don't want to be marked up that much.


image_image plugin does not exist Trying to build a content module (= a module that adds a content type) for drupal 8 but I get the following error on install, the error isnt very informative and Im stuck. The module has a image upload field, and I assume its whats throwing the error but the code for it is copied out of drupals export

  Drupal\Component\Plugin\Exception\PluginNotFoundException: The "image_image" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Code is at the following
https://github.com/ShadyRabbit/drupalIssue

Update: I found the answer myself: entity_view_display was the same as entity_form_display resulting in the error of the content type

Somewhere you specified image_image, a widget, formatter or field type. There is no such thing, find it and correct it.

You get better help if you share your code.


Drush sql-sync: Access denied; you need the SUPER privilege for this operation I am trying to use drush to move my live database down to my dev database. I am doing

drush sql-sync @live @devel --sanitize

However I get the error:

  "ERROR 1227 (42000) at line 1478250: Access denied; you need the SUPER privilege for this operation"

I think it is due to the views in the db from uc_views module, is there any way around this?

I also tried to do

drush sql-sync --skip-tables-key uc_views @live @devel --sanitize

where uc_views is an option declared in drushrc.php with an array of the db views from uc_views, but to no avail.
Here is my drushrc.php

$options['skip-tables']['uc_views'] = array('uc_order_products_pair_vw', 'uc_order_products_qty_vw', 'uc_order_products_user_vw');

I would actually prefer to copy the database views from uc_views rather than exclude them if that is possible.

The user defined in settings.php on one or both sides of the sync lacks the SUPER privilege on the database.

Log in as the mysql root user and do

GRANT SUPER ON [db_name] TO '[username]'@'localhost' IDENTIFIED BY '[password]';

If you are security-conscious (as you should be), it's worth taking the following into account:

  Do not grant the PROCESS or SUPER privilege to nonadministrative users. The output of mysqladmin processlist and SHOW PROCESSLIST shows the text of any statements currently being executed, so any user who is permitted to see the server process list might be able to see statements issued by other users such as UPDATE user SET password=PASSWORD('not_secure').


How to add a list of stock and node reference to create the perfect stock of beers? I'm creating a Drupal site that is able to follow the stock of your beers.

For beers, I have a Beer Content type wth all info on the beer, it's OK.

Now, for each user, I want to give the possibility to create a list of beer and the number of beer user has in fridge. How can I do that?

I was thinking of making these Content Types:

InStock (fields : int + node reference to beer).
MyBeers (fields : node reference to InStock).

But with that, user has to create one InStock for each beer and then after that create one MyBeers and reference to all it's beers, so it isn't the good approach.

I don't want to make custom module if it's possible.

Ideally in fact, in my perfect works, I can add directly a List of (node reference to beer + int items in stock) into the InStock but I don't know how to do so.

Only use the Flag module, so that your users can just "flag" the nodes related to your Beer Content type. With such approach, there is no need for the extra content types InStock and MyBeers that you are considering (a commonly known best practise in Drupal is to try to keep the number of content types to a minimum).
Some details about the Flag module (from its project page):

Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.
Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

Create a flag that can be used by each user individually (not a "global" flag), so that each user can flag the Beer Content types, and which would be the equivalent of your "MyBeers" type you had in mind. And by using the technique of Attaching fields to flags, you could create a field corresponding to that "int" field of your "InStock" content type you had in mind.
Super easy and straight forward. And by using the Flag module, as a bonus you get all those amazing features about integrations with other modules such as Rules, Views, Views Bulk Operations (VBO), etc. Some samples:

Build a view to see what is in "your" fridge, and or apply mass updates using the VBO module.
Use the Rules module to send eMail reminders when your stock "is running low".

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about this module. Especially the Video about Creating non-global flags: between about 6:00 and 8:30 it explains how to add a Flag-related relationship in your view, so that you can then also use flag related data in your view (for fields, etc). The same video (near the end) also shows how to combine this with VBO.
Some more suggestions related to some additional (non-global) flags I recommend you to create, which would probably enhance the beer-experience of your users even further:

My favourites: a flag to indicate the favourite beer(s) of a user (... like "Leffe Blond" ...)
Looking for it: a flag to indicate the beer(s) a user is looking/searching for, like where to buy such beer (like "Celis White" ...).
Tasted it: a flag to indicate the beer(s) a user ever tasted, e.g. to create a contest about nr of different beers somebody every tried (like "400" ...), or an inventory of beers that are still on your whish list to ever try (like "empty" ...).


assign role after registration (male female) I need users to check male/female option when creating an account. Then I need to automatically assign a role male/female to the users.
How can this be achieved? Is there any module which I can use?

You can add a field to the user entity at admin/config/people/accounts/fields. Let's use the List (text) type and call it "field_gender" with the possible values of female|Female and male|Male. Display it on the user registration form.

Then you can use Rules module to react e.g. when someone creates an account and perform various actions. The idea is that you create two different rules for assigning either the male or the female role.

Install Rules if you haven't already done so, and create a new
rule at admin/config/workflow/rules/reaction/add.  Choose a name
for it and tag it if you want. The rule should react on the following
event: After saving a new user account.
Add a condition in the next step and choose Data
comparison. Then type or select account:field-gender in the data
selector.
Choose the data value in the next step to be Female.
Now your condition is ready, add an action, select Add user role,
then choose the female role.
Repeat these steps and create a rule
for assigning the male role.


How would we add Drupal Core modules as dependencies on custom modules post 8.6.2? We recently updated to Drupal Core 8.6.2 and noticed there are changes to module dependencies. We are noticing that drupal: is added before the module names. We were unable to find any documentation that further explains it.

How would we add Drupal Core modules as dependencies on custom modules post 8.6.2?

mymodule.info.yml example before 8.6.2

type: module
name: my module
description: my custom module
package: 8.x
core: 8.x
dependencies:
  - field
  - image

mymodule.info.yml example after 8.6.2

type: module
name: my module
description: my custom module
package: 8.x
core: 8.x
dependencies:
  - drupal:field
  - drupal:image

If you're referencing a recent change in a core module, it was a style/formatting change.

Adding namespaces for dependencies has been in core for a while. The {project}:{module} format is a better practice for removing ambiguity in the event of module/project machine name overlap, but both will work.

For documentation reference, see Let Drupal 8 know about your module with an .info.yml file under the example section for dependencies:

    dependencies - A list of other modules your module depends on. Dependencies should be namespaced in the format {project}:{module}, where {project} is the project name as it appears in the Drupal.org URL (e.g. drupal.org/project/views) and {module} is the module's machine name. Dependencies can also include version restrictions, for example webform:webform (>=8.x-5.x). Note that if your module has dependencies on other contributed modules or libraries, these should be declared in the module's composer.json file.


what about multiple files and their archives in sites/default/files/[css] and /[js]? /sites/default/files/css & /sites/default/files/js
my drupal sites above folders are filled with numbers of css and js files respectively and also with their archives. What are these meant to? and what they have effect on the performance of my site?

One thing i know when i explore my css in fireug, most of contents are refferd from these and even repeating and over-rided contents also appear.
How i can overcome this problem so no css over-ride?
following is the image of css ove-riden, their actual path is sites/all/theme/themename/css but here these are from sites/default/files/css

The files are created when you enable 'Aggregate and compress CSS files.' and 'Aggregate JavaScript files.' The do have a positive effect on the performance since the browser has to do fewer http requests.

The overrides are normal as well, and they also happen when aggregation is turned off. Avoiding those means you probably have to re-write most of the css from core.


How to access $user_profile in page.tpl.php or $page in user-profile.tpl.php in Drupal 7? I need to change layout of a profile depending on user's field. So, I need to either include regions in user-profile.tpl.php or access $user_profile to test that field in page.tpl.php.

I've seen this done, but can't find it now.

As for including regions in user-profile.tpl.php here how you do it.

In your custom theme add the following code to template.php file

function mytheme_preprocess_user_profile(&$variables) {
  // List of all regions for the current theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {
    // Add content to $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then copy user-profile.tpl.php to your custom theme and then place the following code between any HTML tag.

print render($region['region_name']);


Module for extracting information from remote site? I want to give user better experience when filling in forms. They are prompted to fill information about some product, like price, description, image, etc...

My idea is that I'll let them just copy & paste URL to (for example) amazon and the website will itself pre-fill all the fields (price, description, ...).

So I would basically need set of regular expressions per field, per remote site. This is not a problem, I can cover 90% of our user daily used websites. If this mechanism fails, then user still will be able to fill the information manually.

My problem is that I cannot find any drupal module that is capable of doing something like this. Does anyone know how to (simply) achieve this goal? Or do I have to write a module for this?

I think that Feeds XPath Parser and Example Web Scraper could be a guidance to your needs.


How to render a Commerce pane programmatically? I've the following code:

$panes = commerce_checkout_panes();
$payment_pane = $panes['commerce_payment'];

which loads one of Commerce pane which contains the array like:

array (size=15)
  'title' => string 'Payment' (length=7)
  'page' => string 'review' (length=6)
  'file' => string 'includes/commerce_payment.checkout_pane.inc' (length=43)
  'base' => string 'commerce_payment_pane' (length=21)
...

How do I render that pane programmatically?

This is part of commerce_checkout_form_review form (which is normally present at /checkout/%/review), but I need to render only payment part (checkboxes) but in different place.

Panes are forms. Run them through drupal_get_form but you'll need to pass in some extra options:

require_once drupal_get_path('module', $payment_pane['module']) . '/' . $payment_pane['file'];
$order = commerce_order_load($order_id);
$payment_form = drupal_get_form($payment_pane['callbacks']['checkout_form'], $payment_pane, $order);
$output = drupal_render($payment_form);


How do I remove a character from the replacement pattern? In view I call the field field_store_car_model

settings of this field:

formatter: link
result URL is:veyron-164

So far as expected.

But I need this URL: vehicles/veyron-164.
Because of this I have to rewrite the link.

I check rewrite result, format is plain text, I write in the field vehicle/[field_store_car_model]

Result here: vehicles/veyron-16.4.

Now I have this punctuation in the URL! where does the decimal point come from?
From my vocab because view grabs the term BEFORE pathauto cleans it up.

So how can I get rid of the decimal point?
I am sure there is some PHP but WHERE I have to put the PHP code?

Any ideas?

I'm not sure I completely understand your question. But I'm guessing this is what you're looking for.

In Views, under FIELDS, click on the name of your field
Click on REWRITE RESULTS
Enable Output this field as a link
In Link path, insert something like vehicles/[field_store_car_model], where
[field_store_car_model] is one of the available Replacement patterns.

Hope this helps.


How to apply node access rules when querying menu_links table I am creating a custom block which displays a menu.  The menu is constructed by retrieving certain menu links from the menu_links table in the database. It has occurred to me that building it this way could introduce a security issue, in the situation that a user does not have permission to view a certain node, but that menu link is still included in in the custom block.

I am wondering if there is some way of filtering results obtained from menu_links table based on current user role?

Menu links are currently being retrieved with queries like this one:

// Get all siblings of parent menu.
$siblings = db_select('menu_links', 'ml')
  ->fields('ml')
  ->condition('plid', $target['plid'])
  ->condition('hidden', 0)
  ->orderBy('weight')
  ->execute();

Actual menu structure is being constructed as a render array (basically each menu item is a link within a div wrapper).  Below is example of how a menu item is being constructed:

foreach ($siblings as $sibling) {
  $link = l($sibling->link_title, $sibling->link_path);
  $menu_item = array(
    '#type' => 'container',
    '#attributes' => array(
      'class' => array('nav-level0'),
    ),
    'content' => array(
      '#markup' => $link,
    ),
  );
  $menu[] = $menu_item;
}

Yes, menu_get_item() will set return an access element that notes whether the current user has access.

  $siblings = db_select('menu_links', 'ml')
    ->fields('ml')
    ->condition('plid', $target['plid'])
    ->condition('hidden', 0)
    ->orderBy('weight')
    ->execute();
  foreach($siblings as $sibling) {
    $menu_item = menu_get_item($sibling->link_path);

    if($menu_item['access']) {
      //Current user has access
    } else {
      //Current user doesn't has access
    }
  }


Is it possible to pass dynamic values in tokens in Drupal 7? When using tokens, I would like to be able to use a format similar to the following notation so I can provide the needed flexibility in how a content author can invoke these modals with minimal code experience.

[modal:view:<term_id>:<text_string>]

An example of this token in use would be:

For more information, [modal:view:33:"click here"].

What should happen from here is that I can grab the <term_id> and <text_string> and incorporate them in the output of the token replacement.

An example for the expected output would be something along the lines of:

For more information, click here.

Is this possible, and if so, how would I construct the hook_tokens function to handle these dynamic values?

Might have worked myself into the solution via trial-and-error.

function hook_tokens( $type, $tokens, array $data = array(), array $options = array() ) {

    // Returnable markup...
    $replacements = array();

    // Handle Tokens...
    if( $type == 'modal' ) :
        foreach( $tokens as $name => $original ) :

            $name_parts = explode( ':', $name );
            switch( $name_parts[ 0 ] ) {

                case 'view':

                    // Handle modal:view tokens...
                    if( !empty( $name_parts[ 1 ] ) && !empty( $name_parts[ 2 ] ) ) :
                        $value =
                        ''.
                            ''.trim( trim( $name_parts[ 2 ], '"' ), "'" ).''.
                        '';
                        $replacements[ $original ] = $value;
                    endif;

                    break;

            }

        endforeach;
    endif;

    return $replacements;

}

There's a lot of fail-safes missing from this code, but I just want to make sure this falls under best practice and that I'm not doing anything that would be considered taboo by community standards.


How to change the image style for image preview in node-add/edit form? IN a related question, "How to set image style for media browser in node edit form?" one response noted that "Once you have chosen the image and clicked save and the overlay is closed, images are display in the "Media thumbnail" image style."

How can I change this automatic behavior such that the preview image is displayed in my custom image style?

If you are using the Media module, I couldn't find a way to change it so it doesn't use the "Media thumbnail" image style. But what you could do is edit the "Media thumbnail" image style by going to /admin/config/media/image-styles/edit/media_thumbnail and clicking on the override button which will let you edit it to your liking. (Tested on Drupal 7)

If you're not using the Media module, you can by going to your content type's Manage Fields and clicking on edit for your image field. Scroll down a bit until you see Preview image style


Disable responsive Omega I am on Omega 4. How do I disable responsive web design for my sub-theme? i.e. fixed grid yet I can still use singularity or other goodies in Omega.

I was from Omega 3.

I would like to quickly get the website up without spending too much time tweaking for RWD.

Create a custom layout (https://drupal.org/node/1936980)
Comment (or remove) the "breakpoint" in the scss (or sass).


Add checkbox in node menu settings I would like to add one checkbox in Menu settings at node /node/add/{Content types}

I am not sure how to do that.
I need to use Form and Controller.

What form I need to include? This is some of them.

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

And after I need to implemente Implements hook_form_FORM_ID_alter().

Is my thinking ok?

If I understand you correct, you want a menu to appear only at a certain content type? It is not done from there.

In Drupal 8 each menu is a block; After you have created the menu regularly with the native API unchanged, just add the block to the desired region and then set that block to appear only in a certain region you want it to appear in (You should see such an option in the block's conf page).


multisite: only changing name of the website I have a multisite up and running, which has completely different domain names but absolutely the same content (I'm using filters to filter the content by domain).

Everything works splendid with almost no redundancy. However, the only thing keeping me from rejoicing, is that I cannot change the name of the website domain-wise.

So basically, my question is where I can set this up, or rather:
Is there a way to override the page's name on drupal load?
And if there's not, can anyone tell me which table the site's name is getting stored, so I can domain-prefix it?

Do you have a settings.php file per site ?

If yes, you can add inside $conf['site_title'] = 'My Site name' this variable his stocked in the table variablebut you can override it directly with settings.php.


{{ language }} variable not available in block template We are trying to generate a language dependent link in a custom block we created though the UI and placed it into a region.

If I {{ dump(language) }} in page.html.twig, I've got it there. But not in the block. Is this by design? Where/How can I get access to it?

You can solve this with a preprocess hook:

mytheme_preprocess_block(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['language'] = $language;
}

The language variable will then be available in your block template as it is in the page one.


Cache controller with json response I want cached a controller that returns a json..
I try this:

$build = array(
  '#cache' => array(
    'contexts' => ['ip'],
  ),
);
return (new CacheableJsonResponse(['test'], 200))->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));

But i get an exception:

LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\Core\Cache\CacheableJsonResponse. in Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext() (line 154 of /Applications/MAMP/htdocs/finder-cms/docroot/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php).

The controller from your question runs without exception:
public function demo() {
  $build = [
    '#cache' => [
      'contexts' => ['ip'],
    ],
  ];
  return (new CacheableJsonResponse(['test'], 200))->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
}

Result:

["test"]

To produce the exception you need a controller like this:
public function demo() {

  $build = ['#markup' => 'early rendering'];
  $markup = \Drupal::service('renderer')->render($build);

  $build = [
    '#cache' => [
      'contexts' => ['ip'],
    ],
  ];
  return (new CacheableJsonResponse(['test'], 200))->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
}

Result:

LogicException: The controller result claims to be providing relevant
cache metadata, but leaked metadata was detected. Please ensure you
are not rendering content too early.

This may not always be that obvious. Another example is when you try to get an url from an url object, see this answer https://drupal.stackexchange.com/a/187094/47547

Add an URL with cacheable metadata to a response
This is how you avoid the exception, when you render an url for a json response, and at the same time add the correct cache metadata to the response:
  $generated_url = $url->toString(TRUE);
  $response = new CacheableJsonResponse(['url' => $generated_url->getGeneratedUrl()], 200);
  $response->addCacheableDependency($generated_url);
  return $response;


Update webform without losing existing webforms I'm using webform 7.x-3.20 version and I want to to upgrade it to 7.x-4.x, but I've 7 to 8 existing webforms whenever I update this I'm losing my previous webforms cause of changed table structure. If is there any easiest way to update then please let me know. It'll be appreciated.

In the comment section of the documentation there is written: Note that you must be running the latest 3.x version of Webform (for either Drupal 6 or Drupal 7) before upgrading to Webform 4.x.


Search for user by specific 12 digit ID number I'm building some functionality into a drupal 7 site that will let users search for another user, by a 12 digital identity number (for example: ZD-3423FGIO-XZ)

How would I go about doing this? Would I need to create some custom code to insert a new field in the user table that creates a custom number then modify the search functionality, or would I just use a module to do this?

Any help would be great!

It seems to me like a typical use case for Field UI and Views. No code needed.

Video tutorials on Drupal 7, (Fields from episode 9), and Views.


Libraries API not working in my module I'm writing a module that will call some external php libraries. When I was searching for a way to import the library I found the Libraries API. After reading some documentation about the module and core features I found some example code.

When I implement it in my module nothing happens.
My movies.module file contains:

/**
* Implements hook_libraries_info()
**/
function movies_libraries_info()
{

  // This array key lets Libraries API search for 'sites/all/libraries/example'
  // directory, which should contain the entire, original extracted library.
  $libraries['imdb'] = array(
    // Only used in administrative UI of Libraries API.
    'name' => 'imdb',
    'vendor url' => 'https://github.com/tboothman/imdbphp',
    'download url' => 'https://github.com/tboothman/imdbphp/releases',
     // Default list of files of the library to load. Important: Only specify
    // third-party files belonging to the library here, not integration files of
    // your module.
    'files' => array(
      // For PHP libraries, specify include files here, still relative to the
      // library path.
      'php' => array(
        'bootstrap.php',
      ),
    ),
    // Optional: Register files to auto-load for your module. All files must be
    // keyed by module, and follow the syntax of the 'files' property.
    'integration files' => array(
      'movies' => array(
        'php' => array('bootstrap.php'),
      ),
    ),
  );
  return $libraries;
}

No errors are thrown when enabling my module when the library is not installed.

How can my module load the external PHP library using the Libraries APi?

Add a composer.json file to your movies module & name it your custom module's name:

{
  "name": "drupal/movies",
  "type": "drupal-module",
  "license": "GPL-2.0+",
  "require": {
    "imdbphp/imdbphp": "*"
  }
}

Add a new line to the merge-plugin include array in the composer.json of your Drupal ROOT with your module's composer file path:

"extra": {
  "merge-plugin": {
    "include": [
        "core/composer.json",
        "modules/custom/movies/composer.json"
    ]
  }
}

Enable the movies module
Run composer update & composer dumpauto in Drupal ROOT. This will install & autoload the new dependencies in your vendor directory.
Now you can use the classes provided by this library. In your case for example:

$title = new \Imdb\Title(335266);


Hook to track commerce product category view I am creating a drupal commerce module for tracking users. I want to access a hook in drupal commerce on product category page. Went through most of the documentation but was not able to find the hook to listen to for product category page view.

Well, since you're dealing with Drupal, there's no "product category page"s ... per say ... but there are taxonomy terms that are often used for catalogs and attributes. So, you could, in theory, use hook_entity_view() to tap into when a taxonomy term is being viewed.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_view/7

If you're building a module, I could see you building an interface that lets people assign urls and taxonomy terms that would potentially "make" the catalog pages trigger whatever it is you want to trigger.

Ultimately, though, there's no hard and fast rule on how to build a commerce store, so there's nothing for you to hook into.


Module to convert a decimal amount of US Dollars to an equivalent amount of BitCoin I am still new to Drupal and am looking for a module that does the following: convert a decimal amount of US Dollars to an equivalent amount of Bitcoin.

Is there such a module that can handle this or would I have to code this from scratch?

More info:

Accepts a decimal based argument in USD
Submitting the form sends a request to a 3rd party API to convert the dollar amount to BitCoin
Module should create a means to store any API connection details required to communicate with your API key in the database
Module should pull this value from the database when making a request to the API

It seems you're looking for the UC Bitcoin module

This module provides an alternative 'payment gateway' that enables your clients to pay in the equivalent amount in BTC (Bitcoin currency)
It does this by doing a current market exchange rate lookup of your stores default currency and then allowing an option to let people pay in the equivalent BTC amount.


Create entities when user account created I am looking for a hook to fire off an Entity creation method (for an unrelated item that pertains to the user) when a user registers for the site. I'm divided between hook_form_user_register_form_alter and hook_user_insert. What's the best approach here, and i'm wondering which one is the best to use here.

After doing my due diligence, I chose to use the hook_user_insert() to extend my logic for the entity creation. It fires when a new user is verified and added to the users table/entity.


old website to new website Old website is running on live. The version of the old website is drupal 6. Last two months ago, I receive a task to create new website by using drupal 7 to replace old one. That time i have 0 knowledge of drupal. Now ready to replace old one and face problem. Old website is drupal 6. New one is drupal 7. Sure have problems.That why i decide to duplicate old website and database to sub domain. Purpose is to upgrade old website from drupal 6 to 7. Old website in sub domain display succesfully, but the link all point to site listing of the sub domain

FYI, I had managed to replace new website D7 to old website D6 successfully. However, the solution is not base on migrate D6 To D7. This question will be remain unanswered...

First thing you should do is contact your web hosting provider and see if you can go back to working copy of your website. After you have a working copy of your website download that into a local environment. I would recommend to this either a Mac or Linux machine (ubuntu os what I user).

Once you have your local environment you can start trying migrating from D6 to D7. You should never try an migration a production site.

From here you can use drush sup to upgrade your website. After your website is been successful upgrade from D6 to D7. You should consider uploading that to your web hosting provider.


How to import an external database to D8 and create a search form? I have a MySQL database with 2000 doctors, which are accessed classicaly through a HTML form and PHP. With the form you can search with criterias like ZIP, town, target group, treatment, languages, etc. Then a result list with doctors is shown and when clicking on one a profile page is opened with all the details of the doctor.

How can I migrate this to Drupal 8? I already read a lot and often Feeds is sugggested, but unfortunately it is not yet ready for Drupal 8.

The best and most flexible option at your disposal will be to use the Drupal Migrate module. It's included by default in D8.

The steps you'll have to follow is as below:

Migrate your data from MySQl to a Drupal content type or an entity. You could also consider exporting your data to CSV and import from the CSV.
If you are not expecting very large traffic, use views and exposed filter to implement your search form with filters. If you are expecting the more traffic and scale user search_api and use something like Solr in the backend.

Some of the links where you can get started:

Migrate to Drupal 8 from MySql.
Migrate to Drupal 8 from CSV file.
Official Migrate API documentation.

I am assuming you already know what content type, entity, views, exposed filters etc are. In case you don't know any of it, plenty of resources are available online.


Have you seen transliteration module ?  The project summary says it could be used with pathauto 2.x to use transliteration for URLs.


Tell a field to be translatable I have a module with a plugin block. In the blockForm I create all the fields that I need for this block. In the CMS I realized that only the title of my block is translatable. I need some of my custom fields to be translatable. I just can't find how to do that.

public function blockForm($form, FormStateInterface $form_state){

    [...]

    $form['exit_link']['full_schedule_link'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Full Schedule Link'),
      '#description' => $this->t('Enter the schedule node, ex: (/node/20)'),
      '#default_value' => isset($this->configuration['full_schedule_link'])?    $this->configuration['full_schedule_link']:'',
      '#maxlength' => 256,
      '#size' => 64,
      '#weight' => '1',
      '#translatable' => true // <-- NOT WORKING
    );

    [...]

}

Anyone has an idea how to do this?

You define that through the config schema, not the form.

See https://www.drupal.org/node/1905070, use type: label (weird know but that's how it is called) not string and type: text for textareas.

If you have no config schema yet, look at other modules providing blocks with configuration, like aggregator.module to see how to define that.


Drupal Commerce: Create advanced add to cart form block in views With Drupal Commerce product variations, certain values will update without a page refresh based on an attribute selection. For example, changing a color attribute may update the product image.

I want to the display the add to cart form in a views block using the method described in the following video https://drupalcommerce.org/questions/10801/display-add-cart-separate-block . At the same time I would also like to include other product fields in the block, such as price.

I am finding that the block is static and does not update based on an attribute selection. And I have tried enabling Ajax for the block without success.

Is is possible to create a dynamically updating views block to replicate some of the functionality of a commerce product display?

Ajax on the block only works for the views pager and the table sorting. You have to simulate that behaviour by triggering the ajax call when an attribute is selected.

Alternatively try with Ajax Block, Block Refresh, or Authcache Blocks, and see how they trigger the Ajax load on page load, and do the same on attribute selection.


Why is accessing paragraphs slow? Is there a better approach? I'm trying to get the target_revision_id of a paragraph within a paragraph within a node. I can do this, but it is slow.

$all_nodes = db_select('node','e')->fields('e',array('nid'));
$all_nodes->condition('type','author');
$data = $all_nodes->execute();
$the_result = $data->fetchAll(\PDO::FETCH_ASSOC);
foreach ($the_result as $node){
    $node_load =  \Drupal\node\Entity\Node::load($node['nid']);
    foreach ($node_load->field_paragraphs as $item) {
      $para_id = $item->entity->field_affiliation_details->target_revision_id;
      //then, store the para_ids in some array
      $para_ids[] = $para_id;
    }
}

Performing the reference "$item->entity" makes my app slow down by a lot. It is really just Kilobytes of data. Is there maybe a better approach to this?

Thanks for any help.

Well after fiddling around with it some more, I suppose the best answer here is to just cache the variable  $para_ids using \Drupal::cache() and then update it whenever there is a node/entity update or insert. I could look into database optimization to see what is actually happening with the $item->entity reference, and put an index on the joins/where statements but I am not very confident that is the best way.


Archive block for nodes using Views How can I create an archive block like this, only for Drupal 7 (views 3)
http://chrisshattuck.com/blog/how-create-monthly-archive-block-drupal-blog-views

I think you can use the "Contextual Filter" for this. Choose the "Content: Created date" as the contextual filter. Then in the filter settings, choose "Display a summary" and save the view. Maybe this helps you to start with this.


Cache_page table gets massive My cache_page table fills up immensely. I see that the expiry field has values = -1. I assume that means it never expires. Which could be why the table fills up so much.

I wrote a hack to get around this, but would really like to know why this is happening so I can fix the root cause instead of adding a hack?

You can set a lower limit than the default 5000 for the number of cache items that are stored in the page cache bin:

settings.php:

$settings['database_cache_max_rows']['bins']['page'] = 500;

See this change record: Database cache bins are now fixed size — no more unlimited growth


Creating Interactive Charts I'd like to create a page in D8 that allows my users to input some values. Once they've done that I'd like them to click a button that then creates two pie charts for them based on the values they input.

I see the Charts Module is not available for D8. Wondering if anyone here has suggestions for how best to accomplish this in D8 as of this writing?

Have a look at the Easychart module, which has an official release for Drupal 8 (also for Drupal 7).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
It supports pasting of CSV data to create charts from it.
overheid.vlaanderen.be contains some real world examples of a Drupal website (not yet D8 though) with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

Resources:

Module documentation.
Video demonstration.


Add CSS class to view fields I would like to add a CSS class to fields in a view. The view in the screenshot takes the title, the summary, the date and the tags of articles that are published to the frontpage. I know how to add a class to the whole article in the GUI, but I want to add a class to fields on the article in the view.

I have made changes to existing CSS classes, but they appear on other parts of the site.

I found the answer on a video

Go to 'Edit View'
Click on the field you want to add a CSS class to
Go to the 'Style Settings'
Check 'Customize field HTML'
Check 'Create a CSS class'


Link to Views page with token? I've got a Views (machine readable name: e.g 'views-events-page') page that I gave a URL (in the path field, e.g. 'events').

I want to link to this Views page from Link field. Of course, I can paste the path 'events' into the link field. But supposing I would change the path of the Views page the link will be broken. Is there any chance of using a token to get the path of this Views page, like [views:view-events-page:path].

I was not lucky asking the search engine of choice the right question. I did not find any useful

you can create a custom token , another helper link

or use
Custom Token module
then get views url  with

$view = views_get_view('viewname');
$view->set_display('display_name');
view->get_url(); // if not work try this  $view->get_path()

Learn how to create custom token according to below example

 /**
 * Implements hook_token_info().
 */
function my_module_token_info() {

  // Add tokens.
  $site['city_name'] = array(
    'name' => t('Token Name'),
    'description' => t('Token Description'),
  );

  return array(
    'tokens' => array(
      'site' => $site,
    ),
  );
}

/**
 * Implements hook_tokens().
 */
function my_module_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

 if ($type == 'site') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'city_name':
          $city_name = variable_get('city_name');
          $replacements[$original] = $sanitize ? check_plain($city_name) : $city_name;
          break;
      }
    }
  }

  // Return the replacements.
  return $replacements;
}


Views: Computing user's age "on the fly" Is there a way to compute the age of a user on the fly in the "rewrite result" section of a date field?

I am trying to avoid computed field and having to use cron on that one. What I would like to achieve is having the age calculated and displayed on the fly in a date field (date of birth) included in a view.

Any and all input on this will be greatly appreciated. Thank you. :)

This might help you with the "on the fly" age calculation:

PHP calculate age
Calculate age based on date of birth

Then use the Views PHP module to implement it in your view. Or if you want to use the SQL method you could use the Views Raw SQL module.


Views, Pathauto and contextual filters My question is rather simple, but I didn't manage to find anything that can help.

Summary of my setup :

Pathauto
Views
Entity Reference

So I have various custom content types, which I want to organize using views. But for SEO reasons, I want them to use simplified URLs, generated by Pathauto.

These content types are all cross-referenced using Entity Reference, and when I try to configure my View "Page" using the node ID as contextual filter, it works. But when I try to use Pathauto, nothing happens.

So how can I use Views, basically when going to http://example.com/fruits/banana and pass "banana" argument to Views, to filter my content ?

I am searching for it for almost a week, and I am lost.

I couldn't understand what you exactly need but i guess that "banana" is the title of your node, the same value that you are using when you set up the pattern in pathauto settings, right?

So in this case you would have to set Node Title has a contextual filter, and then on "When the filter value is NOT available" you have to set  Provide default value > Raw value from URL > specify the position of your argument in the URL.

It would be nice if you give us more information about what do you need, please


Display certain field values of submissions from multiple webforms in one view I have two separate webforms, and I want to be able to display all submissions from both webforms that have the same value of a specific field. I also want different fields to be displayed based on what form they're coming from.

For example, both webforms have a field called area.
I would like to display the submissions of both these webforms if they both have area set to the same value. Amongst these submissions, if they're from form 1, I want to display the values for field1,field2,and field3 in the view. If they're from form2, I want to display the values for field4,field5, and field6 in the view.

Is there a way to accomplish this in a view?

You may want to read this: https://www.drupal.org/node/2497183

  Views cannot display information from more than one webform at a time
  unless the webforms share the same components.

  One solution would be to add order# as a hidden field so that all
  webforms have a component by this field key. I haven't tried having
  mixed component types for with the same field key, but I suspect it
  will work, at least with some view configurations

You may wind up having to create a template for a module to get the report you are looking for.

Drupal answers actually already has a post on this:
Multiple Webforms in one View


How to redirect a user to the Last Domain Browsed I have a question, what will i do to save the last domain a user was on either on a cookie or a session or anythin else that will work so that whenever they type the main domain they are redirected to the sub domain they were on last even if the browser is closed. i have about 3 sub domains and the main domain. i am using domain access. for example

main.com <== TLD
sub.main.com <== Sub Domain 1
sub2.main.com <== Sub Domain 2

user types in main.com and was browsing sub.main.com yesterday and instantly gets taken to sub.main.com
 and on another machine user types main.com and gets taken to last domain e.g. sub2.main.com
Help!

You need to use Cookie as Sessions will be lost once browser is closed.
You can use hook_init() or hook_boot() or page-front.tpl.php

function hook_init(){
 $domain_last_accessed = $_COOKIE['domain_cookie'];
 if($domain_last_accessed != "" && $domain_last_accessed != $_SERVER['HTTP_HOST']){
 // Check if cookie is set and previous visited was not this domain then redirect
 // redirect using drupal_goto() or Header()
 }
 else{
 // Check for Cookie and set if empty, this might be the first visit or cookie was destroyed
 // SetCookie with $_SERVER["HTTP_HOST"]
 }
}

If you want it to be machine independent then you may need to store last accessed domain in DB and note that this will only help authenticated users.


How to get related nodes for node reference? I have added related nodes using Node Reference module provided by the references module.
Now I want to retrieve all the related nodes. So I am looking for a function which takes a node id as input and returns all the related nodes.

Is there any function provided by Drupal API or reference module which helps me getting nodes related to a node?

I tried searching in the module functions but I found nothing.

I don't know of an API function specifically for that but it's fairly simple to implement one using existing API methods:

function get_related_nodes($master_nid, $field_name) {
  // Load the 'master' node
  $master_node = node_load($master_nid);

  // Get the node reference items attached to this node
  $items = field_get_items('node', $node, $field_name);

  // Loop through and grab the nids
  $nids = array();
  foreach ($items as $item) {
    $nids[] = $item['nid'];
  }

  // Return the fully loaded reference nodes
  return node_load_multiple($nids);
}


Username converted to us-ascii (unix-style) I want to convert unicode characters in user names to us-ascii. I.e my first name is Søren and my last name is Sjøstrøm. It should be converted to soren.sjostrom (unix style) as the user name. How do I do that?

If you only want to transliterate non-ASCII European characters (like those used in Nordic, German and French names), you can use the PHP function strtr. E.g:

$name = strtr($name,
   'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ',
   'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuuyty');

If you want to do romanization of a wider range of non-ASCII alphabets (cyrillic, greek, etc.) take a look at the contributed project Transliteration.

While this is specifically to transliterate file names to US-ASCII, at its core is UTF-8 normalization (based on UtfNormal.php from MediaWiki) and transliteration (based upon Sean M. Burke's Text::Unidecode).  You should be able to use the same libraries for romanization of names and other strings.


Use underscores in menu machine names Why cannot I use underscores in menu machine names?
For example menu_xpto is an illegal machine name for a menu.

What is the problem with using _ in a machine name?

Menu has an inconsistent pattern for machine names with most other parts of the system, that was simply not unified when converted to use the config system.

There is no reason, but it also can't be changed now as existing menus would then be invalid.


Fatal error during add a field to a content type with a custom Field Type I'm working on Drupal 8 and I create a custom field type so

When I tried to add a field to a content type Drupal give me this error

  Fatal error: Cannot redeclare class Drupal\any_to_show\Plugin\Field\FieldType\AnyToShowItem in /var/www/public/sites/all/modules/something/src/Plugin/Field/FieldType/AnyToShowItem.php on line 105

I'm confused because it suppose that the file is the definition and it says that I'm redeclaring the class, I search whole site but nothing.

I was grateful if somebody can help me.
thanks in advance

This happened to me, and the solution was making sure that the file name matches the class name defined within, so in your case, the class name MUST be AnyToShowItem.

This is because the PSR-4 auto-loader would be trying to load .../sites/all/modules/something/src/Plugin/Field/FieldType/AnyToShowItem.php if the class AnyToShowItem doesn't exist. But if the class defined within doesn't match the filename, then AnyToShowItem will still be undefined but the class that IS contained in the file will be. So the next time the AnyToShowItem class is attempted to be constructed, the file is loaded again in a futile attempt to define the class, but the class within will already have been defined, and thus the redefinition error will be thrown


Pass id from URL to next page I have made a product page overview that displays all the products of my webshop. On the left, I have placed a filter where people can filter the products (e.g. country can be France, Germany...). When a customer selects a country (e.g. France) the URL changes and the id of the choice (France) is added to the URL. Now I want the next thing: when a customer selects a product, I want that the id that was added in the previous URL also is added to the URL of the product detail page.

So when you have www.test.com/products, you select France, you get www.test.com/products?field=country%1 and when you select a product, you should get www.test.com/products/product?field=country%1 instead of just www.test.com/products/product...

Anyone who can help?

To get the query string use

\Drupal::request()->query->all();

To further dig into use kint() and debug the  \Drupal::request()


How to make my Drupal custome Service return data on GET? I have defined few Drupal custom Services and they are working fine
via POST requests. But one of them needs to be available via GET.

This one:

function rooms_services_services_resources() {
    return array(
        'api' => array(
            'actions' => array(
                'hotel_inventory' => array(
                    'help' => 'Inventory of all Hotels',
                    'callback' => 'rooms_services_hotel_inventory',
                    'access callback' => 'rooms_services_access_callback',
                    'access arguments append' => false,
                    'args' => array(
                        array(
                            'name' => 'params',
                            'optional' => true,
                            'source' => 'param',
                            'type' => 'struct',
                            'description' => 'all passed URL parameters'
                        ),
                    ),
                ),
            ),
        ),
    );
}

It's working fine when I am making a request via POST with headers:

`Content-Type: application/x-www-form-urlencoded`

or

`Content-Type: application/json`

as those I have enabled in my REST Server...

How do I make it work via simple GET request ?

The short answer is you can't, unfortunately (AFAIK). For all non action resources, the Services module assumes that they are part of the entity C.R.U.D. spectrum, and then decides what to do based on the HTTP method. For example:

POST = Create
GET = Retrieve
PUT = Update
DELETE = Delete

So unless you're building an entity C.R.U.D. layer, you'll have to use POST on the actions array. Alternatively you could use hook_menu() to make your own custom page_callback that outputs JSON, then it could be accessed over GET. Another alternative is to use something like Views Datasource and compose a Views JSON to output your data (also available via GET).


Javascript file in theme does not get loaded I just added a script scroll.js, but it does not get loaded.

My theme is called test. I put the script in the js directory within the theme directory.

Permissions on the script are 644 (like on all other scripts in other themes) and permissions on the js directory are 755.

I added a line scripts[]= js/scroll.js to test.info.

Sorry for forgetting to mention the version of Drupal. I'm using Drupal 7.
I flushed all caches and did a hard refresh in the browser (tried both Firefox and Chromium).

After it looking like nothing was being loaded, I added a line window.alert("sometext"); to the script just to be sure. Still nothing.

In Firefox and Chrome the file is neither listed as being loaded nor as failing to load or permissions error.

It seems to me that the change to the .info file is being ignored, but I might well be wrong. How do I force Drupal to not ignore the new script file?

In drupal 8 my theme uses the file main.js. If my theme was called test I would add the file in this order.

File location:

test/js/main.js

In test.info.yml:

libraries:
  - test/global-js
  - test/global-css

In libraries.yml:

global-js:
  js:
    js/main.js: {}
global-css:
  css:
    theme:
      css/styles.css: {}

Remember your spacing in the .yml files (2 spaces).
also read adding stylesheets and javascript to a drupal 8 theme andCreating a drupal 8 sub-theme, or sub-theme of sub-theme

Happy Drupaling


Need some advice on implementing a HDFS file storage solution for drupal We are looking into using HDFS to store our files users upload through the drupal Site. I have not been able to find a module that claims to do this already so we thought we would build one. So my question is 2 folds.

Is anyone aware of a module that could do this?
Is there a specific API standard to build this out of drupal? Is it just a matter of implementing a  HDFSStreamWrapper

Thanks

I am not aware of any existing module for that, but you could start with storage_api and extend it by your custom implementation for HDFS.


How do I create a multi-select checkbox field in a content entity? Trying to figure out how to have 'Desktop', 'Mobile', and 'N/A' as check boxes on a config entity form in drupal 8, where I can select one or more options.

This configuration worked for me:

 $fields['device'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', ['desktop'=>'Desktop', 'mobile'=>'Mobile', 'na'=>'N/A'])
      ->setLabel('Device')
      ->setDescription('Select associated devices')
      ->setRequired(TRUE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 6
      ))
      ->setDisplayConfigurable('form', TRUE);


Disable links to username and date One of my tasks requires me to disable the links to username and date fields generated from diff_diffs_show() whose output is rendered as in the following screenshot.

The code outputting those links is the following one.
// Generate table header (date, username, log message).
$old_header = t('!date by !username', array(
  '!date' => l(format_date($old_node->revision_timestamp), "node/$node->nid/revisions/$old_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$old_vid])),
));
$new_header = t('!date by !username', array(
  '!date' => l(format_date($new_node->revision_timestamp), "node/$node->nid/revisions/$new_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$new_vid])),
));

How I can change the output of the function so that it doesn't output links?
Basically, I want the username  and date fields in plain texts instead of links.

diff_diffs_show() is the page callback for the node/%node/revisions/view route. The only way to change the output for that route is changing the page callback with hook_menu_alter().
function mymodule_menu_alter(&$items) {
  $items['node/%node/revisions/view']['page callback'] = 'mymodule_diffs_show';
}

function mymodule_diffs_show($node, $old_vid, $new_vid, $state = NULL) {
  // Attaches the CSS.
  $build['#attached'] = diff_build_attachments();

  $default_state = variable_get('diff_default_state_node', 'raw');
  if (empty($state)) {
    $state = $default_state;
  }
  $state = str_replace('-', '_', $state);
  if (!array_key_exists($state, diff_available_states())) {
    $state = $default_state;
  }

  // Same title as the 'Revisions' tab. Blocked by non-page requests.
  if (node_is_page($node)) {
    drupal_set_title(t('Revisions for %title', array('%title' => $node->title)), PASS_THROUGH);
  }
  $node_revisions = node_revision_list($node);

  $old_node = node_load($node->nid, $old_vid);
  $new_node = node_load($node->nid, $new_vid);

  // Generate table header (date, username, log message).
  $old_header = t('!date by !username', array(
    '!date' => format_date($old_node->revision_timestamp),
    '!username' => format_username($node_revisions[$old_vid]),
  ));
  $new_header = t('!date by !username', array(
    '!date' => (format_date($new_node->revision_timestamp),
    '!username' => format_username($node_revisions[$new_vid]),
  ));

  $old_log = $old_node->log != '' ? '
' . filter_xss($old_node->log) . '
' : '';
  $new_log = $new_node->log != '' ? '
' . filter_xss($new_node->log) . '
' : '';

  // Generate previous diff/next diff links.
  $nav_suffix = ($default_state != $state) ? '/' . str_replace('_', '-', $state) : '';
  $next_vid = _diff_get_next_vid($node_revisions, $new_vid);
  if ($next_vid) {
    $next_link = l(t('Next difference >'), 'node/' . $node->nid . '/revisions/view/' . $new_vid . '/' . $next_vid . $nav_suffix, array('absolute' => 1));
  }
  else {
    $next_link = '';
  }
  $prev_vid = _diff_get_previous_vid($node_revisions, $old_vid);
  if ($prev_vid) {
    $prev_link = l(t('< Previous difference'), 'node/' . $node->nid . '/revisions/view/' . $prev_vid . '/' . $old_vid . $nav_suffix, array('absolute' => 1));
  }
  else {
    $prev_link = '';
  }

  $header = _diff_default_header($old_header, $new_header);
  $rows = array();
  if ($old_log || $new_log) {
    $rows['logs'] = array(
      array(
        'data' => $old_log,
        'colspan' => 2,
      ),
      array(
        'data' => $new_log,
        'colspan' => 2,
      ),
    );
  }
  $rows['navigation'] = array(
    array(
      'data' => $prev_link,
      'class' => array('diff-prevlink'),
      'colspan' => 2,
    ),
    array(
      'data' => $next_link,
      'class' => array('diff-nextlink'),
      'colspan' => 2,
    ),
  );

  $links = array();
  foreach (diff_available_states('node') as $alternative_state => $label) {
    $links[$alternative_state] = array(
      'title' => $label,
      'href' => "node/{$node->nid}/revisions/view/{$old_vid}/{$new_vid}" . ($alternative_state == $default_state ? '' : '/' . str_replace('_', '-', $alternative_state)),
    );
  }
  if (count($links) > 1) {
    $state_links = theme('links', array(
      'links' => $links,
      'attributes' => array('class' => array('links', 'inline')),
    ));
    $rows['states'] = array(
      array(
        'data' => $state_links,
        'class' => 'diff-links',
        'colspan' => 4,
      ),
    );
  }
  $rows = array_merge($rows, _diff_body_rows($old_node, $new_node, $state));

  $build['diff_table'] = array(
    '#theme' => 'table__diff__standard',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class' => array('diff')),
    '#colgroups' => _diff_default_cols(),
    '#sticky' => FALSE,
  );

  // Allow users to hide or set the display mode of the preview.
  if (node_is_page($node) && $view_mode = variable_get('diff_view_mode_preview_node_' . $new_node->type, 'full')) {
    $header = '';
    if ($node->vid == $new_vid) {
      $header .= '
' . t('Current revision:') . '
';
    }
    else {
      $header .= '
' . t('Revision of @new_date:', array('@new_date' => format_date($new_node->revision_timestamp))) . '
';
    }
    $build['diff_preview']['header']['#markup'] = $header;
    // Don't include node links or comments when viewing the diff.
    $build['diff_preview']['content'] = function_exists('entity_view') ? entity_view('node', array($new_node), $view_mode) : node_view($new_node, $view_mode);
    if (isset($build['diff_preview']['content']['links'])) {
      unset($build['diff_preview']['content']['links']);
    }
    if (isset($build['diff_preview']['content']['comments'])) {
      unset($build['diff_preview']['content']['comments']);
    }
  }
  return $build;
}

The part getting the username is simplified: The code should check the username length, and truncate it if it's longer than 20 characters; the username should also be sanitized via check_plain().
See template_preprocess_username() to understand how that can be implemented.
I would rather not implement the code shown in this answer, since:

The node/%node/revisions/view route is accessible by the users who have the administer nodes permission, who should be allowed to see any link to revision pages
The users without the access user profiles permission wouldn't see links to user accounts in any case, but the users with the administer users permission should be allowed to see link to user accounts in any page, as that simplifies their work


Integrating Video.js with Google Analytics I'm wondering if anybody has gotten the Video.js module/library to play nicely with Google Analytics? I'm trying to do some integration via this plugin (https://github.com/mickey/videojs-ga), but am hitting a roadblock. I've added the script into my theme as second-to-last in the execution order, followed by another script consisting of the inline code noted in the example (as the final script on my page):

<script>
videojs('video', {}, function() {
  this.ga(); // "load the plugin, by defaults tracks everything!!"
});
</script>

At this point I think it's almost working, but chrome is throwing "Uncaught TypeError: The element or ID supplied is not valid." I've also tried replacing "video" on the above code with the ID of the video on the page that I am testing, and I'm getting the same error. I feel like I'm close, but I'm not sure what needs to be tweaked to get it working. Any ideas?

Right now I'm testing on http://mattweinercreates.com/video-js-testing, i you want to check out my environment.

I think I answered this after I posted. I was trying to use the ID on the <video> itself, but I instead tried using the ID of the div that contained the video, and that worked without issue. I still need to figure out how to update the code dynamically on a per-page basis so that the correct video is tracked, but it's at least working now.

EDIT: I was able to modify the "inline" code file from above to automatically pick up any videos on a page that the script is loaded on.

(function ($) {
    $('.video-js').each(function() {
        videojs(this.id, {}, function() {
          this.ga(); // "load the plugin, by defaults tracks everything!!"
        });
    })
})(jQuery);


My account as a block I am using Drupal 7. I want to show my account page as a block, where user can edit their personal information. Does anybody have an idea regarding this. Do I need to write custom module? Thanks

Possibly you can try this :

Create a views block with current uid in contextual filter & have all the account fields in that views block
Use 'editablefields' module & make use of it for Inline Edit
Enable the block where you need

Hope it helps


Add payment to a commerce order using Rules I am trying to create a component that can add payments to an existing order.(the payment is received offline). However, when I try to add an amount I receive the alert that the field is not writable ("The selected data property doesn't support writing"). Does anyone know how this may be accomplished using Rules?

This is my attempt so far:

{ "rules_set_order_id_as_paid" : {
"LABEL" : "Set order id as paid",
"PLUGIN" : "action set",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"USES VARIABLES" : { "orderid" : { "label" : "orderid", "type" : "list\u003Cinteger\u003E" } },
"ACTION SET" : [
  { "LOOP" : {
      "USING" : { "list" : [ "orderid" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "entity_fetch" : {
            "USING" : { "type" : "commerce_order", "id" : [ "list-item" ] },
            "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
          }
        },
        { "drupal_message" : { "message" : "[entity-fetched:order-number]" } },
        { "entity_create" : {
            "USING" : {
              "type" : "commerce_payment_transaction",
              "param_user" : [ "entity-fetched:owner" ],
              "param_order" : [ "entity-fetched" ],
              "param_payment_method" : "faktura"
            },
            "PROVIDE" : { "entity_created" : { "entity_payment_created" : "Created payment entity" } }
          }
        },
        { "data_set" : { "data" : [ "entity-payment-created:created" ], "value" : 1575626400 } },
        { "data_set" : {
            "data" : [ "entity-payment-created:payment-method" ],
            "value" : "faktura"
          }
        },
        { "data_set" : { "data" : [ "entity-fetched:status" ], "value" : "completed" } },
        { "data_set" : {
            "data" : [ "entity-payment-created:payment-method" ],
            "value" : "commerce_payment_example"
          }
        }
      ]
    }
  }
]

}
}

I ended up doing some sql statements that seem to have done the trick. One challenge was raising the event Paid in full via sql, which I ended up doing via executing a component manually. Not the most elegant solution but it did get the job done.


Token to get the latest revision's URL Drupal version: Drupal core 9.1.5.
I am using Content Moderation and Workflows modules along with Workbench Email contrib module to generate the Email Templates. Workbench Email module uses Tokens for creating dynamic email templates. We have a requirement to provide the URL of the latest revision inside the email body to the reviewer so that he can see the latest updates.

If I create a node that needs moderation, the /node/NID/latest page does not exist. Here reviewer will need link to /node/NID.
When the content is already published and now if gets edited, the link in the email should be /node/NID/latest. If we just provide /node/NID in the URL, it won't show the updated content.

Since we can have only one template to handle both of the above conditions, I was looking for a token which could provide me either /node/NID or /node/NID/latest based on whether the content is new or already published.
Can someone please assist on how can I move further?

The token needs to be available in the email? I've not created custom tokens in D8 yet but in d7 We'd make a custom token and the value would be set in the token definition based on condition.


Different front page per language Is there any way to provide a different node ID per language for the front page setting in Drupal 8?

We need a different front page for a specific language. In Drupal 7, this was easy.

Technically, the config override API that config translation uses allows any kind of override of configuration.
The core config translation however only does translation, meaning it only allows to change things that are classified as user-facing texts and not technical strings.
What you want is usually referred to as localization, changing things based the language that isn't actually a "translation". There is a core issue to better support this, https://www.drupal.org/node/2275865, but it hasn't been updated in quite some time.
There are a few possible workarounds, though:

Since you mention nodes, in Drupal 8, translations of nodes have the same ID/URL. That means you could have your different front pages as translations of the same node. That would be problematic if you use Paragraphs for example, as that doesn't currently support translatable fields, so you'd be forced into the same structure.

You could use Page Manager to have different front pages (there is a per-language constraint necessary, which has a patch but has not yet been committed) or even just a view that selects a node based on a certain condition (like filtered by language of a certain type).

A custom callback that displays a certain node based on a bit of code.

Update:
4 years later, I had this use case too and still no activity on the core issue. As a workaround, I altered the config schema and made the front_page a label type to be able to translate it. Not fully tested yet, so beware of dragons:
function custom_config_schema_info_alter(&$definitions) {
  // Change the front page type to label so that it can be translated.
  $definitions['system.site']['mapping']['page']['mapping']['front']['type'] = 'label';
}


How to distinguish between custom modules and contrib modules? We have taken a project where we have to upgrade a site from d6 to d7.

But their module structure is poor, and does not distinguish between custom and contrib modules. We also want to know what's upgradable, and what isn't?

This would be helpful for sending project estimation.

Is there a way to do this using drush perhaps?

If you want know which module has been upgraded or not and what things upgrade in module then you can use hacked module of drupal.

Go to hacked module configuration and click on "list project" Let it do the work.It will process the modules and will check for the changes.

Once it completes the process you will get a list of module along with the number of changes done in the modules.

Now open the directory sites/all/modules/ and check the modules which are displayed in the list you got after hacked process.The listed modules in the result are the contrib modules and rest of the modules should be custom.


Use a managed file in a menu_item Is there a way to create a menu that links to a managed file? I tried many times, but nothing I tried works.

Do you have any idea?

If you enter the full path of the file, it should work but if you're looking to create the menu with a relative path, see https://stackoverflow.com/questions/4335700/drupal-primary-link-item-to-a-relative-file-on-the-server or How can I add relative path to a pdf file link in drupal menu


How to organize the features export modules As we go along with features export, its being a mess. What I have been doing so far is every module which have another module that contains the feature exports. Let say their is module 'test' and it has some variable settings and I exported it via features. I will have another module name 'test_features_export' or something like that which contains the component associated with that module. But in some cases, the component can be too generic like 'role' which can be associated with multiple modules. Then its issue to bind to any specific features where it is meaningful.

So my question is , is there any better way to organize the features exports modules ??

What we usually do, is create Features based on Content Type, and group everything related in there.

So a Content Type News, would be put in a Feature 'MyProject_News'. Together with everthing that is relevant, like Views related to News, pathauto pattern, specific image styles only in use by News content, etc ..
Usually, we also have another Base or General Feature, containing more generic stuff like text format settings, site settings, .. and also our roles. This Base/General Feature, is a dependency in all other Features.

Others split it up differently, with a Feature containing all the Content Types, another to hold all Image Styles, another one for Contexts, etc ..

In the end, it's all up to you. You can organize it any way you wish.
However I do choose the first method, as in my opinion, a Feature should be able to operate on it's own, or being disabled, without messing up anything in the site.


Is it possible to add PHP code in Global: Custom Text? I have two links to redirect based on if a field is empty or not. Now I use the Global text setting to create a link for redirection with A basic <a> tag.

How can I add PHP code in a view to verify the field is empty?

First, install the Views PHP module and you can now add a "Global: PHP field" to your views that can include PHP code.

Then add your condition field first in your view and after that your PHP field, so that the condition field value is included in available tokens.

The code of your PHP field should be sth like this:

  <?php
      if ($field_test) { // use the field token here and check if empty
       return 'Exists';
      } else {
       return 'Not exists';
      }
   ?>

See also:

How can I enable Global: PHP field

add Global PHP code field to Views on condition


Odd log entries: is it indicative of an attack?, is there anything other than IP blocking that I should do? So I've been getting some odd log entries in my Drupal 7 install:
Here's two:

As far as I can see they haven't done anything and I've blocked the IP addresses but they keep coming with different IP addresses so I'm wonder what they actually mean? Like if they were for manager/html I'd know they were (probably automated) attack testing for Apache Tomcat apps to hack. But these with a location that isn't even my site I'm confused by.
Also wondering why the message starts with ttp:// instead of http:// or something normal.

Well continued my research and a day without no answer was enough time for me to figure it out. As I suspected yes this is an attempted attack/test. It is not specifically an attack on Drupal although it does show up in the Drupal log.

Specifically this is checking to see if your server is set up in such a way that it can be used as an open proxy; in other words if you give it a get request for a domain it doesn't serve will it GET the content from the right server and pass it on. This is bad without a login, since it lets anyone appear to be your server while they are spamming/etc - see the Apache Proxy Abuse Page.

In this case since Apache passed the request on to the virtual hosts it shows that the server is not configured as an open proxy and is safe (at least from that attack vector at this time). The server logs show a 404 as well which confirms that either the url was invalid or that there is no open proxy:

125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 404 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

If it was a successful attack test/attack it wouldn't appear in the Drupal logs, only in the server logs. In the server logs it would appear something like:

125.64.35.67 - - [03/Dec/2014:08:08:52 -0500] "GET http://6.url.cn/zc/chs/img/body.png HTTP/1.1" 200 716 "-" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.3072; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0)"

with a response code that indicates a valid resource.

As to why the Drupal log strips the initial h for the message I don't know and it doesn't really matter; that being said if I have time I'll probably investigate it and submit a patch to fix it.


Add custom fields to the Apache Solr search results I'm trying to configure a search page from Apache Solr module, and add some custom fields to the items. Here is the code I'm using for this

Custom module:

function hook_apachesolr_query_alter($query) {
$query->addParam('fl', 'ts_field_up_short_description');}

Function in tamplate.php:

function tamplate_preprocess_search_result(&$variables) {
$variables['ts_field_up_short_description'] = $variables['result']['fields']['ts_field_up_short_description'];}

Display field in search-result.tpl.php:

<?php if ($ts_field_up_short_description) : ?>
     <?php print $ts_field_up_short_description; ?>
<?php endif; ?>

I'v created 3 nodes with this field, but only one of them displays the short description field (if displaying the search results with views everything is fine). Please tell me am I missing something? Thanks

I have forgotten to add the content type filters, everything is correct now. Another (better) way is to modify the snippet in module (like here) instead of the search results template.


Tiered HTML lists using Views and Taxonomy? I would like Views to output an HTML unordered list of a certain vocabulary (Taxonomy Term). This is not a problem... the problem is that the list is rendered flat, instead of showing the parent>children relationships contained in the vocabulary.

How to I get Views to render this:

  Parent

  Child
  Child

  Parent

Instead of:

  Parent
  Child
  Child
  Parent

I'm going to assume your view is a taxonomy term view.

First thing you would want to do is add a relationship to your view. The relationship you want to add is the Taxonomy: Parent term relationship and set required this relationship.

Once you're done adding the relationship add another Taxonomy: Term field to your view but this time make sure to select the "Parent" relationship for that field.

Also select "Exclude from display" for this field if not this is going to show up twice.

Once you've done that you will need to group your fields by the Parent Term. This can be accomplish by going to the settings option for the format and selecting the Parent term you just added.

You will now get the display you want.

Hope this helps.


Additional fields for my entity from another table in views I have table of my entity with structure:

=====================================
eid | myfield1 | myfield2 | myfield3
=====================================

And also an additional table with primary key being foreign key to my entity id:

==========================
eid | myfield4 | myfield5
==========================

I would like to expose values in my second table to view of fields, of my entity, but I don't want to join second table with first, every time, but only if I will use one of its fields.

I believe it should be doable with views_join class modifying a query at handler level, but is it possible on hook_views_data_alter() level?

Is it possible to do this transparently - so I wouldn't need to add any relationship to view (just like the field values are pulled from fields tables - yes, you can think a bit about it as about creating fields alternative ;) ) ?

Technically it's possible, using hook_views_query_alter(), you can adapt the view query to add or change conditions. So you could add a join with something like this:

function modulename_views_query_alter(&$view, &$query) {
  $join = new views_join();
  $join->table = 'mytable';
  $join->field = 'eid';
  $join->left_table = 'entity_table';
  $join->left_field = 'eid';
  $join->type = 'left';
  $query->add_relationship('relationship_name', $join, 'entity_table');
}

But a better approach would be to use hook_views_data() to expose your table to views, and then add the relevant fields when needed (with a relationship though), but in practical terms is no different than altering the query.


Send email notification when a new comment is posted I'm using Drupal 8.1 with Rules 8.x-3.0-alpha1.

I want to create a rule to send an email to the author of a node when a new comment is posted to this node. Problem is I didn't get the email address of the author with rules because the dataset gives me only this values: @node.node_route_context:node or comment but under comment I didn't find anything like comment:node:author. In Drupal 7 I have this data. What I have to do in Drupal 8?

Updated Answer

Whilst testing this on a fresh install of Drupal 8 with Rules (Alpha 2) I have come across a bug which is preventing a successful test of this, whilst the data selector below is correct I am presently unable to reproduce a working rule.

The bug report is here: https://www.drupal.org/node/2770291 - To summarise this issue Rules is expecting the TO: parameter to be an array and will throw an error when passing the email address token below which returns a string.

My initial answer holds true for Drupal 7 however for Drupal 8 the situation seems simpler and hinges on a single fact that isn't yet well-documented.

In D7 we're familiar with a syntax resembling: comment:node:author:mail

In D8 the same selector (which works) is: comment.entity_id.entity.uid.entity.mail.value

Hopes this helps, I'm leaving the previous answer below in case it helps someone else.

Previous Answer

*In general with Rules to use the value of a field the rule must first specifically check for the existence of the field (i.e. that the field has a value in the context the rule is running).
If you haven't tried this already you might want to try adding an "Entity has field" condition to the rule to check for the existence of the email address. This should then expose the token for the field.

I've had similar issues executing rules using entity relations (which is more or less what you're doing by referencing the author from the node) checking for the existence of the field (in your case most likely a check that the entity has an author (this should open up access to the user object) then a check against the user object to ensure it has an email address) opened up the available field tokens from the referenced entity.*


Form problem : calendar pop up overriden by an autocomplete field Drupal 7. I use a bootstrap theme with some customized css.
I have a node/edit form with a date field with calendar popup widget and an entityreference field with autocomplete widget.

When I click on the date field, a part of the calendar is missing : it is overriden by the autocomplete field.(see picture below)

If I change the widget for the entityreference field and choose select widget, the calendar is OK.

With the original bootstrap theme (without customized css), the calendar is OK.

Is there something I can change in CSS to prevent the calendar to be overridden by the autocomplete field ? (should I change the date css ? or the autocomplete css ?, which setting ?)

Try:

input{
  position: relative !important;
  z-index: 0 !important;
}

You can change the "input" selector to meet your needs and try this without "!important" also.


Auto Assign User to Node I am working on a site that is a directory of all track and field clubs (trackandfieldclubs.com). A user can create an account and add their club if it is not listed. However, nearly all the clubs have been listed by me to give the site some value. After all, what good would the site be if no track and field club were listed? The problem is that I want a user who's club is already listed to become the author of their club's node. Right now I have implemented a rather archaic system to do this where a user first creates an account, then fills out a web form (http://trackandfieldclubs.com/form/request-edit-existing-club) telling me their club name and username. I then login as an admin and change the node's author. Is there a better way to do this? Can this process be automated? Thanks in advanced!

You can create a simple module, implementing hook_form_alter, add additional form submit action which checks the submitted values on your form, looks up if there is node matching them and finally loads and updates the node accordingly.

Alternatively, you can add the Existing Club Name field to registration, implement hook_user_insert, and do the same logic as described above. This would save you unnecessary web form and improve the user experience greatly.

EDIT:
Now that I think of it, it might be possible to achieve this using Rules module (https://drupal.org/project/rules) without coding. You add the field to the registration, create a rule, on event when user is created. Then iterate over all nodes of the Club content type (this should be possible with rules) and do a string comparison on each, to find the corresponding club. If the string comparison matches, you can easily change the node author. Please note that this solution is rather slow (and definitely not "right"), users could experience slow registration times.

Alternatively, you could change the rule event from user registration to form submission (which you have already) and therefore this (possibly) slow processing would not affect all users.

Also, I havent tried it, it's just an idea, but you should definitely try it.


Approach to create team roster? I'm trying to create a team roster content type. Each team member has first name, last name, tel number, character name and a photo.

Attempt #1:
 I've installed NameField module which allowed me to add/edit players on the team. The problem with Name field is that i can create unlimited number of players in team roster, but namefield doesn't provide a field to upload a photo to each of them.

Attempt #2:
I tried to create a content type called 'Player' with fields for name, photo, and tel number. Then create a View with sorted table. My problem: User needs to constantly click add Player to create more than one player. Is there any way to make it more user-friendly?  For example,
Just click 'Add one more field' without getting into content creating menu?

Question:
Approach to create sorted table view of players name, tel. number, and photo?

Try using the Field Collection module.

Create a collection of fields and then attach it to the content type as one field.


Search results showing duplicate entries For some reason the search results show duplicate entire with the view I have, I also have  distinct on under the query options so it doesn't show duplicate nodes, I cant figure out why its doing this for the life of me.

This is the view I have of it.

Any input is appreciated.

Edit: It seems to only do this when I search for  only 2 words, for example "should I" "can you" "this that" "now here" ect...

You seem to have added a field (Field: Image). If there are nodes with multiple field items (multiple images), then they will show up multiple times. To avoid that, enable aggregation in the advanced settings. It might also be possible to configure the field to only list the first value, not exactly sure.


db_query(); -- list of files attached to a node? I have a DRUPAL_BOOTSTRAP_DATABASE .php -script that loads info based on the nid it gets via POST request.

I need to list files attached to the requested node, and I know how to do this in D6, but after spending 30min trying to understand the new table structure of Drupal 7, I cannot fathom how to pull the fid (or any other file info related to the node) via a db_query();

I've been trying to read Devel query log to get a hang of how Drupal handles this to no avail. Any insight into my problem would be greatly appreciated. :)

replace uppercase by your data:

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

$sql = 'SELECT f.* FROM {field_data_field_YOURFIELDFILENAME} ff INNER JOIN {file_managed} f ON ff.field_file_fid=f.fid WHERE ff.entity_type = :etype AND entity_id=:nid';
$result = db_query($sql, array(':etype'=>'node', ':nid' => YOURNID));

foreach($result as $row) {
  print_r($row);
}

Create custom function for processing uri: public://FILENAME.EXT and getting right path from this.