how to make big menu in drupal 7 How to make the menu like this in drupal 7. There are many customer module in drupal.org, but I don't know much about which module will suit with this. I would to drop down product category when user puts cursor on product menu item.

Thanks

You can do this by using any of below modules :

Megamenu

  Mega menus are a type of drop-down, which seeks to overcome some of
  the usability drawbacks to traditional style drop-downs.

Bigmenu

  THIS MODULE attempts to replace the all-in-one global tree view with a
  similar interface, but sub-trees are "collapsed" below a certain
  level, and can be expanded as needed.

TB Mega Menu

  TB Mega Menu allows you to create a mega menu with an innovative
  back-end user interface and synchronized with Drupal core menu.

OM Maximenu

  That is now possible by using OM Maximenu which can create menus with
  all other module blocks you want as attachments, modules like views,
  slideshow, menu, user, nice menus, quicktabs, and custom blocks with
  tables, lists, images, videos, etc.

Superfish

  Superfish integrates jQuery Superfish plugin with your Drupal menus.

Menu Views

  Allows menu items to render views instead of links. This is useful for
  creating "mega-menus".

MuchoMenu

  This module allows users to create mega menus that have mini panels as
  their flyout content. The benefit is that ANY type of content or UI
  can be added to the menu flyouts.


How can I set up a "many to many" relation with an entity How do I set up n:m database relation in a custom Drupal 8 module?

I want to create task entities that may be related to different users (a task may have multiple related users and a user may have different tasks).
Using the database directly I would create two tables(as the user table already exists), a tasks table and a task_users table which contains the relations (User IDs and Task ID)s.
How do provide something like this in Drupal 8?

I only find a way to handle 1:n relations in setting up a user reference field (entity_reference) as a base field definition.

$fields['user'] = BaseFieldDefinition::create('entity_reference')

But how do I provide a relationship table?

You can set unlimit cardinality, some like this:

->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)

This create a intermediate table to reference two entities.

Check api documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21BaseFieldDefinition.php/function/BaseFieldDefinition%3A%3AsetCardinality/8.6.x


Submenus do not work on some pages For some reason, sub-menus do not work on all pages on my site. Here is one (basic page) that shows the submenus

and here is a screenshot where it doesn't even though the mouse is hovering over the Home menu item.

The links are enabled in Main Menu and I tried toggling "Show as expanded" on and off but neither one makes a difference. The background image is hidden by a display:none css style in the second image/page. If I go to the Contact page, which looks similar to the first image the submenu does not show up on there either. The Contact page was created using the webform module.

Any help figuring this out would be much appreciated.

Thanks,

Kamal

UPDATE: I noticed that on the pages where the submenu works, the following code is generated for the menu.

Home

Host A 51@EarthHour Event

Whereas on the pages where it doesn't work, I only see

Home

Which page are you on when it does not show and is that page in the menu? Also Are you using a block for the menu or printing it in the theme template file? That could be the cause. I'd recommend switching to a block if that's the case and make sure the expanded check-box is checked.


Webform issue with captcha I have created about 11 webforms in my website. Now I want to add recaptcha challenge in all of them.

I have installed the captcha module and recaptcha module. recaptcha is coming in all these forms. The problem is form gets submitted even if challenge is not taken. Below is yml file of a sample webform I have created

test_field:
  '#type': textfield
  '#title': 'Test field'
  '#required': true
captcha:
  '#type': captcha
  '#captcha_type': recaptcha/reCAPTCHA

I don't think reCAPTCHA module provides front-end validation. Have you tried performing front-end validation using reCAPTCHA API? You could try something like this:

 $('form').submit(function () {
   if (!grecaptcha.getResponse()) {
     event.preventDefault();
     $('reCAPTCHA is invalid').insertAfter('.g-recaptcha');}
  });


View with content from Media gallery links to node not working So i have a couple of nodes I made with the media gallery module. Then made a view called 'most recent photoalbums' with I put inside a block to be displayed on the frontpage.
The problem is that characters %5B and %5D are being generated against will and make the links to the nodes not work when clicked.
So, hovering over an image in such a view

So with display set as block, everything is left as default except the following:
Format:
Show: fields

Fields:
Content: title - nothing fancy here when it comes to settings just linked to node

Content: Gallery media - here obviously is the problem

No labels set whatsoever
uncheck exclude from display
Formatter set to Media
File view mode: Preview
Multiple field settings fieldset: 'Display all values in same row' checked, Display type: 'unordered list', 'Separator: Display 4 values starting from 0' - 'reversed' unchecked - 'first and last only' unchecked.
Style settings fieldset: only 'add default classes' checked.
Rewrite settings fieldset (where it's at):
'Rewrite this output as fied' unchecked,
'Output this field as link' checked,
'Link path': node/[title] (I tried all replacement patterns as suggested ),
'use absolute path' unchecked,
'Replace spaces with dashes' checked,
'External server URL' unchecked,

Transform the case: no transform, all the textfields under

Link class, title text, rel text, Prefix Text, suffix text and Target are left empty,
'Trim this field to a maximum length' unchecked,
'strip html tags' unchecked, under 'preserve certain tags'  -> 'remove whitespace' checked,      'Convert newlines to HTML br tags' unchecked.

Looks like you probably have spaces in the field [title], try using the nodeid check it works first then come back.

If you have pathauto you could then use this to rewrite the URL to an aliased URL.


Feed Import is successful and shows number of nodes imported but nodes not listed under content I am using the Feeds module to import content from a different Drupal site as xml.

The problem is that the feed import is successful, and a message says how many nodes of the new content type it has created. But when I go to content or to the database the content imported is nowhere to be seen.

What is the workaround for this issue? Is it a bug in the module?

I found the solution. This is what I did for the nodes to be picked and listed under content:
For the importer, Mapping for Node Processor, added a source xpathparser mapped to target GUID and checked Unique target.

Then for XPath XML parser mapped the GUID field to the Node id field in my xml file (for my case the label was Nid)


Is it possible to define hook functions in template.php instead of the module? Theme functions are defined in the template.php but is it possible to define hook functions in there? for example There is a content type called phone-book, its add content form ID is phone-book-node, I want it to redirect to my custom page when it is submitted. so I created this function in the template.php :

function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) {
$form_state['redirect'] = 'go/some/where';
}

but it doesn't work. I don't know if it is totally impossible to define such hook functions inside template.php or something is wrong with my code.

Yes, you can implement any alter hook in a theme, as well as  hook_theme() and preprocess hooks.

Adding $form_state['redirect'] won't do anything there, though. You need to do that in a submit handler:

function MYTHEME_form_phone_book_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'MYTHEME_phone_book_node_form_submit';
}

function MYTHEME_phone_book_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'go/some/where';
}

To ensure that your hook is running, get the Devel module installed and add dpm('alive'); in there. Then clear the caches (to be sure) and refresh the page a couple of times. If you don't see the debug message, the hook isn't being called, and it might be named incorrectly.


How to change to default Localization Client language to translate Localization Client allow me only to translate from English to one of others languages.

It is possible to translate from language x to English too?

No.

The reason is the way the Drupal translation system is built. Original strings (defined in modules) must be written in English. This means all translation will be from English to X-language.


How do I access the updated entity after saving with entity wrapper When using entity wrapper to modify and save an entity, what is the preferred way of accessing the updated entity.

For example, after the following code saves the node:

$node = node_load(123);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

After that, what is the preferred way to access the updated node object (the full object, not just field values)?
Can it be accessed via the wrapper in some way or do you have to load the node again?

There's no "preferred" way, as such, but I guess if you're using the wrapper to work with the entity, it makes sense to stick with that convention to re-access it.

Don't forget you've just altered an in-memory object, so regardless of the persistence layer, that object will still have the changes in it.

Once you've done this:

$node_wrapper->field_textfield->set('New value');
$node_wrapper->save();

Your changes will immediately be available by inspecting

$node_wrapper->field_textfield

EMWs use the core entity API under the hood, so persistence is actually done through the default entity controller. As such, everything that would happen in calling node_save(), for example, happens when you update the wrapper object.

In practical terms, that means you can save an entity with EMW, and also access the changes on it immediately using an object returned from entity_load(). It's the same underlying object in memory.

I think it's safe to say that context, and even surrounding code/conventions, will often dictate the particular method you use.


Execute drush commands from UI? So i wrote a lot of custom code which is executed form custom drush commands from the command line/terminal, works fine, but now the client changes his mind and want to execute the code from the UI, the admin panel.

Is there any way i can run those drush commands from that level or not?

Thanks,
Will

in php you can do something like :

  shell_exec("drush status");

if this is temporary, you can execute it from devel/php, but if it's a production site solution that you need, you can per example add a custom form that does this in its submit method


Set max_execution_time for view? I've got a view that generates a CSV report on user information. However, due to the size of the dataset it's causing the server to timeout. Is there some way that I can set the max_execution_time() or set_time_limit() just for this path?

If you're looking for a custom-code centric path. Both D7 & D8 provide a hook_views_pre_execute() hook. It will trigger prior to any view query execution.

You can hook into this function, inspect $view object for the particular view you're wanting to extend your PHP execution, then call the PHP function of your choice.


Drupal authentication for a non-Drupal script I have a non-Drupal PHP script I would like to put on a D7 Drupal site, but I would like it to be available only to users who have logged in via Drupal. What are the best/easiest ways to do this? It's my script, so I can change it any way I want, embed it in a module, a PHP-capable field, etc.

To be specific, it's a signup sheet system that uses form submissions, using files (not the db) to store the data.

You can wire up your script via a hook_menu, and instead of returning the output to render via Drupal, you can print it directly and exit at the bottom of the function.  The submission handler would do the same thing, but drupal_goto() at the end.

That said, this is a moderately bad idea for the long run.

A better solution would be to use Webforms.  Webforms are really easy to make, get stored in the database, and can be exported to Excel.  I wouldn't be surprised if there is webform hook available so you could do your filesystem thing, too.

Another option is to use the Forms API to make your form w/ your custom validation and submission handlers.


fetchAll Database query returns an error I'm building a REST Resource in drupal 8 php that returns the result of a query to the database. However using the fetchAssoc() only returns one result.
So I figured that fetchAll() returns all results, but it throws an error when I do so.
This is the code
$result = $database
      ->select('node__field_recipe_category', 'recipe_cat')
      ->fields('recipe_cat', ['entity_id','bundle'])
      ->condition('entity_id', [3,8], 'BETWEEN')
      ->execute()
      ->fetchAll();
     // Configure caching settings.
    $build = [
      '#cache' => [
        'max-age' => 0,
      ],
    ];

    // Return results.
    return (new ResourceResponse($result, 200))->addCacheableDependency($build);

This is the error
The website encountered an unexpected error. Please try again later.

Symfony\Component\Serializer\Exception\NotNormalizableValueException: Could not normalize object of type &quot;stdClass&quot;, no supporting normalizer found. in Symfony\Component\Serializer\Serializer-&gt;normalize() (line 164 of vendor/symfony/serializer/Serializer.php).
Symfony\Component\Serializer\Serializer-&gt;normalize(Array, &#039;json&#039;, Array) (Line: 116)
Symfony\Component\Serializer\Serializer-&gt;serialize(Array, &#039;json&#039;, Array) (Line: 176)
Drupal\rest\EventSubscriber\ResourceResponseSubscriber-&gt;Drupal\rest\EventSubscriber\{closure}() (Line: 573)
Drupal\Core\Render\Renderer-&gt;executeInRenderContext(Object, Object) (Line: 177)
Drupal\rest\EventSubscriber\ResourceResponseSubscriber-&gt;renderResponseBody(Object, Object, Object, &#039;json&#039;) (Line: 76)
Drupal\rest\EventSubscriber\ResourceResponseSubscriber-&gt;onResponse(Object, &#039;kernel.response&#039;, Object)
call_user_func(Array, Object, &#039;kernel.response&#039;, Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher-&gt;dispatch(&#039;kernel.response&#039;, Object) (Line: 191)
Symfony\Component\HttpKernel\HttpKernel-&gt;filterResponse(Object, Object, 1) (Line: 173)
Symfony\Component\HttpKernel\HttpKernel-&gt;handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel-&gt;handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle-&gt;handle(Object, 1, 1) (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache-&gt;pass(Object, 1, 1) (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache-&gt;handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware-&gt;handle(Object, 1, 1) (Line: 52)
Drupal\Core\StackMiddleware\NegotiationMiddleware-&gt;handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel-&gt;handle(Object, 1, 1) (Line: 708)
Drupal\Core\DrupalKernel-&gt;handle(Object) (Line: 19)

Any ideas?

fetchAssoc worked for you because of the result is an associative array.
fetchAll did not work because the result is an array of stdClass objects and JSON normalizer did not know how to return the data.
I think you will need fetchAllKeyed(0,0), but better play around a bit.
reference: https://www.drupal.org/docs/8/api/database-api/result-sets


how to identify first element in array of node objects? hook_node_load($nodes, $types) in Drupal 7 takes two arrays as parameters. In the module I'm working on (Drupal 7 port from Drupal 6), just one node of one type is being loaded. I tried $node[0] to specify the first node in the array, but no joy. How do I get at the first node and the first type? There is only one object in each array.

$nodes is keyed by the node ID, which you probably won't know in advance. Instead of directly trying to access the first node in the array, iterate over them with a foreach loop.

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $nid => $node) {
    if ($node->type == 'basic_page') {
      ...
    }
  }
}


Is there a way to export the whole panelizer settings for a page? With whole settings I mean: context, layout and content. I know how you can export the layout and context, but I do not know how to export the content.

We have several websites that share some pages in common which have widgets in the panels and we try to automate that so that our content managers do not have to do this with every setup.

You can do this with Features:

Enable Strongarm module
Create new feature
Export and Deploy Panelizer settings

Alternatively you can do this with a custom module. See https://www.phase2technology.com/blog/exporting-panelizer-defaults-to-code/


Form theming with templates Please could someone explain why the following doesn't work?

This is in the form build:

$form['#theme'] = 'some_form';

Here's the hook_theme function:

function MYMODULE_theme($existing, $type, $theme, $path) {
    return array(
      'some_form' => array(
        'template' => 'some-form',
        'variables' => array('form' => NULL),
      ),
    );
}

The template (some-form.tpl.php):

<div id="some-form">
<?php print render($form); ?>
</div>

You can see the wrapper markup from the template file but the form is not being output.

Since you're attaching the #theme to an element, you need to user render element in your theme declaration in place of variables:

function MYMODULE_theme($existing, $type, $theme, $path) {
  return array(
    'some_form' => array(
      'template' => 'some-form',
      'render element' => 'form'
    ),
  );
}

After you clear the caches your template should start being used for that form.

See hook_theme() for more information.

Just another thought, if your template file is as trivial as just wrapping the form in a tag you can use the #prefix and #suffix properties on the $form object instead of using a theme at all:

$form['#prefix'] = '
';
$form['#suffix'] = '
';


table like in admin of custom module I have created a custom module that can add an entry into my own created tables. However, I need to display the contents of that table into the admin, a table like view. Like this one in the picture:

Can you point me to the correct documentation or what is this called?

Thanks.

You can create such tables with the Views module.

  You need Views if:

  You like the default front page view, but you find you want to sort it differently.
  You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain type.
  You like the idea of the 'article' module, but it doesn't display articles the way you - like.
  You want a way to display a block with the 5 most recent posts of some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.


Display a view of geolocation fields with lat lon on a google (or equiv) map I have a geolocation module installed with a field that geolocates and gives a lat lon value. Then I want to use a view of these values to show them in google maps or equivalent. If there is a quick and dirty solution would be good, otherwise I would spend time coding one solution.

I used this sandbox module geolocation views with geolocation field module.
http://drupal.org/sandbox/xandeadx/1782036


How can I pass a fixed argument to a view within a panel? I have a view that will be repeated on many pages, and to not replicate many times, has two arguments. These arguments do not come from URL, are fixed. This view is inserted into a panel.
Is it possible? How?
Thanks!

I'm making the assumption your on D7, with views 3, and have Views Content Panes running on your site (Views Content Panes comes with ctools).

So your gonna create your view as you normally would. When it's good and displaying as you want it to, add a display of a content pane (up near the top, under the display, hit the plus sign, select content pane). This will give you access to the "PANE SETTINGS," one of which is "Argument input." Click on this. If you have two contextual filters running on your view, there should be two drop down menus, one for each of your contextual filters.

Set both of these to "input on Pane Config." Now when your adding your views to your panels, your going to use the "View Panes," NOT the "views." Once you add your view pane, you should be presented with two text boxes for your contextual filters, you may set provide the arguments for those here.


Editing the default layout for a content type in Panopoly I am using the panopoly distribution. What is the easiest and preferred way to edit the default layout for a content type.

I know that I can use panelizer for one page, but where should I go to edit the entire contenttype?

You're looking for the panels (node_view) page. You should be able to find it at admin/structure/pages and then look for node_view.  Edit that page and add a new variant for your content type.


Can I use sites.php to resolve subdomain on my multi-site installation? I have a Drupal multi-site setup on Ubuntu.

One of the multi-sites is cyber.site.edu.

Our requirement is to have another virtul host named cyber1.site.edu.

cyber1.site.edu should also resolve to cyber.site.edu

Can I use example.sites.php? I read the documentation at this link but it is not clear to me.

Any help would be appreciated.

This assumes your multi-site structure is as follows:

sites/site.edu
sites/cyber.site.edu

Let's start at the top by addressing a few key things:
1. Is there a DNS entry for your subdomain?
When working locally, you should add the subdomain to your hosts file.
Hint: If browsing to cyber1.site.edu generates "This webpage is not available", the answer is no.
Help: (AskUbuntu) Setting up subdomain on Ubuntu server
2. Have your Virtual Hosts been properly configured?
You need to inform Apache how to pass the correct domains to Drupal.
Hint: If browsing to cyber1.site.edu generates a Drupal site installation page, the answer is no.
Help: How To Enable Multiple Sites on a Drupal Installation On Ubuntu 12.04
3. Do you have a folder in sites/ bearing the actual hostname, including the subdomain?
In this case, we already know the answer is no. If the answer were yes and you had a folder in sites/ named cyber1.site.edu then Drupal would be able to auto-discover it in the usual way. Since you do not, we need to tell Drupal what to do.
This is where sites.php comes in handy:

Setting up sites.php
From the docs in sites/example.sites.php:

This file allows you to define a set of aliases that map hostnames and
pathnames to configuration directories. These aliases are loaded prior
to scanning for directories, and they are exempt from the normal
discovery rules. (...)
To use this file, copy and rename it such that its path plus filename is 'sites/sites.php'.

Add this line to the end of the file and save.
$sites['cyber1.site.edu'] = 'cyber.site.edu';


Display fields node in table like views I have a content type documents and my fields (created by admin) are:

Doc1
File
Date
Doc2
File
Date
Doc3
...

The reason why I don't do a content type just with: "Doc, file, date" and add the nodes I want is because I need the Document name to be written by admin, and no one can edit it.(for example: birth certificate) (If you have an idea to do this other way, I'm listening)

This way, the user inserts just one node with all of those fields.

I want to somehow group those fields (Doc1, file, date) and display it like a view.

Views display all nodes from a content type. I need to display the fields of just one node, like a table. Is this possible?

Thanks

You can create a view to display a single node. You can determine which node to display by using a contextual filter. For instance, you can pass the node ID to the view, in order to get it displayed.

There are many tutorials explaining how to use contextual filters with views. A possible starting point might be the following: https://www.drupal.org/node/1578558


Which tables can i share in multilingual multi-site installation? I have a multi-site installation with different databases. I've shared i18n_; language; locale_ tables. On the main installation several languages work just fine.
But on the others sites which i am trying to use also with multilingual settings i can't get language switcher appear whatever i try. They don't want to use prefix between nodes. Translated nodes are connected but there's no way to switch between them.
Please could you give advice which tables am i able to use to have shared translations without problems?

As i understood you almost cant use common tables on multi-site installation - i`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.


How to change the page of a view block display programmatically I have a view with a block display. Is there any way to change the block pager page programmatically?
Currently i am embedding theview using the views_embed_view and i am passing the url arguments. What i need is to pass also the pager index argument also. Is this possible?

Thanks in advance

This is how you can get a view programmatically:

  $view = views_get_view('view_name');
  $view->set_display('view_block_name');
  $view->set_arguments(array($argument_goes_here));
  $view->pre_execute();
  $view->execute();
  print $view->render();

The views object has many functions which can be viewed here.

You can set current page for the pager with $view->set_current_page($page);


How to get firstname in autocomplete when adding new members in og group? I have created the group in og.

When adding the user for the group, In autocomplete its been displaying the user's email ID.

function custom_form_alter($form,&$form_state){ if($form['#id']== 'og-ui-add-users'){
     $form['og_user']['name']['#autocomplete_path'] = 'user/autocomplete';
}

}

But I want to get the name instead of email ID.

I have tried to change the user/autocomplete in hook_form_alter,but its displaying email id only

Is there any way to get name instead of email ID ?

Tell me how to sort out this problem?

I didn't get a clear idea, anyway please Check This.


Upload one image but save/export to multiple formats Have been searching for this quite some time but I can't seem to find an answer. There must be someone who has encountered this before.

What I want to do is have an editor upload 1 image and then save/export it to multiple formats. Automatically save a thumbnail, smaller teaser version and a version that has a color filter. I don't want to create 3 upload fields and have the editor choose a filter.

Any help is appreciated.

If you are on Drupapl 7 then in Admin You would see Image Style. Once you are there you can define different presets such as thumbnail, large, medium etc. There are three predefined presets available. But you can add your own with the dimensions of your choice. Once you set that you can use that where ever you display in the image.

In views or fields display management with in the content type.

For advanced filters you should look into the imagecache actions


How can I get webform file upload to display a thumbnail instead of a link? I have a webform with a file field.
When I upload the file I want to return a thumbnail of the file.

Is this possible? If so how can I achieve this?

I eventually used a bit of JavaScript to replace the link with an image tag that used the path in the link for it's source.


How do I customize the search result page? I have customized the teaser view of my content types and the page view. Now I need to use the teaser view for the search results page. By default, Drupal displays a full text jumbled mess for each result, I need to be able to customize the look of each one per content type. I don't want to change HOW drupal gets the results, just how it displays them.

You can override theme_search_results(), or theme_search_result().

The first is the theme function that is invoked for the search result page, while the second is the theme function that is invoked to render a single result. Both the theme functions use a template file (search-results.tpl.php in the first case, search-result.tpl.php in the second case).

search-result.tpl.php would use $info_split['type'] in Drupal 6, which contains the node type. In the latest Drupal 7 version, $info_split['type'] is not anymore passed, but search-result.tpl.php still gets $result['node'], in the case the search is done for nodes; $result['node']->type is then the content type of the node.

To notice that Drupal 7, and higher, allows the modules to implement hook_search_page(), but it is a hook used by a module that integrates with the Search module, not from a module that wants to change the result page for results returned by another module.
Also, on Drupal 7, each theme function uses a preprocess function, which in this case would be hook_preprocess_search_results() and hook_preprocess_search_result(). They are helpful in the case you just need to edit the value of what passed to the template file.


How do I import a feed in a node? I was looking for a solution to import RSS Feeds as nodes. We need to make modifications and add more fields to the content. This would have been easy in Drupal 7 with Feeds Importer, but it doesn't appear that there is a viable alternative for Drupal 8.

What would be the best way to import a feed directly to a node?

The solution is described in:

https://ohthehugemanatee.org/blog/2017/06/07/stop-waiting-for-feeds-module-how-to-import-remote-feeds-in-drupal-8/

1) Download and enable migrate_plus and migrate_tools modules. You should be doing this with composer, but I won’t judge. Just get them into your codebase and enable them. Migrate Plus provides plugins for core Migrate, so you can parse remote XML, JSON, CSV, or even arbitrary spreadsheet data. Migrate Tools gives us drush commands for running migrations.

2) Write your Migration configuration in text, and paste it into the configuration import admin page (admin/config/development/configuration/single/import), or import it another way. I’ve included a starter YAML just below, you should be able to copypasta, change a few values, and be done in time for tea.

3) Add a line to your system cron to run drush migrate -y my_rss_importer at whatever interval you like.

Below is a YAML file which you should adjust:

id: my_rss_importer
label: 'Import my RSS feed'
status: true

source:
  plugin: url
  data_fetcher_plugin: http
  urls: 'https://example.com/feed.rss'
  data_parser_plugin: simple_xml

  item_selector: /rss/channel/item
  fields:
    -
      name: guid
      label: GUID
      selector: guid
    -
      name: title
      label: Title
      selector: title
    -
      name: pub_date
      label: 'Publication date'
      selector: pubDate
    -
      name: link
      label: 'Origin link'
      selector: link
    -
      name: summary
      label: Summary
      selector: 'itunes:summary'
    -
      name: image
      label: Image
      selector: 'itunes:image[''href'']'

  ids:
    guid:
      type: string

destination:
  plugin: 'entity:node'

process:
  title: title
  field_remote_url: link
  body: summary
  created:
    plugin: format_date
    from_format: 'D, d M Y H:i:s O'
    to_format: 'U'
    source: pub_date
  status:
    plugin: default_value
    default_value: 1
  type:
    plugin: default_value
    default_value: podcast_episode


Webform custom validation red highlight How can I add the red error border to a webform component programmatically?

I am doing so custom form validation when the form submits and I need to set the red border on under rules very specific to my module.

Currently, I am doing the following:

form_set_error('email_address', 'Please supply matching email addresses');

It adds an error message and stops the form from being submitted but it does not highlight the form field I am validating. That makes it difficult for the users to see the problem area at a glance

You can use Webform Validation. This module includes a lot of validations for webform elements.

Alternatively, you can code your own validation yous adding your validation function to the desired forms. Then use form_set_error to mark wrong element with red border.

Webform puts the fields inside a group, so if you need to mark a field as not valid you must provide the full hierarchy.

For example, for this field in $form:

$form['submitted']['form_contact_data']['form_contact_email'] = array(
...
);

You can mark it as erroneous with:

form_set_error('submitted][form_contact_data][form_contact_email', 'Error message');

In this example the filed is inside two groups: the first, 'submitted' is the main Webform group. The second, 'form_contact_data', is a field group created where I've placed contact data fields for this webform.


How do I periodically import from a source? In the basic settings of a feeds importer there is a select list:

Periodic import
Every 30 min
Choose how often a source should be imported periodically. Requires cron to be configured.

Merely selecting an option doesn't appear to import from my source every 30 minutes. It appears that I have to configure cron too. I've found a lot to read about this, but nothing that describes the basics.
What do I need to do to ensure my source is imported periodically? I can do a manual import without problem.

For periodic import of feed, you have to configure cron.

Let say you want to import feed in every 1 hour then configure cron to run after every 1 hour too.

In Drupal 7 you can enable cron via the Administration > Configuration > System > Cron (admin/config/system/cron).

For more information cron setup visit here


How can i get the value from the Dynamic query $query=db_select('node','n');
$query->join('field_data_field_cmp_playerid','b','n.nid=b.entity_id');
$query->join('field_data_field_cmp_id','c','n.nid=c.entity_id');
$query->join('field_data_field_cmp_userscore','d','n.nid=d.entity_id');
$query->join('field_data_field_cmp_usersupport','e','n.nid=e.entity_id');
$query->join('field_data_field_cmp_status','f','f.entity_id=c.field_cmp_id_nid');
$query->join('field_data_field_cmp_attend_time','g',' g.entity_id = n.nid');
$query->join('field_data_field_cmp_end_date','h',' h.entity_id = c.field_cmp_id_nid');
$query->fields('n',array('title','nid'),'d',array('field_cmp_userscore_value'),'e',array('field_cmp_usersupport_value'),'f',array('feld_cmp_status_tid'),'g',array('.field_cmp_attend_time_value'),'h',array('field_cmp_end_date_value'));
$query->condition('b.field_cmp_playerid_uid',$userid,'=');
$query->condition('n.type','Campaign_PlayerList','=');
$result=$query->execute()->fetchAll();

i use foreach loop to get the value of the query

foreach($result as $value)
{
    drupal_set_message(t('The variable is %va',array('%va'=>$value->title)));
    drupal_set_message(t('The variable is %va1',array('%va2'=>$value->field_cmp_userscore_value)));
    drupal_set_message(t('The variable is %va2',array('%va2'=>$value->field_cmp_end_date_value)));
}

the value i get is  "title" and i can't get the field_cmp_userscore_value and field_cmp_end_date_value value.

what could the problem be?

Thank you

The problem is that the following line is wrong:

$query->fields('n',array('title','nid'),'d',array('field_cmp_userscore_value'),'e',array('field_cmp_usersupport_value'),'f',array('feld_cmp_status_tid'),'g',array('.field_cmp_attend_time_value'),'h',array('field_cmp_end_date_value'));

You need to call fields() separately for each table. Right now, the additional arguments are ignored.

Also note that it is strongly recommended to use EntityFieldQuery to query field tables, that however has the limitation that you need to load the node object to get the field values.


How to update core and all modules and themes from CLI? On a LAMP environment I have a Drupal 8.5.6 website which is nearly all-core with the Bartik theme and a few stable contrib modules. Nothing is customized and I have daily backups so I don't "fear" of updating anything in one go this time.

I tried drush up * but got:

  Command "up" is ambiguous.

I didn't find an update command in Drupal Console documentation.

How could I upgrade all in one go from the CLI?

Assuming you are using Composer to maintain your Drupal 8 installation, you can use the following command to update core and all modules (and dependencies).
composer update drupal/* --with-dependencies

If you started you project from "drupal-composer/drupal-project" the command becomes the following.
composer update drupal/* webflo/drupal-core-require-dev --with-dependencies

I recommend reading https://www.drupal.org/docs/8/update/update-core-via-composer and https://www.drupal.org/docs/8/update/update-modules.
Always after updating, don't forget to run database updates and rebuild the cache.
drush updatedb
drush cache:rebuild

If you started your Composer project from drupal/drupal as the user guide says, you are in trouble, since drupal/core isn't listed as installed. You could try to use Composerize Drupal to fix the problem.
If you started your project from a tar-ball, you also need use Composerize Drupal if you don't plan to do manual updates forever.
Drush 9 doesn't support updating core or modules. It will tell you to use Composer. Anyway, reading the Drush docs is very useful.


In D7 what is the correct way to create a page template that has HEAD elements specific to that page? In Drupal 6 HEAD tags were part of the page.tpl.php.  Now that that has moved to the html.tpl.php in D7, what is the correct way to create templates that need different data in head tags?

Use hook_preprocess_html ( e.g in template.php ) to modify the html.tpl.php variables.

For different JS or CSS, check the path ( e.g current_path() == 'foo' ) and add with

drupal_add_js or
drupal_add_css

Set the 'every_page' option, and perhaps preprocess flag to FALSE.


I can't override the user_pass hook because I use a websevcice to manage my users, I need to override the user_pass() to send a new password via my webservices.
This is what i did:

/**
* Implements hook_validate()
*/
function beneficiaire_user_pass_validate($form, &$form_state){
    die('poc');
}

/**
* Implements hook_submit()
*/
function beneficiaire_user_pass_submit($form, &$form_state){
    module_load_include('inc', 'beneficiaire', 'ws');
    global $user;

    if(beneficiaire_reset_password($user->name)){
        drupal_goto('login');
    }
}

My module is named beneficiaire.
I've cleaned my caches many times
when I enter a username in the form, it returns me

  Sorry, %name is not recognized as a user name or an e-mail address

instead of

  poc

An idea ?

Thank you

The main error is that, since your module's short name is beneficiaire, those are the implementations of hook_user_pass_validate() and hook_user_pass_submit(), which aren't hook Drupal utilizes. If you rename the functions beneficiaire_validate() and beneficiaire_submit(), those would not be hooks which are used as validation and submission handlers for the password change form.
See @Clive's answer for how adding form validation and submission handlers, keeping in mind that the validation handler is added with $form['#validate'][] = 'beneficiaire_user_pass_validate';.

As side notes:

If you want to check a validation handler is called, use form_set_error("", "beneficiaire_user_pass_validate() called");
To redirect the user after submitting a form, set $form_state['redirect'] as in $form_state['redirect'] = 'login';


Changing from a Profile to Standard profile after the installation Its possible from moving from a custom profile or a Distro and move to a the Standards profile ?

The reason, I'm asking this is because I build a website with the Recruiter distro. At first everybody likes the workflow of the recruiter, then after a while my client ask me to change the entire workflow of the website. I have change some many things from the distro that is not longer useful to have the recruiter profile. I'm running issues with some incompatibility with some modules that the distro is not running the latest version. And I do not think that I need the distro any more.

I have try to move some modules from the profile/recruiter/module to sites/all/modules and the module does not seem to be working.

So my goal would be to remove the /profile/recruiter and move everything to /sites/all/modules & /sites/all/themes

I figure out how to do it. You will need to use the Profile Switcher module in order to achieve moving from one profile to another one.


OAuth2 Server sending 'null' as the 'sub' parameter instead of User Id When using OAuth2 Server module to authorize with users, I am not receiving the correct "sub" parameter in the response from the server. I get all the other fields such as email, email_verified, name, preferred_username, and zoneinfo; just not the sub parameter.
{
  "sub": null,
  "email": "someuser@email.com",
  "email_verified": true,
  "name": "SomeUser",
  "preferred_username": "SomeUser",
  "zoneinfo": "Asia/Dubai"
}

I've tried using hook_oauth2_server_user_claims to alter this parameter like so:
function my_module_oauth_server_user_claims($account, $requested_scopes) {
  $claims = [];

  if (in_array('profile', $requested_scopes)) {
    $claims['sub'] = $account->id();
    $claims['user_id'] = $account->id(); // for debugging purposes
  }

  return $claims;
}

Doing this adds the user_id parameter to the response body, but the 'sub' is still set as 'null', therefore it must get override afterwards.
I double checked the documentation and have all the permissions set, but can't find anything about this particular issue.. Why is `sub' not being populated correctly during this process?

The code invoking that hook is the following one, in the OAuth2Storage.php file, line 750 and forward.
    // Prepare the default claims.
    $claims = [
      'sub' => $account->{$sub_property}->value,
    ];

    if (in_array('email', $requested_scopes)) {
      $claims['email'] = $account->getEmail();
      $claims['email_verified'] = $this->configFactory->get('user.settings')
        ->get('verify_mail');
    }

    if (in_array('profile', $requested_scopes)) {
      if (!empty($account->label())) {
        $claims['name'] = $account->getDisplayName();
        $claims['preferred_username'] = $account->getAccountName();
      }
      if (!empty($account->timezone)) {
        $claims['zoneinfo'] = $account->getTimeZone();
      }
      $anonymous_user = new AnonymousUserSession();
      if ($anonymous_user->hasPermission('access user profiles')) {
        $claims['profile'] = $account->toUrl('canonical', ['absolute' => TRUE]);
      }
      if ($picture = $this->getUserPicture($account)) {
        $claims['picture'] = $picture;
      }
    }

    // Allow modules to supply additional claims.
    $claims += $this->moduleHandler->invokeAll('oauth2_server_user_claims', [
      'account' => $account,
      'requested_scopes' => $requested_scopes,
    ]);

    // Finally, allow modules to alter claims.
    $context = [
      'claims' => &$claims,
      'account' => $account,
      'requested_scopes' => $requested_scopes,
    ];
    $this->moduleHandler->alter('oauth2_server_user_claims', $context);
    return $claims;

Since the code first sets $claims to ['sub' => $account->{$sub_property}->value] and then adds any array key returned from that hook with $claims += $this->moduleHandler->invokeAll('oauth2_server_user_claims', ['account' => $account, 'requested_scopes' => $requested_scopes]); the hook cannot change the value for the sub key. You can verify how PHP behaves with the following simpler code.
$array = ['sub' => NULL];
$array += ['sub' => 10, 'id' => 10];
print_r($array);

To alter the sub key, the module should implement hook_oauth2_server_user_claims_alter().
function my_module_oauth_server_user_claims_alter(&$context) {
  if (in_array('profile', $context['requested_scopes'])) {
    $context['claims']['sub'] = $account->id();
    $context['claims']['user_id'] = $account->id();
  }
}


Delete unmanaged file after download? In a custom module I create a file and then use drupal_goto to download it. How can I delete the file after it is downloaded? Placing a file_unmanaged_delete after the drupal_goto doesn't get executed, and hook_file_download happens before the download for permissions checks and such. So I'm not sure how to do this. Do I have to resort to cleaning up files in a folder with cron somehow?

// Generate pdf card.
$file_path = $crm_card->generatePdfCard();
$filename = basename($file_path);
$headers = [
  'Content-Type' => 'application/octet-stream',
  'Content-Disposition' => 'attachment; filename="' . $filename . '"',
  'Content-Length' => filesize($file_path),
];

$binary_file_response = new BinaryFileResponse($file_path, 200, $headers);
$binary_file_response->deleteFileAfterSend(TRUE);

return $binary_file_response;


Monitoring field changes in custom content type I have custom content type with "price" field.

I would like to log the information about when the price has been changed (by administrator). All I need is date and old/new value of that field (for each entity of my custom content type).

But how to monitor such changes? Can I use any hook for it?

Step 1 - Detecting changes

You can make this work using the Rules module:

Rules Event: Before saving content.
Rules Condition (1st): "Entity has field", whereas you should specify these values:

"node" (saved content) for the "data selector" of entity.
the machine name of your price field.

Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different. For this you add an additional Rules Condition which is a Data comparison. And the actual data to be compared are:

original value of the field, which you should be able to find/select by first using as data selector the node-unchanged:...(unchanged content), followed by selecting the field name of your field from the additional list that is shown after you selected that node-unchanged:...(unchanged content).
updated value of the field, which you should be able to find/select by first using as data selector the node:...(saved content), followed by selecting the field name of your field from the additional list that is shown after you selected that node:...(saved content).

Step 2 - Logging changes

By using the Message module, you can create your custom logging of changes detected by the Rules module. For way more details on this, refer to the answer to "What is a good flexible way to send auto system emails to users?".


Prepopulate new Taxonomy Term's Parent via the URL I currently have a views page made up of taxonomy terms. Each term has a link next to it that redirects to the Add Term page. The add term page should auto-populate the parent of the corresponding term.

The Prepopulate module should make something like this possible and it works with all other fields, but not with the Parent select field for some reason.

I am using the following query parameter=?edit[parent][]=24 in the URL (where 24 is the value).

Any help getting this to work with Prepopulate, or using another method would be extremely helpful. Thanks in advance for any assistance.

I found out that the fieldset name must also be included, and for whatever reason the "[]" is also not required. To get it to work, I used the following:

?edit[relations][parent]=24


How can I show children in the taxonomy teaser views of parent/grandparent terms? Lets assume we have a Taxonomy called Region

Asia - Thailand - Bangkok

If a post is tagged with Bangkok, would it show up in the teaser view on following pages:

/region/
/region/asia/
/region/asia/thailand

or would it only show here?

/region/asia/thailand/bangkok

If later is the case, what's the best way to show it in parent terms teaser views?

Thanks for your help in advance.

You can try adding taxonomy as a hierarchical structure like

Term 1
Term 1-1
Term 1-2
Term 1-3

Term 2
Term 2-1

Then you can get the display using either

Taxonomy Menu Trails

And css as you wish.

Good Luck.


How to provide ubercart discount coupons only for specific users Anyone can say how to provide ubercart discount coupons only for applicable users and not for the other users ?. For example if a user from texas, then the admin can provide a coupon code only for that texas user and  it should not applicable for other out of texas users . please reply ASAP if anyone knows . thanks.

What you are looking for is a custom hook_uc_validate_coupon function. Ubercart coupon module allows for custom hooks here:

// Invoke validation hook.
  foreach (module_implements('uc_coupon_validate') as $module) {
    $callback = $module . '_uc_coupon_validate';
    $result = $callback($coupon, $order, $account);

So in your site module you would need to define a new hook function that validates whether the order (or possibly the user object?) is using a billing address from Texas. Roughly, clone the existing validation function and add logic to check the order for your conditions.

function YOURMODULE_uc_coupon_validate($code, $order = NULL, $account = NULL) {

if ($order->billing_state != 'Texas') { // or however you want to handle this
   $coupon = new stdClass();
   $coupon->valid = FALSE;
   $coupon->message = t('This coupon code is only valid in Texas.');
   $coupon->title = t('Unknown');
   return $coupon;
}

.. rest of validation function

}


How to format Computed Field as WKT (geofield CCK) with display code I'm pretty green here. This is my first question!

I am using computed field to calculate a WKT (Well known text) geofield using the geocoder API. This calculation is being done correctly, giving a result such as "POINT (28.12866 46.17625)".

When I want to display this computed field the only have the following options:

Unsanitized
Plaintext
Raw value, no display code
Filtered Markup
-Hidden-

I currently have the following display code, which I think it the problem:

$display_output = $entity_field_item['value'];

I don't know how to make the normal geofield formatters available to display this field, so for example I can render it as a map.

Geofield calculates various values with the geofield_compute_values() functions (see README), so calculating a WKT will not replace it properly. Geocoder supports computed field, so I guess you can use that to populate a geofield.


View: show title of field where user is entity-referenced I've got a content type of "Course" with entity references to users for Professor, TA, and Designer. Each user can be any of the three roles for any course.

I've got a View that shows, for the logged-in user, what courses they are the professor, OR TA, OR designer for.

What I'd like to add to that View is a column that tells the user which role they play in the course - or, in Drupal terms - which entity reference field their account is referenced in. I'd like to do this with exactly one column in the view.

The view already has Relationships from the Course to each of the referenced entities - but I am not sure how to get the conditional into a single column.

Is there a way to accomplish this with the Drupal 7 Views features, or do I need to re-write a column...?

So you can print the user reference fields, but that will show all users and their roles, and you only want to show the one?

This might seem a little hacky, but it should work.

First of all, add all three user reference fields, and add them to the same table cell using the views table settings.
Next, you need to hide the user reference fields that do not contain the current logged in users name. To do this, we will be overriding the fields with a tpl.php template. In your view, click on "advanced" and at the bottom, click on "theme: information". In the relevant row, you will find something like views-view-field--course--professor.tpl.php. Note that this is overriding the field, and has the view name type in it (which will not override any other views with the same field).
In your FTP, go to the views module folder. Click on the "theme" folder, and find the file views-view-field.tpl.php. Copy this file to your themes template folder, and rename it views-view-field--course--professor.tpl.php, or whatever your field name was in step 2. Then flush your cache. This should now be overriding that field in the view. (To make sure, you could edit that file, and add some text below the <?php print $output; ?> to see if it worked.)
Now that we are overriding the field, we can influence what will be shown in that field. I would replace <?php print $output; ?> with the following....

<?php
global $user;
$username = $user->name;

if (strpos($output, $username) !== false) {
  print $output;
}
?>

I haven't tested the above, but something similar to that should print the fields output, only if the current logged in users username matches the output.


What is the goal of template_preprocess_page(&$variables)? I am trying to modify the login and register page drupal 7 but i actually don't understand what is the goal of template_preprocess_page(&$variables) ... Someone can give me a better explanation of that ?

It is an entry point in your theme or module that allows you to modify or add template variables before the page (or applicable item) is rendered. This hook affects any page*.tpl.php files.

Similarly, template_preprocess_node is the same, but for node templates.

Example:

I need to change existing variable foo:

function mytheme_preprocess_page(&$variables) {
  // $foo used to be 'Old Value'
  $variables['foo'] = 'New Value';
}

I need to add new variable:

function mytheme_preprocess_page(&$variables) {
  // $baz does not yet exist
  $variables['baz'] = 'Baz!';
}

These are injected into the template, then they can be rendered with render or printed:

page.tpl.php:

<?php print $foo; ?>
<?php print $baz; ?>

This is because $variables are passed by reference (note the & symbol) which allows you to modify the array.


Products containing a hyphen or numbers not shown or wrong relevance I have an external Apache Solr Server, with Search API and Search API Views.

When we search for ordinary products, they are shown correctly, with the correct descending relevance order.

When we search for a product with the exact name: "Productx-123W"
it is showing in this order (with highlighted terms by search function):

Productx-123D
Productx-123S
Productx-123
Productx-123W

So the exact product name is only shown on the 4th place, while all other products with no hyphens or - in them have the correct displayed order in the results.

It is like the hyphen splits the word in two.

Secondly, I have a product: Product20001w
When I look for this search term: "2000" nothing is shown. It's like the numbers on the end confuse the server.
When I look for "2001w", it shows the right products which have partially this "2001w" in their name.

Anyone knows how to fix this?

It is basically a feature of Word Delimiter Filter to allow matching of words on case-change, alphanumeric boundaries, and non-alphanumeric chars, so when typing "wifi", "wi fi" could match documents containing "Wi-Fi". That is why Product-123A is split to match more products. See: Intra-Word Delimiters.

So you can either disable WordDelimiterFilter, or customize it. For example:

<filter class="solr.WordDelimiterFilterFactory"
        protected="protwords.txt"
        generateWordParts="1"
        generateNumberParts="1"
        catenateWords="0"
        catenateNumbers="0"
        catenateAll="0"
        splitOnCaseChange="0"
        preserveOriginal="1"/>

Since the second part of your word consist number (e.g. 123W), you may try to enable catenateWords and catenateNumbers (set to 1) in your schema.xml file and apply the changes to your hosted Solr server.

You can also provide some customization usingwdftypes.txt file, see: SOLR-2059.

However, if you want to keep the feature as it is (without modifying any Solr config files), you can also consider increasing the score for certain fields, such as titles (e.g. a product name). So your Productx-123W phrase after a word split will match higher on documents with partial matches such as 123W in specific fields.

Related posts:

Search with various combinations of space, hyphen, casing and punctuations
Quering numbers containing hyphens with SOLR WordDelimiterFilterFactory isn't working?


Use the full name instead of the user name as author of articles I'm coming to Drupal from Joomla.  To be honest, Drupal is a little more daunting.

I simply wish to have the author's name appear in the articles (ie, written by RealName) instead of the default (written by username).

I already have the real name field created, and can display the real name if I click on user info.

Any idea how I can have "written by realname" on articles?

There's a module for that - RealName

  The RealName module allows the administrator to choose fields from the user profile that will be used to add a "real name" element (method) to a user object. Hook_user is used to automatically add this to any user object that is loaded. It will also optionally set all nodes and comments to show this name.

EDIT - since your new to Drupal you might want to checkout - http://drupalmodules.com/ - great way of finding modules that you might need.


Display roles in profile? I'm trying to display roles in the default user profile (no profile2) with consistent formatting to the other fields being displayed.

In user-profile.tpl.php I have this:

<div class="profile"<?php print $attributes; ?>>
    <?php
    // var_dump($user_profile); exit;
    $account = user_load(arg(1));
    $roles = '';
    foreach ($account->roles as $rid => $role) {
        $roles .= "
".$role."
";
    }
    if (count($roles) > 0) {
        $user_profile['field_user_roles'] = array(
            '#entity_type' => 'custom',
            '#bundle' => 'custom',
            '#theme' => 'field',
            '#field_type' => 'text',
            '#title' => 'Roles',
            '#label_display' => 'above',
            '#field_name' => 'field_user_roles',
            '#markup' => '
' . $roles . '
',
            '#weight' => 5,
        );
    }

     ?>
  <?php print render($user_profile); ?>

Which is giving me this output (which is close):

The problem is that it doesn't seem to be using #markup to display the field.

I'm getting these errors which indicate I'm doing something wrong:

  Notice: Undefined index: #items in template_preprocess_field() (line 1060 of /path/to/site/modules/field/field.module).

  Warning: Invalid argument supplied for foreach() in template_preprocess_field() (line 1060 of /path/to/site/modules/field/field.module).

  Notice: Undefined index: #view_mode in zurb_foundation_preprocess_field() (line 311 of /path/to/site/sites/all/themes/zurb_foundation/template.php).

I'm also using the Foundation Drupal template (v7.5) which seems to relate to the above errors.

Updated answer

Scrolling through the Drupal.org module library, I discovered Role expose. I have never used it, but it seems to do the trick as well:

  Role Expose -module gives site administrators ability to expose user
  their own user roles. Roles are listed on user profile page. Users may
  be granted an option to view own roles or all users roles.

Original answer

Looking at the render array, I feel you misunderstood a bit (unless you have configured a field on the user object where you already put a string of all his roles, but then you would not need the logic here)...

$user_profile['field_user_roles'] = array(
  '#entity_type' => 'custom',          // Nope, it is 'user'.
  '#bundle' => 'custom',               // Nope, it is 'user'.
  '#theme' => 'field',                 // Probably it is not a field, but a custom render element containing markup.
  '#field_type' => 'text',             // Probably not since it probably wasn't a field.
  '#title' => 'Roles',
  '#label_display' => 'above',
  '#field_name' => 'field_user_roles', // Probably not since it probably wasn't a field.
  '#markup' => '
' . $roles . '
',
  '#weight' => 5,
);

I guess it works better if you remove some of the data (see below).

On a small side note, logic should be avoided as much as possible within template files. So I'd recommend creating a small custom module and implementing hook_user_view_alter(). (If you are planning on supporting only one theme, you can also place it in the theme's template.php file. Use the theme name as the module name.)

function MODULENAME_user_view_alter(&$build) {
  // Obtain the account that user_view() stored for us.
  $account = $build['#account'];

  // Prepare roles string.
  $roles = '';
  foreach ($account->roles as $rid => $role) {
    $roles .= "
".$role."
";
  }

  if (count($roles) > 0) {
    $build['modulename_user_roles'] = array( // Prefix with module name to prevent collisions.
      '#type' => 'item',
      '#title' => 'Roles',
      '#markup' => '
' . $roles . '
',
      '#attributes' => array('class' => 'class-one class-two'),
    );
  }
}

Additionally you can implement hook_field_extra_fields() to expose the property on example.com/admin/config/people/accounts/display and choose its weight within the admin interface.

function MODULENAME_field_extra_fields() {
  $extra['user']['user'] = array(
    'display' => array(
      'modulename_user_roles' => array( // Make sure the name matches your custom property
        'label' => t('User roles'),
        'description' => t("Lists the user's roles."),
        'weight' => 5,
      ),
    )
  );

  return $extra;
}

Combined, the property should have been added to the $user_profile array and there is no more need to override the template file.

If you want to use the item_list, as proposed by Yogesh, your render array in MODULENAME_user_view_alter() should look something like this:

    $build['modulename_user_roles'] = array(
      '#title' => 'Roles',
      '#theme' => 'item_list',
      '#items' => $account->roles,
      '#type' => 'ul',
      '#attributes' => array('class' => 'class-one class-two'),
    );


Remove the link "add comment" if the user has already commented on the node I wish that my users can leave only one comment per node (including by using the url).

Once their posted comment, I wish that the link "add comment" disappears.

I tried numerous solutions, such as Onecomment or custom code, but all prevent the second comment at the level of the form (form validate), with an error.

I would like for better user experience than it is not upstream possible to click on "add comment".

Do you know a solution ?

If you are OK with custom modules, you can make the module below.
If you have never made a custom module before, just make a folder called single_comment and create 2 files inside called single_comment.info and single_comment.module then add the code below into the respective files.

single_comment.info

name = Single Comment
description = Allow users to only add one comment to a node.
core = 7.x

single_comment.module

function single_comment_node_load($nodes, $types) {
  global $user;
  if (user_is_logged_in()) {
    foreach ($nodes as $node) {
      $comment_arr = comment_load_multiple(comment_get_thread($node, COMMENT_MODE_FLAT, 100));
      foreach ($comment_arr as $comment) {
        if ($comment->uid == $user->uid) {
          $node->comment = COMMENT_NODE_CLOSED;
          break;
        }
      }
    }
  }
}

You can call the module whatever you like but just remember to replace anywhere single_comment occurs. That includes the folder, file names, name in .info and the function name.


List module releases that are "Recommended by the project’s maintainer." On the project page of a Drupal module there is a list of releases.  The project owner can set for each one whether it is recommended, and the page displays that fact.  For example if there are releases 2.0 and 3.0, it's possible for either one to be recommended or both.
I would like to know which releases are recommended without having to visit the project page of each module one-by-one.  I would be interested in any type of answer: GUI, command line, API, etc.
I have already tried

The GUI (/admin/reports/updates).  It lists releases that are "also available" but does not indicate which are recommended.
composer.  It seems to have no idea of recommended.  With my settings, it appears to pick the newer release except if it is less stable.
drush.  In drush 8, the rl command lists recommended releases but seems to be broken with current Drupal 8.  Newer drush does not have this command.
Code.  The return value of update_get_available() or update_calculate_project_data() don't seem to contain this information.

As described in Update status XML, Drupal.org returns information about project releases, including the recommended major version, as XML output. For example, the first XML elements returned from https://updates.drupal.org/release-history/imagemagick/8.x are the following one.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<api_version>8.x</api_version>
<recommended_major>3</recommended_major>
<supported_majors>3</supported_majors>
<default_major>3</default_major>
<project_status>published</project_status>

<recommended_major>3</recommended_major> is referring to any version matching 8.x-3.*.
Unfortunately, that information isn't returned from https://updates.drupal.org/release-history/imagemagick/current or any URL matching https://updates.drupal.org/release-history/*/current.
<title>ImageMagick</title>
<short_name>imagemagick</short_name>
<dc:creator>sun</dc:creator>
<type>project_module</type>
<supported_branches>8.x-3.</supported_branches>
<project_status>published</project_status>
<link>https://www.drupal.org/project/imagemagick</link>


Trying to write custom handler to extend views_handler_field_term_node_tid Edit: solved, see first reply for answer.

I am trying to write my views filter handler to extend the views_handler_field_term_node_tid class. I believe I have done everything correctly but I'm having no luck. In my module I have implemented hook_views_api()

/**
* Implements hook_views_api().
*/
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', mymodule') . '/views',
  );
}

Called the handler.inc file and the mymodule.views.inc in the module .info file:

files[] = views/mymodule.views.inc
files[] = views/mymodule_handler_field_term_node_tid.inc

This is the contents of that file:

class mymodule_handler_field_term_node_tid extends views_handler_field_term_node_tid {

  function option_definition() {
    $options = parent::option_definition();
    $options['convert_spaces'] = array('default' => FALSE, 'bool' => TRUE);

    return $options;
  }

  /**
   * Option to replace spaces with hyphens.
   */
  function options_form(&$form, &$form_state) {

    parent::options_form($form, $form_state);

    $form['convert_spaces'] = array(
      '#title' => t('Convert spaces in term names to hyphens'),
      '#description' => t('This allows links to work with Views taxonomy term arguments.'),
      '#type' => 'checkbox',
      '#default_value' => !empty($this->options['convert_spaces']),
    );

  }

  function render_item($count, $item) {
    return $item['name'];
  }

}

And finally I have implemented hook_views_data_alter() in the mymodule.views.inc

/**
 * Implements hook_views_data_alter()
 */
function mymodule_views_data_alter(&$data) {
  $data['node']['term_node_tid'] = array(
    'title' => t('Taxonomy terms on node'),
    'help' => t('Relate nodes to taxonomy terms, specifying which vocabulary or vocabularies to use. This relationship will cause duplicated records if there are multiple terms.'),
    'relationship' => array(
      'handler' => 'views_handler_relationship_node_term_data',
      'label' => t('term'),
      'base' => 'taxonomy_term_data',
    ),
      'field' => array(
      'title' => t('All taxonomy terms'),
      'help' => t('Display all taxonomy terms associated with a node from specified vocabularies.'),
      'handler' => 'mymodule_handler_field_term_node_tid',
      'no group by' => TRUE,
    ),
  );

}

So the weird issue is that running dpm($data); in my mymodule_views_data_alter function before I alter the $data['node']['term_node_tid'] brings up no reference to that data at all. That is being originally defined in taxonomy.views.inc and should be existing in the $data array because I have added the Content: All taxonomy terms field to my test view. I've been pulling out my hair for the last couple hours trying to figure this out with no luck.

You must adjust your module's weight so that it runs after views. Use hook_module_implements_alter or Modules weight

And then you can also change your code in MYMODULE.views.inc to something simpler:

function MYMODULE_views_data_alter(&$data) {
  $data['node']['term_node_tid']['field']['handler'] = 'MYMODULE_handler_field_term_node_tid';
}


Importing non-unique terms with Feeds Importer I'm trying to import a large chunk of data to our site using Feeds Importer. However, I've come to a small problem when trying to map a piece of our data to a collection of taxonomy terms.

The problem is as follows:

We have a vocabulary called Categories with two levels. Every parent term has a list of child terms.
In some of our terms, both the parent and the child have the same name, e.g.:

parent; child
Cozinhas; Cozinhas

This is absolutely necessary as we need both the main category and the sub category to be listed and presented in this fashion.

With Feeds Importer we simply import all the main (parent) categories once and the every sub (child) categories related to it (e.g.: "Casas de Banho" -> "Banheiras"). However, in this case, it simply maps the term to the parent and lists it twice. We are using Hierarchical Select to save the terms, so we use Tamper to explode the terms we've imported and send it to the correct field.

I've tried importing the alias of the sub-category term ("Cozinhas-0") and the unique ID to map it correctly but it simply doesn't work that way, it seems it has to be the term name.

Is there any way to map this correctly?

tl;dr:

We need to import several values, with Feeds Importer, into a single Hierarchical Select field and we need them to be unique, in order to map same-name taxonomy terms to their correct ID. Is there a way to do this?

Obviously, there is a way to map by term ID on the mapping settings of the Feeds Importer.

Problem solved!


Filter view based on several user profile fields (D7) I’m trying to apply automatically several filters to a view based on the corresponding profile fields selected by the current user.
For example, the users can select a favourite color (yellow, blue...) and a favourite food (fruit, meat...). If a user have selected that he likes "yellow" and "fruit", he should see in the view only the nodes that match both criteria (yellow fruits): bananas, lemons...
This is pretty easy to do when there's only 1 field to match (following the process indicated here), but this same process doesn't seem to work for matching several fields (the content field of the view only allows 1 relationship).
I've tried creating relations between relationships (like "chain relationships") and doesn't seem to work, but maybe I'm doing something wrong (I don't have a really deep understanding of how relationships work).
Any ideas?
Maybe using the Relation or Entity Reference modules? Or some PHP code?

You should try chain relationship, this discussed here, similar problem to yours.
Here the answer on similar question on drupal.stackexchange.


How do I apply check_markup() as Twig filter? I am trying to modify output in my twig file. In D7, I was able modify data in my array with this

check_markup($tweet->text, 'full_html');

and I see that this function still exists in D8. However, I'm not sure how I would use this in a filter in twig. This is what I have so far:

{% for tweet in params.tweets %}

    {{ tweet.text }}

{% endfor %}

I actually tried to do this before I sent it to the template as well, but it didn't change anything:

 foreach($tweets as $tweet) {
  $tweet->text = check_markup($tweet->text, 'full_html');
  $cleanTweets[] = $tweet;
}
dpm($tweets);
$params = array('tweets' => $cleanTweets);
$tweet_template = array('#theme' => 'twitter_pull_tweet_listing', '#params' => $params);
return $tweet_template;

What I'm trying to do here is make drupal create links for web links in the twitter tweet text. This worked fine for me in D7.

First of all, what is the motivation here? Are you getting double escaping or something? Providing more background information may help to get you a better answer.

Before we get too much further, relying on a certain configuration of the full_html text format seems like it's not a good solution. For example, to get the below to work for automatically creating links for this scenario, I had to enable Convert URLs into links in the full_html text format.

If you take a look at the documentation for check_markup() you'll see this note:

  Note: this function should only be used when filtering text for use elsewhere than on a rendered HTML page. If this is part of a HTML page, then a renderable array with a #type 'processed_text' element should be used instead of this, because that will allow cache tags to be set and bubbled up, assets to be loaded and #post_render_cache callbacks to be associated. In other words: if you are presenting the filtered text in a HTML page, the only way this will be presented correctly, is by using the 'processed_text' element.

So based on that I think what you may want to do is in your block build method create a 'processed_text' element (render array):

foreach ($tweets as $tweet) {
  $cleanTweets[] = array(
    '#type' => 'processed_text',
    '#text' => $tweet->text,
    // Relying on the full_html text format to do certain things is probably
    // not a good idea.
    '#format' => 'full_html',
    // Potentially add keys for #filter_types_to_skip and #langcode.
  );
}
$params = array('tweets' => $cleanTweets);
return array('#theme' => 'twitter_pull_tweet_listing', '#params' => $params);

Then you can do this in your Twig template (twitter-pull-tweet-listing.html.twig):

{% for tweet in params.tweets %}
  …
  {{ tweet }}
  …
{% endfor %}

To relate this to Drupal 7, that Twig template code would be roughly equivalent to running render() on each array element (individual render array) in the $cleanTweets array.

If you're more interested in creating an actual Twig filter, the Twig documentation has some information on that, and Symfony has some very comprehensive documentation that matches up with how you would create a Twig extension in Drupal 8.


How to make autocomplete search by an entity field instead of by name? Let's say we have 3 custom entities:

When creating a new operator, I need to autocomplete the license:

By default we can use the autocomplete to find by name. So, we need to type the name to display the related results.

But here I'd like to autocomplete by authority name instead (since a license has no name).

Is it possible? If so, how to do it?

Create a new view with the display type "Entity Reference"
Add "Fields", "Filter criteria" and "Sort criteria" like in any other normal view
Under "Format > Settings", select the fields you want to be searchable
Under "Show > Settings", select the fields you want to show as search result
Save the view
Now visit "Structure > Content type > NODETYPE > Manage fields"
Edit your entity reference field, set the "Reference Method" to "Views: filter by an entity reference view"
Select your previously created view


What is the right place for Product Image We can take image of product through Product Type or Product Display content type, I just want to know what is the right place for product images fields ?

It is related to want you want, if you want have a product display with some variation that each variation  different with each other ( different image) it is better put product image field in product , but if all product variation has equal image (or you have not product display  with multi variation product ) it is better put image field in product display content type .

I hope this can helped you.


Javascript running twice when not logged in I have this issue that any custom js (added into theme.info file) script file is runned twice. However, I noticed that it will be runned only once if I am logged in. This happens in Drupal 7.

What is the cause?

The js script is a clear only having alert("Entered js file");

Also it is not added twice in the info and also looking into source code not there twice either.

The function is triggered while nothing rendered on page and second time when all DOM elements are loaded.

I finally found out what was causing this issue. It was a module named Drupal for Firebug.
So, if anyone finds this, disable this module and you will be fine.


drush for several drupal I have drupal 7.54 that are placed in  /var/www/html which I use as main site.
Also I have drupal 8 (for testing) that are placed in /var/www/html/drupal8  where I have drush.

And there is some problem. When I tried to launch command "drush status" it gives me information about drupal 7. And it happens regardless directory of drush.

How to specify version of drupal on which drush must operate?

And I want to notice that I installed drush not via composer but just downloaded and unzipped it.

First I assume you have drush 8 since that is required for both D7 and D8.  It's also the default on drush.org.

The best way to deal with multiple Drupal sites is via Drush Aliases.

Basically you create a .drush directory in your home directory and create a aliases.drushrc.php file in it.  For each site, have an entry with the minimum information of:

$aliases['d7'] = array (
  'uri' => 'yoursite.dev',
  'root' => '/path/to/drupal/root',
):

There are a lot more options but those are the required ones for local sites.

To use them, run drush commands using the @alias option.  E.g.:

drush @d7 status

This will let you switch between multiple local sites.


How do I access a view's results with a custom module? I'm creating a module that will expose a feed of content (under certain rules) as a JSON response. I want to use a Drupal 8 view to construct a query for that set of content, since it is a complicated set of rules.

Is there a way to query a Drupal 8 view in a custom module and iterate over the results?

Note that I am not trying to modify the output of the View with PHP; I just read the results and package them into a JSON response in my custom module.

I'm looking for something similar to entityQuery where I can instantiate a view object, execute it, and then iterate over the nodes that are in the result set.

Most of the searching I've done here and on Google points to Drupal 7 answers (which might not be relevant to Drupal 8 code), or otherwise generic Drupal query examples (when I am specifically looking for the Views module).

As an example, I'm looking to be able to do something like this (pseudocode):

class MyCustomModuleController {

  public function getFeed() {
    $view = View::get('my_view_name');
    $nodes = $view->execute();
    $response = [];
    foreach ($nodes as $node) {
      $response[] = $node->getSomeField();
    }
    return $response;
  }

}

$view = \Drupal\views\Views::getView('my_view_name');
$view->execute();

foreach ($view->result as $row) {
    //dont remeber if $node is fully loaded
    $node = $row->_entity;
    // if not, add this
    $node = Node:load($row->_entity->id());
    $response[] = $node->[FIELD]->view('full'); // full display
}
return $response;


How to get all the fields defined by a particular module? Suppose i have a module1 where i define fields and i get list of all the fields in module2 using module1_fields_info(); this is done in D7. How to get list of fields defined by module1 in module2 in Drupal 8?

hook_field_info() defines field types in Drupal 7, so I think you're actaully interested in field types, not fields?

If so, field types, like any other plugin definition have a provider key, if you want to get the field types of a certain modules, call \Drupal::service('plugin.manager.field.field_type')->getDefinitions() and then filter on the provider key:

$field_types = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();
$field_types = array_filter($field_types, function (array $definition) {
  return $definition['provider'] == 'yourmodule';
});

Code example written in browser and untested.


What is the right way to get number of items from a field? In code review I saw a developer using count($paragraph->field_events) to get the number of referenced entities.

I thought, surely that can't work, that can't be right.  So the question is, what is the correct way to get the number of items from a field on an entity?

Using count() on a field is acceptable because there is an implementation of Countable::count in the ListInterface implemented by ItemList class where it overloads the count method to count the items, from which FieldItemList and EntityReferenceFieldItemList inherit.

So you can use:

$paragraph->field_events->count()

or

count($paragraph->field_events)

synonymously.  They do the same thing.

From ItemList.php:

public function count() {
  return count($this->list);
}

If you'd like test this, you can play with this simple class.  If you remove the "Implements Countable" calling count(a) on object a doesn't return the count() method, but if you add it back, it does.  So on a low level, Drupal is using this so you can call count() on fields.


How to debug queries and exports sent to Salesforce? I'm using Salesforce Suite module.

My initial investigation says that the connection is encrypted via HTTPS.

Is there any easy way of debugging what is exactly sent to Salesforce?

I ended up by tracing the code via XDebug, but it's useless on environment which doesn't have it.

The module uses SalesforceSoapClient.

If you're using Ubercart / Salesforce Integration, you can use the following patch:

Drupal 6

--- a/uc_salesforce/uc_sf_order/uc_sf_order.module
+++ b/uc_salesforce/uc_sf_order/uc_sf_order.module
@@ -635,6 +635,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
     // Export the object to Salesforce.
     try {
       $response = $sf->client->create(array($object), $map->salesforce);
+      drupal_alter('uc_sf_order', $response, $sf);
     }
     catch (Exception $e) {
       drupal_set_message(t('Error exporting order to Salesforce.'), 'error');
@@ -681,6 +682,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
         }
         try {
           $product_responses = $sf->client->create($product_objects, $uc_order_products_fieldmap->salesforce);
+          drupal_alter('uc_sf_order', $product_responses, $sf);
         }
         catch (Exception $e) {
           sf_dpm($e->faultstring, 'Ubercart order line item exception');
@@ -718,6 +720,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
       else {
         $user_object_export = salesforce_api_fieldmap_export_create($user_map_id, $account);
         $user_response = $sf->client->create(array($user_object_export), $user_map->salesforce);
+        drupal_alter('uc_sf_order', $user_response, $sf);
         $account_sfid = $user_response->id;
       }
     }

and then you can define the following function:

<?php
/**
 * Define debug constant
 * To activate, run: drush -y vset foo_debug 1
 */
define('FOO_DEBUG', variable_get('foo_debug', FALSE));

/**
 * Implements hook_TYPE_alter().
 */
function foo_uc_sf_order_alter($response, $sf) {
  $xml_request = $sf->client->getLastRequest();
  $xml_response = $sf->client->getLastResponse();
  FOO_DEBUG ? watchdog('foo', "UC Salesforce XML request/response:\n
Request:\n@req\n
Response:\n@res", array('@req' => $xml_request, '@res' => $xml_response), WATCHDOG_NOTICE) : NULL;
}
?>

To activate debug messages, run the following drush command:

drush -y vset foo_debug 1

And run watchdog messages in foreground before your test:

drush watchdog-show --tail --full

Read more:

Add hook_alter for catching and debugging the requests and responses.


Creating content via PHPMYADMIN I'm trying to add content to my Drupal 8 from the PHPMYADMIN.

You may be wondering Why this way? The fact is that I have a web in Drupal 6 and I tried a lot to migrate using the tools Drupal has, without success.

I'm not so good at programming, and the time is passing, so I decided to try the manual approach.

I created an article and inspected the database and saw what tables where altered to discover which tables where affected when I create an article.

Then I proceeded to manually create them.

The involved tables where:

node
node_revision
node__body
node_revision__body
node__comment
node_revision__comment
node_field_data
node_field_revision
node__field_tags
node_revision__field_tags
taxonomy_term_field_data
taxonomy_index
taxonomy_term_data
taxonomy_term_hierarchy
comment_entity_stastics

I noticed that "menu_tree" and "cache_entity" are altered when creating an article, but I do not know how to manually insert data there because they have blob data.

After that, I re-built the cache, but the content I created wouldn't show.

I wonder if there are some tables I'm missing, or if with this method I won't be able to achieve what I'm trying to accomplish.

If I have to choose between spending time in trying to learn something hard for me (something I don't know if will be or not 100% a success) and manually creating the 1500 articles with the Drupal 8 UI, then I would stick with the second option, because manually creating content is 100% secure and won't consume my desire to live the way the alternatives I'm trying with no effort are doing.

But there may be something. to automatize the process at least a bit. Is there?

What should I do?

I wonder if investigating the import.php as some kind of method to which I can pass and array of info and achieve what I'm trying to do!

Ps: I have already tried with the Migrate, Migrate Plus, etc with no result.

Don't even bother. This level of effort is not even necessary.

If you are just moving content from Drupal 6 to Drupal 8, use the built in Migration modules that come with core. It is designed to do this. I can't even quantify how long this would take to do in PHPMYADMIN of all things. You'd likely wind up corrupting the database itself. The schema is nowhere near as simple as it once was.

Please try using the tools and check the docs for more: https://www.drupal.org/node/2257723

All you have to do is point it at your Drupal 6 database and let it work. If you have basic content (sounds like Articles and blog posts) it should work very well. It will even build out the content type and taxonomy for you.

Even if the automatic route doesn't totally work, still attempt to use the Migration tools available to you. You will save a ton of hours (probably hundreds) vs editing a database manually.


Drush: Permission denied outside htdocs I've been trying to solve this problem for hours now.

I successfully installed Drush locally and it works fine when I'm using it within XAMPP's htdocs folder. However, I want to move the Drupal folder to a virtual host outside htdocs. When I run drush inside the new folder, it says:

$ drush status

PHP Warning:  pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///usr/local/bin/drush/includes/startup.inc on line 359

Warning: pcntl_exec(): Error has occurred: (errno 13) Permission denied in phar:///usr/local/bin/drush/includes/startup.inc on line 359
Error has occurred executing the Drush script found at /Users/ivan/drush
(errno 13) Permission denied

Tried to change folder owner to admin group, chmod -R 777 - nothing worked. I am running on OS X 10.11.6 and XAMPP 5.6.12.

Thank you for any help.

It seems you have two Drush installations - /Users/ivan/drush and /usr/local/bin/drush I'm guessing that /Users/ivan/drush isn't executable and hence causing the error. I suggest just removing /Users/ivan/drush.


How to create slideshow with views using images from node's field I have a field in Page content type. Field's type is Image. It can contain unlimited number of images. I want to use this field for Slideshow (module views_slideshow). I need to create view for showing content of this field sorted by field's delta and showed like Slideshow. I have a problem with sorting, and showing field items as images (I also need to apply images style to my images).

Is it possible?

You might have more luck with galleryformatter it's easy to use and works.

The module allows you to select a gallery formatter for an image field.


Drupal 7 at shared hosting behind Cloudflare I use Drupal 7 at a share hosting account (with apache server) and I use Cloudflare.com CDN.
Cloudflare ip token (at webform etc) shows cloudflare IP instead of visitor's original IP.

At settings.php I put

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_header'] = 'HTTP_CF_CONNECTING_IP';

These did not seem to work.

What seems to work was:
the instructions given by cloudflare for PHP

if ($_SERVER["HTTP_CF_CONNECTING_IP"]) {$_SERVER["REMOTE_ADDR"] = $_SERVER["HTTP_CF_CONNECTING_IP"]; }

or alternatively what was written at drupal cloudflare module (which is only for drupal 6 and not 7)

$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"] ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];

The questions are

why the typical drupal settings ($conf['reverse_proxy_header) did not work, and how can I make them work?
If not, then which of the 2 solutions that worked for me is more secure or better?
Should I setup $conf['reverse_proxy_addresses'] with cloudflare ips,
or it's useless since $conf['reverse_proxy_header'] does not work
anyway?

Why don't you install the CloudFlare - Free Reverse Proxy, Firewall, and Global CDN module? The module comes with instructions on how to solve this problem:

Installation Instructions:

  Install and Enable this module. Add one line of code at the end of
  your settings.php file:

$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"] ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];

  Save your email address and CloudFlare API key to the CloudFlare administration screen on your Drupal web site (admin/settings/cloudflare).


How do I automatically change the background image of body? How do I automatically change the background image of body, when I click on a menu link?

I want to obtain the same effect shown in the Drupal Design Camp Boston 2011 site.

This is the code that is added directly to the page and is not part of a seperate script.

<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-image', 'url("/sites/default/files/palm1.jpg")' ) });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-color', '#2a2f1d' ) });
//--><!]]>

The place where you want do this is inside your theme's template.php file under the function MYTHEME_preprocess_page(&$variables)

then add something like

$script_bg_img = "jQuery(document).ready(function () { $('body').css( 'background-image', `url('/sites/default/files/palm1.jpg')` ) });"
drupal_add_js($script_bg_img);

or put the javascript in a separate file, then add
   drupal_add_js(PATH_TO_FILE . '/FILENAME');


Calculate redirect hash in drupal 7? I'm upgrading my site from D6 to D7, and want to move a section of the site to a better spot. That requires about 10000 redirects. (I use redirect module: https://drupal.org/project/redirect ).

With D7, the redirect table includes a hash ("hash - A unique hash based on source, source_options, and language."). How can I build that, using PHP? I have a textfile with node/# and the old URLs. I can make them into a mysql table.

But while I can do basic PHP, I'm not advanced enough to understand the redirect.module source. The relevant bits are, I understand, lines 399-403:

$redirect->source = $path['original']['alias'];
$redirect->redirect = $path['source'];
$redirect->language = $path['original']['language'];
// Check if the redirect exists before saving.
$hash = redirect_hash($redirect);`

and lines 1069-1081:

function redirect_hash($redirect) {
  $hash = array(
    source' => $redirect->source,
    language' => $redirect->language,
  );
  if (!empty($redirect->source_options['query'])) {
    $hash['source_query'] = $redirect->source_options['query'];
  }
  drupal_alter('redirect_hash', $hash, $redirect);
  redirect_sort_recursive($hash, 'ksort');
  $redirect->hash = drupal_hash_base64(serialize($hash));
  return $redirect->hash;
}

Thanks!

Usually there is always a module that can help out.

In your case I recommend Path Redirect Import. It has a bulk import mechanism for redirects via CSV. It supports the Drupal 7 redirect module.

To get the redirects exported from D6 in the right format, check the Path Redirect Export module.

I believe that should do the trick for you.

I hope this helps you.


Find out if a view returns any results and if it doesn't disable a link to that view I have a panels page with two view panes on it. The first view pane lists taxonomy terms. When you click on one of the taxonomy terms the second view pane will display a list of content for that taxonomy term.

Is there any way that if there is no content for one or more of the taxonomy terms then those links can be disabled/hidden from the first view pane?

The second view pane uses the term ID from the links in the first view pane as an argument to filter the content for that term.

I'm not quite sure how to go about doing this. One way I had thought was to use jQuery and Ajax to somehow call a function in Drupal to find out if the view returned any result and then hide the link. But I haven't attempted this before in Drupal.

There is another slight complication in that the panels display are for organic groups and the second view pane only shows content for the taxonomy term clicked on and also content that is associated with that group. So that any function that finds if there are any results would need to pass in both the argument for the term ID and also the ID for the group, which the view was getting from the context.

Any help would be much appreciated, or even an outline of an approach I could take.

The one solution is hide empty terms. You can hide empty terms as shown here

Another solution is use php in your view or views template, use taxonomy_select_nodes function.

  Return nodes attached to a term across all field instances.

The tid can get from view. If the function return empty , dont provide link for that term.

Otherwise you can link term to your second view.


How to structure git repositories for project? I'm working on a content synchronisation module for Drupal.  There is a server module, which sits on ona website and exposes content via a web service.  There is a also a client module, which sits on a different site and fetches and imports the content at regular intervals.

The server is created on Drupal 6.  The client is created on Drupal 7.  There is going to be a need for a Drupal 7 version of the server.  And then there will be a need for a Drupal 8 version of both the client and the server once it is released next year.

I'm fairly new to git and source control, so I was wondering what is the best way to setup the git repositories?  Would it be a case of having a separate repository for each instance, for example:

Drupal 6 server = 1 repository
Drupal 6 client = 1 repository
Drupal 7 server = 1 repository
Drupal 7 client = 1 repository
etc

Or would it make more sense to have one repository for the server and another for the client then create branches for each Drupal version?

Currently I have 2 repositories: one for the client and another for the server.

Drupal.org uses just one repository for module, and branches for each module version (for example, 7.x-1.x for module in version 1.x for Drupal 7, 6.x-1.x for module in version 1.x for Drupal 6, 7.x-2.x for module in version 2 for Durpal 7, and so on).

Also, if your server and client share code you may use just one Durpal module with submodules, so all code is in one repository. Users will just enable client or server (and the module that holds the common code).

So, your actual setup is fine if client and server do not share any code or very little and you want to keep them as separate modules. Just add branches for each Drupal version (6.x, 7.x, 8.x). Or join them into one repository and split code into three modules: common, server and client.

You can check the 'Maintaining a drupal.org project with Git' page.