user-profile.tpl.php and render($user_profile) not working Pulling my hair out after googling all day to solve this.

I am using a corolla subtheme on drupal 7. I am trying to override the user account edit page in a template file.

For that I am using the default user-profile.tpl.php that comes with core's user module.

But without preprocessing the file won't be recognized by my theme. So I googled here and there and came up with the following:

function mytheme_theme(&$existing, $type, $theme, $path){

  $hooks = array();
    // Make user-profile.tpl.php available
    $hooks['user_profile_form'] = array (
       'render element' => 'form',
       'path' => drupal_get_path('theme','mytheme'),
       'template' => 'templates/user-profile',
       'preprocess functions' => array('mytheme_preprocess_user_profile_form'),
    );
  return $hooks;
}

function mytheme_preprocess_user_profile_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_profile_form', $form_state['build_info']['args']);
}

My php is at a level copy/paste + minor adjustments with a lot frustration.

This preprocessing makes my site read the user-profile.tpl.php, but I can't access the array $user_profile. Instead fields are in the array $form, which misses some fields I need, and all fields miss their default values which should come from the user whose account is shown.

This way I can't rebuild the default password-inputboxes and the 2 new password-inputboxes, and I need a lot of extra php to supply the values for all fields.

I am missing something here, but my knowledge won't go that far that I know what to change, and my google-fu is depleted. I think I need to change some things in the preprocessing-code, so that the array $user_profile is loaded and all the fields have the correct values allready.

How to accomplish this?

How can I make this to work?

In order to have the $user_profile renderable array available within your tpl, you can use the same logic used by Drupal user core module.

Build the content for a user object, loop through each field and assign it to the $user_profile variable.

In your case, it would something like this:

function mytheme_preprocess_user_profile_form(&$vars)
{
    // load user
    $account = user_load(arg(1));

    if (!$account) {
        // user not found
        return;
    }

    // retrieve all profile fields and attach to $account->content.
    user_build_content($account);

    // loop through each field attached to the user object
    $vars['user_profile'] = array();
    foreach (element_children($account->content) as $key) {
        // add it to the $user_profile variable, which will be available in tpl
        $vars['user_profile'][$key] = $account->content[$key];
    }

    $args = func_get_args();
    array_shift($args);
    $form_state['build_info']['args'] = $args;
    $vars['form'] = drupal_build_form('user_profile_form', $form_state['build_info']['args']);
}


Drupal + MongoDB + ApacheSolr I'm developing a website which uses MongoDB drupal module, I also need ApacheSolr as search engine, I googled about the Compatibility of ApacheSolr and MondoDB but found nothing.
Can I use Mongo as database and ApacheSolr as search engine (with search api) together?

Given that Search API/Search API Solr use Drupal core functions for retrieving entity data in order to be database agnostic, and the MongoDB module just adds another database backend for storing items like fields, there wouldn't be a conflict. As long as you stick with Drupal core functions in your custom integration, you should be fine.


Views, getting nodes type 1 which user have NO node of type 2 published that references the node type 1 I'm using drupal 7.20 with Views 3 module.

I've a content type "Homework" and a content type "Solution". The Solution content type has an entity reference field that references nodes of type "Homework".

Well, I'm trying to set up with Views a new Tab in the user profile menu: "Pending Homeworks" that lists all Homeworks that has no Solution referencing them and published by that user.

Best an example:

"Homework 1" <- "Solution (by user 1)"
             <- "Solution (by user 2)"
             <- "Solution (by user 3)"

"Homework 2" <- "Solution (by user 1)"
             <- "Solution (by user 3)"

"Homework 3" <- "Solution (by user 3)"

In this example, user 2 hasn't published yet his Solution for Homework 2 and Homework 3, so, the View I want, must output: Homework 2 and Homework 3.

Thanks in advance.

This has already been answered here.

A simple view will not do what you want.


How to add link module in Bootstrap Paragraphs? I experiment with the xeno_hero module and Bootstrap Paragraphs module in order to create a call to action block. I want to create an image background with a centered linked textfield.

I tried a lot of options. The option of a link is not given so I tried to add link (core module) to dependencies like this

dependencies:
  config:
    - field.field.paragraph.xeno_hero.xeno_background_image
    - field.field.paragraph.xeno_hero.xeno_content
    - field.field.paragraph.xeno_hero.xeno_invert
    - field.field.paragraph.xeno_hero.xeno_offset
    - field.field.paragraph.xeno_hero.xeno_overlay
    - field.field.paragraph.xeno_hero.xeno_parallax
    - paragraphs.paragraphs_type.xeno_hero
    module:
    - entity_reference_revisions
    - image
    - options
    - link

And copied the link.schema.yml file from core to custom module. So far no good.

How can I add a linked textfield?

If you add a Simple paragraph into the Content field, you can add whatever content you want in the wysiwyg without the need for a link field modification.

Here is of the hero the Bootstrap Paragraphs demo site.


Checking if user is logged into Drupal from another php application using Drupal services and REST I have an external php application that currently uses Drupal services to authenticate users.

It's working fine but users frequently enter incorrect credentials and Drupal's flood control eventually blocks the IP of my application. And therefore every user that attempts to login to my application.

The plan to get around this is to have users log directly into Drupal and redirect them to the app. And if they go straight to the app it checks to see if the user is logged in via services. If not logged in then direct them to Drupal's login page.

As far as I can tell I should be able to use /system/connect.json to get the current user, but I keep getting anonymous user and not the user currently logged into the browser.

When I retrieve the X-CSRF-Token using a REST console browser extension via /services/session/token I get the correct token for the currently logged in user .. But getting the token through the app using php_curl I get an new token with every request.

Is it possible for me to determine if a user is logged into Drupal in the current browser via services not knowing who they are? Or am I going about this the wrong way?

I would recommend using OAuth2.0, check out OAuth 2.0, assuming Drupal 8, otherwise there's the OAuth 1.0 for Drupal 7 (or if you're not using SSL with D8 for some reason).

This is the same tech that Facebook and Google use when you want to let people log into your site/app using their 3rd party credentials, so it should be robust enough if I understood what you were asking.


Undefined offset, CCK field I've been getting the following php notice:

Notice: Undefined offset: 9 in include() (line 89 of node--name.tpl.php).

Here's the code:

<?php
// loops through array to print out addendum pdf's.
for ($i = 0; $i < 10; $i++) {
  $variable2 = "../sites/default/files/" . $node->field_addendum['und'][$i]['filename'];
  $variable1 = $node->field_addendum['und'][$i]['filename'];
  if (isset($variable1)) {
    $result = $i + 1;
    echo "$result&nbsp&nbsp&nbsp";}
  else {}
}
?>

The field_addendum is a "file" field type from a custom content type. I understand why I'm getting the notice: if the node only has 3 addendums, once the loop gets to $node->field_addendum['und'][3]['filename'] and onwards, there is nothing in the array.

Is there a way to get the number of files without having to loop through the array first?

You can try to check if array element exist before assigment, and only if so, assign it, an this way avoid undefined offset:

  if (isset($node->field_addendum['und'][$i]['filename'])) {
     $variable1 = $node->field_addendum['und'][$i]['filename'];
    }


Services Views and combine different field values into one? I got a site with a profile2 type and a content type that uses the same field containting coordinates (field_coordinates).

I'm using Services Views to show these coordinates in JSON but this is where I ran into some problem. I want only one field set of these coordinates visible, but I have to chose the relationship of the field: either no releatinship shows the node coordinates, or the relationship with the profile shows the profiles coordinates.

There will never be two sets of coordinates per output node (in one case the are requested from the node, and the other case from the profile). The JSON output cant show two fields with the same label so I have to have two different names: one for profile coordinates and one for node coordinates.

The issue is that I want only one coordinate field, and therefore added a global text field, where I put both of the place holders from the other coordinates. But this global text field output wont show in my Services view. Why is that?

Try taking one field and hiding it with views then if the next field is empty pull that one in there?


How to rewrite this theme call to drupal_render I have this call to the theme function in my code :

print theme('image_style',
            array(
                'path' => $news_image['uri'],
                'style_name' => 'thumbnail',
                'alt' => $news_image['alt'],
                'title' => $news_image['title'],)
            );

However in the theme function documentation you can read :

  Avoid calling this function directly. It is preferable to replace
  direct calls to the theme() function with calls to drupal_render() by
  passing a render array with a #theme key to drupal_render(), which in
  turn calls theme().

So, how do I rewrite the above simple function using drupal_render ?

Something like this...

$build = array(
  '#theme' => 'image_style',
  '#path' => $news_image['uri'],
  '#style_name' => 'thumbnail',
  '#alt' => $news_image['alt'],
  '#title' => $news_image['title'],
);

$rendered = drupal_render($build);

Where every named variable you would normally pass to the theme() function as the second parameter becomes a #-prefixed key in the render array.


Not load JS formatter field used Views Infinite Scroll I had my module formatter field for Image Slide . After load scroll page that field not run slide , I Debug see not include js slide when load scrolled ! So how to include js or call js field formatter after load scrolled ?

add an ajax complete function to your js code.

Ex:

$( document ).ajaxComplete(function() {
    // Do stuff here when ajax loads.
});


Run drupal website over only HTTPS Possible Duplicate:
  How to simply make the whole site https

I have my drupal 6 website running on apache. I want this site to run only on HTTPS. What should be done for this. There are lot many solutions, which are getting me confused. Please help me on this.

You can try Secure Pages and Secure Pages Hijack Prevention modules.


How can i publish my content with Schedule I want to publish some content in a day, not all of unpublish content at once.

for example
I have 20 unpublish content and i want to publish 2 random content in a day at 13:00.

How can I resolve this?

If you aren't concerned with the "random content" portion of your question you could use the scheduler module to accomplish the task - https://drupal.org/project/scheduler which would allow you to set specific times during the day when you wanted content to be published.

If you do want it to be randomized though, you're going to need to use rules - https://drupal.org/project/rules and VBO - https://drupal.org/project/views_bulk_operations.

(I'm assuming Drupal 7)

Create a view.
Under Fields add a "Bulk Operations: Content" field. Set the number
of entities to your desired number (in this case 2.) Set it to
publish content, Enqueue the operation instead of executing it
directly.
Under Filter Criteria set it to  "Content: Published (No)."
Under Sort Criteria set it to "Global: Random (asc)"
Under Pager set to "Display a specified number of items" and choose
the number of desired items (in this case 2)
Save your view.
Now to go Rules configuration.
If you are only running cron once every 24 hours (at 13:00) you
could trigger this on cron run, otherwise you'll need to set up some
additional steps. Assuming the 24 hour cron, set your rule to
execute when "Cron maintenance tasks are performed".
Under actions click add action then select "Load a list of entity
objects from a VBO View." Select the view you just created from the
value dropdown. Click save.
Then under actions click add loop. Default variable name at the
 bottom should be "list_item." Click save.
Now click the add action button horizontal to the loop you just
 created. Select node publish content. For the "data selector" field
 use list_item from the loop above. Click save.
Run cron to test.

2 random pieces of content should publish.


How can I load comment IDs using the comment type? I know how to load comment ids for a particular node by following code

$entity_manager = \Drupal::entityTypeManager();
$cids = $entity_manager
    ->getStorage('comment')
    ->getQuery('AND')
    ->condition('entity_id', '25364')
    ->condition('entity_type', 'node')
    ->execute();

But I need one more condition to add on because this node might have multiple comment type linked. I know the machine name , but I don't know exactly what should be the first parameter to be passed in condition.

I itself got the answer i just guessed the name to be passed in condition.

$cids = $entity_manager
    ->getStorage('comment')
    ->getQuery('AND')
    ->condition('entity_id', '25364')
    ->condition('entity_type', 'node')
    ->condition('comment_type' 'post_trp_comments')
    ->execute();


How do I add default values to a database table using hook_install()? I am creating a custom module with its own schema of a few tables. These tables need to have some values pre-populated into them for the module to work (default locations, select options, etc).

What's the best practices way to insert default values into these tables during hook_install?

Since drupal_write_record is not available, I can use db_query, but I just want to make sure that I'm not breaking any cardinal rules by doing so.

The better way is to do it inside hook_enable(); at the time the hook is invoked, the module is already installed, and the schema of its database is available to Drupal, and to drupal_write_record(). As the hook is invoked all times a module is enabled, and not just when the module is installed, the hook implementation should check if it didn't added those database rows already (e.g., it should use a Drupal variable containing a boolean value).

As example of module that uses hook_enable() for a similar purpose, you can check forum_enable(), or php_enable() (which adds the "PHP code" input format).

function php_enable() {
  $format_exists = (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE name = :name', 0, 1, array(':name' => 'PHP code'))->fetchField();
  // Add a PHP code text format, if it does not exist. Do this only for the
  // first install (or if the format has been manually deleted) as there is no
  // reliable method to identify the format in an uninstall hook or in
  // subsequent clean installs.
  if (!$format_exists) {
    $php_format = array(
      'format' => 'php_code',
      'name' => 'PHP code',
      // 'Plain text' format is installed with a weight of 10 by default. Use a
      // higher weight here to ensure that this format will not be the default
      // format for anyone.
      'weight' => 11,
      'filters' => array(
        // Enable the PHP evaluator filter.
        'php_code' => array(
          'weight' => 0,
          'status' => 1,
        ),
      ),
    );
    $php_format = (object) $php_format;
    filter_format_save($php_format);

    drupal_set_message(t('A PHP code text format has been created.', array('@php-code' => url('admin/config/content/formats/' . $php_format->format))));
  }
}

As shown from those hook implementations, the code could necessarily need to be executed all times the hook is executed; it could also be the code needs to just executed once, as in the case the default values added to the database cannot be altered from the user, who doesn't have a user interface to alter/delete those values.


Seller and Buyers Own Comments (Commerce Communicae) I would like to have a way for my seller/author (author of node) and my buyer/user (not author of node) to communicate.

First, I have looked at the comments. If I allowed buyers to only start one comment and seller only able to reply to that buyer's one thread.. I envision buyer adding comment and seller only being able to reply to that comment. the seller would also see comments from other buyers; one thread per buyer so the conversations are grouped by buyer; for the seller to see. The buyer would see only their initial starting comment and any replies from the seller.

If used a view to contextually filter for same exact node and contextually filter for logged users authored nodes. basically showing the same node if logged user is seller. then I just use view mode to display the comments only. this results in the seller/author seeing entire comments.. in this case id only have to limit buyers/users to making one comment thread and the seller/author view would be 'finished'

How do I limit buyers/users from posting only one initial tread that buyer and seller reply back and forth. so from sellers view, they see buyers only once in comment list and the conversation there.

For the buyer I haven't been able to use view block to make correct relationships to get the buyers initial comment thread as well as the authors replies to it..

Should I use two views and better filters and relationships, (or
even 1 view?)
Should I make new content types or entities instead
of using comments? (id hope to leverage the comment form, and email
alerts and rest of comment stuff instead of making new framework
Should I consider other modules or organic groups? (again comments is
so close id hate to reinvent the wheel.
Should I consider livechat module and have it make a separate chat channel per item, per buyer/seller?

Edited
It seems to me that if I can keep user making only 1 comment, if I can target the start of the thread I can then say grab only the buyers comment starting tread.

Added
So tried entity construction kit and was further than comments is already from my goal. used entity reference field so in node edit you saw a message text field; didnt want that.

Also tried some modules for buyers to only start one comment thread. onecomment, one_comment_only... did not have what I was looking for.

Have you tried commerce_message? In Kickstart 2, we created an order commenting system, where buyers and sellers could leave messages for each other and the system could also leave notes about the history.


Add a CSS class to a certain text field for node display How can I add a CSS class to a certain text field?  I have a content type, "Board Member", displaying thusly, see my screen shot below if it comes through...  This is the node, not a view.  The text for "BIO" is typical paragraph style and size.  I want it slightly bigger.  The field in the content type is a "Long Text with summary".  The widget used is "Text Area with a summary".  I don't see any way to assign a unique CSS style to it in Drupal.  Investigating CSS here, Firebug only shows this:

Lorem.....

Why is it skipping showing that this field is the "bio".  The other lines of text above it "Name" and "Board Member Role" were presenting unique classes and thusly I was able to format with css class rules to make them green and large.

I don't want to depend on the user to type in text with WYSIWYG exactly the same style with each of the board members, although that can be done since I've enabled that for FULL and Filtered HTML for that field.  I just seems that I should be able to assign a CSS class to this field.  I'll be using this field for TEACHERS and STAFF later on as well.

Thanks for the help.

Dave N

Another option would be to use Display Suite if you didn't want to use hooks in template.php.

This would allow you to add the class directly from the content type edit page, this would probably be a little easier to manage if you started adding more classes to other fields.

After downloading Display Suite, you would need to enable: Display Suite, Display Suite UI, Display Suite Extras.
Then go to /admin/structure/ds/list/extras and check Enable Field Templates
Go to your content types manage display page and use the "Select A Layout" dropdown, this will enable display suite for that view mode under that content type.
Arrange your fields as needed and click the gear button to the right of the field and select Field Template: Expert
Check "Field Item" or any of the wrappers and add a class and an element and you're done.

It may seem like a lot to do to complete your specific task but it will make your life much easier in the long run.  I haven't built a single site without display suite since I discovered it.


Upgrading drush under Windows using self-update I installed Drush on a W/XP workstation using MSI and want to upgrade it.
I've tried using drush self-update but the suggestions it gives all seem to pertain more to Unix installations than Windows.
The best suggestion looks like drush dl /path/to/drush but I'm not 100% sure what the /path/to/drush would be on a W/XP system.

If you stick to using the Pear installation method for Drush then you can just update all Pear modules (or just Drush) at will. I don't even see the selfupdate command in Drush 6.2, but it just may be hidden now.


Problem trying to create a views with tabs. Link of tab doesn't point to the path I set I am trying to create a views with tabs:
so that a page that has several tabs, the View has a primary page that shows all Article nodes, a tab for all Event nodes, and a tab for Blog nodes.
Something should works like this:

"Content" button in menu links to /content,
"Articles" tab links to /content/articles,
"Blog" tab links to /content/blog,
"Event" tab links to /content/event.

However, with my work, this is what I got:

all the 3 tabs link to /content, instead of /content/articles, /content/blog, /content/event.

==========

Below is configuration of my view:

So basically, the tabs shows up, but the links of tabs are all pointed to /content, rather than their individual link.

What have I done wrong? Please advise. Thanks in advanced!

I've not had the pleasure of Views 3, but I think I can see what's wrong. I believe you want to have three displays:

Articles, which has a default menu tab (and you want Views to provide the parent menu item)
Blog, which has a menu tab (but not default)
Events, which has a menu tab (but not default)

(Currently the displays are set up as default tabs, which is why they point to the parent item - just like the path for the View tab on a node view doesn't point to node/x/view but points simply to node/x.)


Theming a node teaser to use its content types's custom tpl.php I have a page--contenttype.tpl.php in a custom theme that displays a node exactly how I want it to display on its own node page. How do I make it so that the teaser for the node of that type displays the same as it displays in full view?

I want to add this in either template.php, page.tpl.php or page--contenttype.tpl.php of my custom theme but cannot figure out the best way of doing it

You can add template files in your template.php & then add files for them. In your case write something like this in your template.php -

function THEME_preprocess_node(&$vars) { //Replace THEME with your theme name.
  if($vars['view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__teaser';
  }
}

After that, your TPL file for teaser would be in the format of node--[type]--teaser.tpl.php. Don't forget to clear your cache after you do this..


How can I debug a Views 2 block argument set via "Provide default argument" and "PHP Code"? I am using Views 2.16 on Drupal 6. I have the Content Profile module loaded and the profile has a nodereference field to another content type called Project. I would like to show a list of Projects in a block on the side when viewing the user page. I need to provide a default argument to a view since it is a block.

So the urls look like /user/admin, /user/joe who are related to content profile nodes 1867 and 1952 etc. I have the view showing correctly if I feed it a node id for a user profile as a hard coded value.

Now I want to do some stuff in the default argument code such as user_load(array('name' => arg(1)), content_profile_load($user->uid) and so on but it's not working.

What I have tried:
print_r, var_export('abc', true), dpm($user), watchdog('php-test', 'a string').

None of these methods gave me any debug output. How can I debug the argument code?

After more testing it appears that the watchdog function does work for debugging the embedded PHP code in the Argument Validator and Argument Default Value. I believe my validation was too strict previously and was preventing any output. For example embedding the line below in the "PHP validate code: " area gives all the argument components.

watchdog('block-args-php', var_export(arg(), TRUE));


Drupal registry table not populated with test class files I tried to write tests for custom modules and I found that registry database table is not populated with .test files and thus admin/config/development/testing displays only one SimpleTest test. I tried to rebuild registry with http://drupal.org/project/registry_rebuild but there is still no files. Is this a Drupal 7.19 bug?

Do you by any chance have the contrib 'simpletest' module installed? (as opposed to the core simpletest module that comes bundled with drupal 7)

I had the same problem you have.

What fixed it for me was uninstalling simpletest.
Than completely deleting the the contrib simpletest module.
Then reinstall simpletest (with the contrib module gone, this will install the core module)

And voila, my test classes started showing up in the registry and all is peachy :)


Best practice when testing module updates A problem I face on a regular basis is trying to test sites that have recently had a lot of module updates. My usual process is to take each module on a case by case basis and test site features related to that module.

For instance, if the wysiwyg module is updated, I'll find a node that implements it in a field and do exploratory testing. But the reality is that the issues can be more subtle - perhaps certain user roles have lost permissions, allowing them to embed media when they were previously restricted.

Sometimes there are so many factors to bear in mind it is impossible to test them all, and invariably the client, at UAT phase, discovers major issues that I may have been blind to for various reasons.

I would be interested to hear of any advice or approaches towards testing sites that have had comprehensive module updates - what can I do to ensure quality, and even, what kind of line should I take with our clients to prepare them for issues that do invariably arise?

A solution that I would very much like to test, but haven't so for, is combining a branching model like this one, not necessarily with git, with selenium automated testing. Every night, a tool like Jenkins pulls the development branch, runs drush make, drush site-install, and runs your selenium test suite.

I also remember reading an empirical study about finding bugs in software, that I unfortunately can not find a link to right now. The findings were, that no single way of finding bugs was "good enough", and that at least two separate models, such as "Test-driven", "User beta testing", "Code review", etc, were necessary to reach a high, +75%, level of found bugs, prior to release.


Using views_embed_view() in View I have created a View page, and added a "Global:PHP" field to embed a View block from another View using the following code:

<?php  print views_embed_view('VIEW_NAME','VIEW_BLOCK_NAME', $data->tid);?>

Now, it worked perfectly, but there's no detail or variables I can find in the print_r($data)/dsm($data) about this View block's content.

My purpose is that, if there's no result in view block, then I will hide a particular custom field. In short, "if views_embed_view() return empty then hide field A

Wondering how to go about it. Please advise. Thanks!

I would instead use views_get_view_result() if all you are concerned with is if there is a result.  More information on it can be found here.


Disable node summary page on /node path I want to disable the default front page, that is showing a list of nodes. I use another front page but it is still displayed at the url example.com/node. Either restricting access or redirecting to the front page would be fine.

My homepage is currently set to /home (which gets nicely rewritten to example.com/). Now I have already tried a few different things.

Under /admin/config/search/path, I have set an alias from node to home.
Unfortunately this just resulted in redirecting both example.com and example.com/node to example.com/home, showing the node list - not my front page.
I tried with an alias from node to <front> (I don't know if that is even valid there). This almost worked, /home and /node both redirect to example.com showing the right page. But now the node list is available at /<front> ...
I also tried with panels, creating a variant of node template. Returning a status code when the  path was equals node did not work, I guess because the page is only triggered on /node/, with a slash. It won't let me create a panel just for the node path as the path is already in use of course.
There doesn't seem to be any permission for setting access to this list.

So, how can I disable the page at example.com/node?
I guess my problem is I don't even know what kind of page this node list is. I have the feeling it's some unique page type, buried deep down in the core and can't be easily disabled.

If you're ok with writing a small custom module you could do it very easily using hook_menu_alter():

function MYMODULE_menu_alter(&$items) {
  $items['node']['access callback'] = FALSE;
}

The above will deny access to the page, if you want to remove it completely use this instead:

function MYMODULE_menu_alter(&$items) {
  unset($items['node']);
}

There's a discussion on the subject here with a few other ideas but I think this would be the simplest.


Getting Image URL in Views with field_views_field I have an content type called Image that has two fields:  Title and Image

I have a Views block created so that it displays the images I want based on my criteria.

What I need is to have the raw image URL available.

Example:

/sites/default/files/background1.jpg

I found this article Rendering Drupal 7 fields (the right way) and quite frankly, I am at a loss.

From the Drupal API:

field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL)

I know I have to code the views-view-fields--my_custom_view.tpl.php, but everything I do results in an error.

What needs to go in this file so that I can simply get the URL from the image that I am looking for?

Also  point in the right direction to a tutorial would be great.  Everything I have found assumes you are an expert in Drupal and at this point, everything feels circular.

I was able to do this strictly using Views by creating a relationship to the File Entity.

I have detailed this in another post which can be found here Getting the URL from an Image (or Any File).

This eliminates the need for a URL Formatter module and is D8 compatible out of the box.


Unable to override Superfish styles in Zen theme I am using a zen subtheme and a superfish menu. I am trying to override the background colours of the menu but am not having luck in IE8. I've tried clearing the cache but still no luck.

Do you have any idea why? Why isn't IE8 recognising the pages.css style sheet?

This style sheet is being picked up by IE8.

superfish/style/default.css

.sf-menu.sf-style-default li,
.sf-menu.sf-style-default.sf-navbar {
  background: red;
}

.sf-menu.sf-style-default li li {
  background: pink;
}

.sf-menu.sf-style-default li:hover,
.sf-menu.sf-style-default li.sfHover,
.sf-menu.sf-style-default a:focus,
.sf-menu.sf-style-default a:hover,
.sf-menu.sf-style-default a:active {
  background: green;
  outline: 0;
}

While this style sheet is being picked up by FireFox (this is what I want).

mytheme/css/pages.css

.sf-menu.sf-style-default li,
.sf-menu.sf-style-default.sf-navbar {
  background: orange;
}

.sf-menu.sf-style-default li li {
  background: yellow;
}

.sf-menu.sf-style-default li:hover,
.sf-menu.sf-style-default li.sfHover,
.sf-menu.sf-style-default a:focus,
.sf-menu.sf-style-default a:hover,
.sf-menu.sf-style-default a:active {
  background: grey;
  outline: 0;
}

It was just a matter of selection the Aggregate and compress CSS files option under Bandwidth optimization


Identifying Community Modules vs. Custom Modules Is there a list of Drupal Community modules that's easily query-able by the module's name/folder-name?

Context: I've inherited a web application built in Drupal.  This application has around 30 modules in

sites/all/modules

I'd like to identify which modules the previous team developed on their own vs. which modules the previous team downloaded from the community modules listing.

So, I'm looking for a list of community modules I could check the module identifier (as opposed it's free form name) against in an automated way.  This seems easier than manually search for 30 different modules.

Happy to hear other solutions for my problem.

I am unaware of any full list of modules that are on drupal.org for public consumption (there are a lot).  If I were you, I would do one of two approaches.

Based on https://stackoverflow.com/questions/6136022

cd sites/all/modules
for module in *; do
  echo -n $module
  echo -n ': '
  wget --spider --no-check-certificate -S "https://drupal.org/project/$module" 2>&1 | grep "HTTP/" | awk '{print $2}'
done

Lines that print out with a 200 exists; ones that don't should give a 404.

The other option is

cd sites/all/modules
for module in *; do
  grep 'project = ' $i/$i.info
done

Only modules on drupal.org will have a project line, which gets added by the packager script.

Also, if you visit the Available Updates page (admin/reports/updates) and check for updates, only public modules will be listed.


How to set default value for taxonomy autocomplete field? I am using Drupal 7. I have created a content type with autocomplete taxonomy field. I need to set default value programmatically.
I am using this code under hook_form_alter:

$form['field_school_locality_city_level'][LANGUAGE_NONE]['names']['#default_value'] = tid;

It's giving me just term id, but I need it in format Bhopal[tid:8193].

Load taxonomy term using term id then, generate data in your required format.

 // Term id.
 $tid = 8193;
 // Obtain the term.
 $term = taxonomy_term_load($tid);
 // Format data.
 $data = $term->name . '[tid:' . $tid .']';

$form['field_school_locality_city_level'][LANGUAGE_NONE]['names']['#default_value'] = $data;


Dificulties in modifying or duplicating a view I'm using drupal 8 (it seems to me exact version is 8.1.8) as CMS.
I created many views, and I would like to modify them o to duplicate those views.
But, mainly after I set a contextual filter, is not possible to modify the view.

And I 'm experiencing troubles too in duplicate a view and then modify the parameters.

Is there any know issue about those difficulties?

Instead of creating multiple views, have you considered using additional displays from the base view instead? That way they can share common configuration, but you can do things like apply a contextual filter to just certain displays.


How to Group the same content into one in View? I am using Date Module to display the view summary for a particular year and also count the contents are created in the same year.

I have created the several contents in the year of 2016 , it may contain more than 12 contents.

In each content, I have created the DATE field in the format of (Day / Month)

And, I have called all the contents in the block , while clicking the link content , the content detail should be displayed in the page.

Help me to sort out this issue

Look the Archive view /archive it will give you solution.


Remove "Language Undefined" from content with Multilingual module Using Multilingual - Internationalization module, now all my pages show:

  Language
  Undefined

At the bottem. How do I remove this text? I'm using the language switcher, and I have already disabled "Hide content translation links" in the module, but I guess that isn't it.

You can remove it from : admin - structure - content types - Article / Basic page "Manage Display" - set the language field from "visibe" to "hidden" - Save

Done!


Content exists in Drupal but unseen in PHPMYadmin? I have a content type which I enter data to by means of a csv file. Everything works fine as I have multiple content-types set up like this.

However, I'm trying to clean-up the database and remove data that is from 2012 and before.

Within Drupal at the /admin/content/filter url, I set the parameters for the content-type and such as:

node type is Print Data
and is created before 2013-01-01
and node status is published

(note, I just used the code indicator to set-off the options for this post)

Upon return, I have pages of content with each page showing 500+ results. I can delete them from within Drupal, but only at 500 at a time so I went to phpMyadmin but in there, I can only see/find data that is from 2013.

So where is Drupal storing all that other data if not in the database?

First of all allow me to say that you should not delete from db directly unless you are really aware of drupal's architecture and how the db tables are organized. (basically have in mind drupal store information for an entity in multiple tables not only one.)

Secondly have in mind in case you are looking through node table for a node created prior 2013-01-01 m the actual date is saved as unix timestamp (1357020000)

Thirdly allow me to recommend you VBO (View Bulk Operation) module for the exact scenario you are looking for , it will let you bulk delete, unpublish, publish (even has an API for custom bulk operations). I would create a simple view accesible for admins only, exposed filters for node creation date and some basic bulk operation. Please consider using this


Views Exposed TID Filter Hidden Behind Body Hello i have an exposed filter on my view allowing folks to seach by term. When folks start typing though only the first option on the list is shown and he rest is hid behind the body of my website.

You can view it here-
my exposed filter

Its the 2nd from the left in the red bar view up top.

Its driving me mad.

thanks

Looks like it is just a minor problem with the overflow property of the parent element. The following CSS rule (specific to your page) should fix it:

#preface-top.row,
#block-views--exp-latestnew-page_1.block {
  overflow: visible;
}


Help with $base URL path in settings.php Since I created my site (long time ago!) I have added content and changed many settings. My URL has always been www.domain.com/'drupalfolder'/(content)

I want to remove the drupal folder from the URL and just have my domain name (www.domain.com/content)

I have moved (manually) all the contents of the drupal folder on the 'public' folder but when I try and log in I get not found page or access denied.
I have tried to clear the caches before and after but still nothing. I had to change the main menu urls manually... I want all the URLs to change automatically!

Am I doing it properly? is there a process I can follow to save me time?

UPDATE: I do not have access to the .htaccess file as only my host has access to it ---- I am using cPanel

All URL will be changed automatically, if u have not provide static URL in it. For further checking what is causing the issue, check your apache log (if your server is Apache2)

cd /var/log/apache2
tail -100 error.log

See the latest error which is showing, or paste it here.


how to create a custom skin in jCarousel I want to create a custom skin in jCarousel. I have seen this website http://timonweb.com/how-create-custom-skin-jcarousel-drupal-7, but I don't want to create any new module. How to do it in a simple way? I had tried creating a new skin folder inside the skins directory of jCarousel module, but it didn't worked.

OK, after a moment of googling, I can say that apparently you cannot go without writing a tiny module, but even though I myself have been reluctant to write YABM (Yet Another... Module), it took me about 5 minutes.
Have a glimpse at this article, copy and paste the code, change the skin name occurrences and there you go - your skin recognized with clean hands. Thanks to http://timonweb.com.


node not listed under create content for panel page I'm following this book called drupal 6 panels cookbook. With panels installed, the example in the book says to go to the Panel UI of the new panel, click on the content tab> click gear icon > click add content

Then, a windows pops up and it has a couple of links on the left side that you can click. Listitems are Activity, cTools examples, menus...

What is supposed to be listed also is 'form' and 'node' but they're missing. At first I thought it was because maybe CCK wasn't enabled but everything that has to do with the CCK module is enabled.

Honestly don't know where to look.

Never really found a solution, just a workaround where I went with a view to display the content.


The item of an unregistered user's cart is shown a different unregistered user Using Drupal Commerce 2 in Drupal 8.8, if an unregistered user puts something in the cart (and doesn't check it out) another unregistered user sees these items in Cart block (provided by view (order)). They aren't shown to the users on the /cart page.

The reason for the behavior described above is that in Views I changed the advanced option context filter - order id - for "if there is no value for the context filter" from: "static" (the option after installation, which had the effect that no cart was shown at all) to "show all results" (with the effect described above).

I found this link https://www.drupal4u.org/howtos/how-hide-empty-shopping-cart-drupal-commerce saying the correct value would be "Current user's cart order ID", but this was not available. I'm not sure if this is a bug, if things changed for Commerce 2 or if I configured something wrong.


"cannot use a scalar value as an array" warning for adding #prefix and #suffix in template.php via hook-form-alter – Drupal 7 I have the following code in my Drupal’s template.php file. What it does is to embed every element of my site's contact form (created with the Webform module) in a li element (the form itself is already embedded in a ul element).

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &$field) {
      $field['#prefix'] = '<li>';
      $field['#suffix'] = '</li>';
    }
  }

This works, but I get 'Warning: Cannot use a scalar value as an array in MYTHEME_form_alter()' when accessing a page that contains such a form. The warning shows twice, once for each of the two lines where I add the prefix and suffix, respectively.

I have searched far and wide, but I do not know what to do. To the best of my knowledge, this is how Drupal wants me to handle this. And like I said, it does work, but it would be nice to get rid of the warnings and do everything 100 % correct.

(I'm using Drupal 7 and PHP 5.6.24.)

Does anybody know a better / the correct way to do this? Thank you.

Warning: Cannot use a scalar value as an array in MYTHEME_form_alter()

It is a common PHP error which means you are treating a scalar value (eg: int, string) as an array.

You can fix it by checking if it is an array before using it.

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &$field) {
      if (is_array($field)) {
        $field['#prefix'] = '
';
        $field['#suffix'] = '
';
      }
    }
  }

As mentioned by @Clive

Since you are adding #prefix and #suffix, you are obviously trying to change for the render element. So it would be better to limit the change occurred on render element only.

element_children is the API provided by Drupal for that purpose.

function MYTHEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($element_children($form['submitted']) as $key) {
      $field = &$form['submitted'][$key];
      $field['#prefix'] = '
';
      $field['#suffix'] = '
';
    }
  }


How do I render an entity view mode like 'teaser' in a twig template? I have an entity reference field in one content referencing an other content.

What I'm trying to achieve is to display that reference in a teaser format programmatically.

I was hoping that I could do something like this :

{{ node.field_entity_ref.view('teaser') }}

But that doesn't work. Do I need to declare a preprocess anyway ? If so what's the best practice ?

The best practice would be to configure the reference field in UI as teaser and use it in the node template:

{{ content.field_entity_ref }}

If this is not an option for your case, you would probably need some code in preprocess.

But much easier is to use the module Twig Tweak, which can render nodes without preprocess:

{{ drupal_entity('node', node.field_entity_ref.0.target_id, 'teaser') }}


user login by php code i have an app that sends username and password to a php script. This script checks that a user exists on Drupal 8 with username and password entered but does not log the user. I need the user to log in. Can someone help me? thanks
Follows script code
use Drupal\user\UserAuthInterface;
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
// Boot Drupal.
$autoloader = require __DIR__ . '/autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod', FALSE);
$kernel->boot();
// Recupero Nome utente e password
$nome_ut = $_POST['nome'];
$pass_ut = $_POST['pwd'];
// effettuo il controllo
$user_auth = \Drupal::service('user.auth');
$user_storage = \Drupal::entityTypeManager()->getStorage('user');

$accounts = $user_storage->loadByProperties(['name' => $nome_ut, 'status' => 1]);
$account = reset($accounts);

if ($account) {
    if ($user_auth->authenticate($nome_ut, $pass_ut))
       {
    // The credentials are correct.
       $id = $user_auth->authenticate($nome_ut, $pass_ut);
       print ("Accesso riuscito!");
           // Force session start if we don't already have a session.
               $session = \Drupal::service('session');
               if (!$session->isStarted()) {
               $session->migrate();
           }
           if (\Drupal::currentUser()->isAuthenticated()) {
               // This user is logged in.
               print ("Utente Loggato");
           } else {
               // This user is not logged in.
               print ("Utente non Loggato");
           }

       }
}

Could you use a rest endpoint? Because this is already handled by drupal core. See for example this or this
Otherwise I think you're just missing user_login_finalize after your check if the user is logged in.
user_login_finalize($user);
//Eventually redirect the user somewhere
$user_destination = \Drupal::destination()->get();
$response = new RedirectResponse($user_destination);
$response->send();


How to really remove the node title of an embedded node? I want to have easily reusable pieces of content inside my nodes. I did something with Node Embed and Exclude Node Title.

But then I found out that Exclude Node Title is really dirty and simply makes the string itself empty, but there's still HTML, so I have

, which sucks for design (can be hacked around with CSS) but even more for SEO: I don't want my piece of reusable content to be indexed in Google, I don't want Google to start thinking I'm playing them by having an empty .

Is there a good fix for this? Or maybe there's a better way to do this, e.g. by embedding blocks inside the content?

node_embed uses node_view() and drupal_render() to display a node.

With the default node.tpl.php, the title is always displayed unless the node is rendered as a "page". The "page" variable is determined in an obscure way in template_preprocess_node(), and is typically false with embedded nodes. So the title will be rendered.

  <?php print render($title_prefix); ?>
  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>

I see two ways to prevent this:

A custom node template for the view mode that is used by node_embed, in your theme.
Use a display suite layout for the given view mode. With display suite, the usual node template is ignored, and the title is just one among other visual elements to be positioned in the display. I prefer this solution, because I like display suite :)

node_embed ships with a dedicated view mode 'node_embed', which is used by default for embedded nodes. So this is the one you need to configure or target with a template.

BTW, at the time of this writing, the module page of Node embed says it is no longer supported. There is another module, Entity embed, which seems not to have this problem.


Replacing core forum pages with views throws a warning I set up views for forum/% paths to replace the core forum pages, and it works fine except I get this error:

Notice: Trying to get property of non-object in forum_menu_local_tasks_alter()
(line 169 of opt/jenkins/blahblah/modules/forum/forum.module).

Line 169 is the last line in this code block:

/**
 * Implements hook_menu_local_tasks_alter().
 */
function forum_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  global $user;

  // Add action link to 'node/add/forum' on 'forum' sub-pages.
  if ($root_path == 'forum' || $root_path == 'forum/%') {
    $tid = (isset($router_item['page_arguments'][0]) ? $router_item['page_arguments'][0]->tid : 0);

This is failing because $router_item['page_arguments'][0] is defined but it's a string, not an object.

So what are my options here?

I don't want to hack the forum module to change that line
I don't want to change the path of my views to something besides forum/%
So I think I need to figure out how to unset $router_item['page_arguments'][0] so that that conditional will short circuit? Or is there another way?

I ended up just using a different URL and fixing links to point to that one. Not a real fix to my problem, but whatever.


Default logo according to theme setting I'm creating the theme with two styles, dark and light. User can choose which style he wants in theme settings. My default theme logo is in the root of the theme.

Now I want to change default logo according to choosen style, so if the user choose dark style and doesn't set logo image, default logo is logo.png form theme root, but if user choose light style and doesn't set logo image, default logo is logo_light.png from theme root.

How can I override default logo according to result from theme_get_setting?

I think you can by adding algorythm like this:

  <a href="<? print $front_page; ?>"><img src="<? if (theme_get_setting(theme)=="dark") print $logo; else print $logo_light; ?> border="0" alt="<? print $site_name; ?>">


How to programmatically enable/disable Quantity text widget on cart/checkout page? There are the following things which I've investigated so far:

Version of Commerce Cart: 7.x-1.9
Shopping cart form is controlled by commerce_cart_form view.
Checkout page is controlled by commerce_cart_summary view.
Quantity widget can be enabled or disabled in Manage display for Product display content type. But there are no any rule actions controlling display Quantity widget.

So the question is, how do I (programmatically) enable or disable text Quantity widget on checkout page (e.g. for certain conditions/product types)? So people can edit the Quantity for only certain product types.

There is Commerce Rules Extra module, but it doesn't provide much functionality, but I've already posted feature request for that.

It seems the Quantity widget is a matter of configuring the views.

If you'll edit one of the commerce views e.g. commerce_cart_form or commerce_cart_summary, Quantity can be found in the field list.

By default Commerce Cart module has Quantity set to text field (File: commerce_cart.views_default.inc), so to change the widget from text field to numeric and vice versa you need to edit your view and replace the Quantity field with other one.

There are two fields available for these views:

Commerce Line Item: Quantity

The quantity of the line item.

Machine name: quantity

Handler: views_handler_field_numeric
Commerce Line Item: Quantity text field

Adds a text field to edit the line item quantity in the View.)

Machine name: edit_quantity

Handler: commerce_line_item_handler_field_edit_quantity

If you need to switch between numeric and text widget on certain conditions, you'll have to alter the view by using hook_views_pre_view() and change the handler on the fly.

Here is a simple example:

/**
 * Implements hook_views_pre_view().
 */
function MODULENAME_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form':
    case 'commerce_cart_summary':
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // 'quantity' for numeric, 'edit_quantity' for text field
      break;
  }
}

Other method is to create TPL view template file i.e. views-view-field--commerce-cart-summary--default--quantity.tpl.php and change the widget from there. Check 'Theme:Information' in view edit page for more info.

Here is example for restricting Quantity field based on the product type:

You need at least one TPL file created in your template directory (sites/all/themes/foo)

for cart page:

views-view-field--commerce-cart-form--default--quantity.tpl.php
for summary page:

views-view-field--commerce-cart-summary--default--quantity.tpl.php

with the following PHP code:

print foo_quantity_available_for_row($row) ? $output : 1; // Hardcoded '1'.

Note: If Quantity is numeric, it'll always display 1, so extend it based on your needs.
And the following two functions:

/**
 * Implements hook_views_pre_view().
 */
function foo_views_pre_view(&$view) {
  switch ($view->name) {
    case 'commerce_cart_form': // On cart page
    // case 'commerce_cart_summary': // On summary page
      $view->display['default']->handler->options['fields']['quantity']['field'] = 'edit_quantity'; // Enforce Quantity field from numeric to text field for further changes.
      // $view->display['default']->handler->options['fields']['text_quantity'] = $view->display['default']->handler->options['fields']['quantity']; // Create clone.
      break;
  }
}

/**
 * Restrict edit of Quantity field based on the product type.
 *
 * Callback from views-view-field--commerce-cart-summary--default--quantity.tpl.php.
 *
 */
function foo_quantity_available_for_row($row) {
  ($line_item = $row->commerce_line_item_field_data_commerce_line_items_line_item_) &&
    ($line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item)) &&
      ($product = $line_item_wrapper->commerce_product->value());

  if ($product) {
    switch ($product->type) {
      case 'product_type_1':
      case 'product_type_2':
        return TRUE; // Allow users to edit Quantity field.
        break;
    }
  }
  return FALSE; // Disallow users to edit Quantity field.
}

It could not work in all cases, so modify based on your needs.

Other method, as suggested by MarcElbichon would be to use hook_form_alter:

<?php
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if (strpos($form_id, 'views_form_commerce_cart_form_') === 0 ) {
        $form["edit_quantity"][0]["#attributes"]["readonly"] = "readonly";
        $form["edit_quantity"][0]["#attributes"]["disabled"] = TRUE;
    }
}
?>


Drupal 7 views admin redirecting to json returned after changing jquery version I have installed the seven theme on the admin side and blocks theme on the user side...
after getting alot of errors from multiple files adding jquery library, i have removed the extra files and upgraded the jquery in the misc directory to 1.9 with migration plugin.

the main problem was that wysiwyg and hierarchical select didnt work on the front end,
so after removing the extra jquery libraries it is working now.

the problem after all that is that now when i try to edit a View, each time i edit something in the view and click on save, it redirects me to the json returned from server instead of just closing the dialog and showing the View edit panel.

In short the problem is that the ajax doesn't work.

So What Should I Do??

You can't just upgrade the jQuery in the misc directory. You will get many many problems.

If you want to update jQuery because a specific plugin you want to use requires it, I would recommend the jQuery multi module.

However if you want your whole site to use a newer version, use the jQuery update module.
Currently though, the jQuery update module only supports up to jQuery 1.8.2.

In my experience using jquery update with versions above 1.5 was still too buggy, however those issues are claimed to have been fixed recently, so if you use the latest dev version it will apparently work.

However, you need 1.9 so jquery update isn't an option yet.

If you need 1.9 for a library (I assume that is probably the case), I would say use jQuery multi (I have successfully used it to run a bunch of things off on top of backbone.js and it has been working without issue for a long time now).


Create a view of the 'Recent Log Messages' I would like to give an admin user (not User 1) permission to see the Recent Log Messages (/admin/reports/dblog), but I only want him to see 'User' logs. As it is a subscription website he could see who has been signing up and cancelling their accounts. But if I was to give them this permission, they will also be able to see all the other log messages, which I do not want them to see.

I have searched for a module that allows permissions by Log Type (access denied/cron/page not found/etc.) , but with no luck. My best idea is if there was a way to create a View of the recent log messages, I could then create a filter to only show User messages.

Is there a module or some hook where I can limit a users access to 'Recent log messages' by 'Type'?

In Drupal 8, you can simply create a view of "Log entries". Just make sure you add a "Type" filter and select "user" as the type.

Then under "Page settings", change the "Access: Permission" to "Role > Administrator". However, if you don't want this user to view other log messages, perhaps that user shouldn't be an administrator? I recommend creating a new role for that type of user.

In Drupal 7, the Views module doesn't allow you to make a view of log entries out-of-the-box, however if you install the Views Watchdog module, you can do it just like the Drupal 8 method described above.


Using short URLs with AddThis I am using the AddThis module on my site.  Can this be configured to use short URLs instead of the native ones?

If you're not wedded to AddThis then the Service Links module integrates with the Shorten URLs module to provide this feature. It has the advantage of not being coupled with/crippled by the AddThis service.


CKeditor to search images on PC instead of server I have added the CK editor WYSIWYG to my website.

However I want user to browse their own local PC directory when uploading images and not the server. The default Image module from drupal core does this fine how can I do this with CKeditor?

This is one way to do this:

Install IMCE
Go to Configuration > Content authoring > CKEditor. Click edit for the Full profile
Expand the File browser fieldset. Select IMCE in the dropdown menu under File browser type. Save.

Then, when you click the Browser Server button, you will see the following window. Notice the Upload button. Clicking it will allow the user to select a file from their computer.


attach file to a node by code I wanted to associate a file to a node. so far so good. create a cck type file, and the problem was solved. but I can not do this, I do not want the user to choose the file. the file in question is already in the system.
I have tried to place the file as # default_value field and hide it with the hook_form_FORM_ID_alter, but failed.

function my_module_form_node_form_alter(&$form, $form_state, $form_id) {
    if(isset($form['type']) && isset($form['#node'])) {
        $type = $form['#node']->type;

        if(stripos($type, 'node-type') === FALSE)
            return;

        switch($type) :
            case 'node-type_xyz':
                $fid = arg(3);
                $file = file_load($fid);

                // make a cck field_invoice a hidden field
                $form['field_invoice']['#prefix'] = '
';
                $form['field_invoice']['#suffix'] = '
';

                $form['field_company']['und'][0]['value']['#default_value'] = 'ABC';
                $form['field_account_number']['und'][0]['value']['#default_value'] = '09879';
                break;
        endswitch;
    }
}

anyone have any suggestions?

This can be a bit tricky, there are a few steps to get right. First create and save the node, then add the file to the node as a second pass. Here's an example implementation.

/**
 * Add a file to a field on a node
 * @param int $nid  node ID to add the content to
 * @param string $field_name the machine name of the field to add to
 * @param string $filedata the raw binary data as a string
 * @param optional boolean is the attachment an image (should image validation
 *        be performed)
 */
function mymodule_addfile($nid, $field_name, $filedata, $is_image = FALSE) {
  $node = node_load($nid);

  $field = content_fields($field_name, $node->type);

  // Load up the appropriate validators
  $validators =
  filefield_widget_upload_validators($field),
  if ($is_image) {
    $validators = array_merge(
      $validators,
      imagefield_widget_upload_validators($field)
    );
  }

  // Where do we store the files?
  $tmp_files_path = file_directory_temp()."/$file_name";
  $files_path     = filefield_widget_file_path($field);

  // Put the file in the temp folder
  $ret = file_put_contents($tmp_files_path,$filedata);
  unset($filedata);
  if ($ret === FALSE) {
    watchdog('mymod_error',"Could not write $nid ($file_name) to temp: $tmp_files_path");
    drupal_set_message("Could not write $nid ($file_name) to temp: $tmp_files_path", 'error');
    return FALSE;
  }

  $path = $files_path.'/'.$file_name;

  // Create the file object
  $file = field_file_save_file($tmp_files_path, $validators, $path);

  if ($file == 0) {
    watchdog('mymod_error',"Failed to save file $file_name");
    drupal_set_message("Failed to save file $file_name",'error');
    return FALSE;
  }

  // Apply the file to the field
  $node->{$field_name}[0] = $file;

  node_save($node);
  return TRUE;
}

A variation on the bottom works too, just assign the result to the file field.

function _fhi_add_existing_file($file_drupal_path, $uid=1, $status=FILE_STATUS_PERMANENT) {
  $fs       = filesize($file_drupal_path);

  $res = db_query("SELECT fid FROM files WHERE filepath = '%s' AND filesize = '%s'", $filepath, $fs);

  $fid = db_fetch_array($res);

  if ($fid) {
    //drupal_set_message("$filepath already found. fid: $fid");
    $fid = $fid['fid'];
    return field_file_load($fid);
  } else {
    $file=(object)array(
      'filename'  => basename($file_drupal_path),
      'filepath'  => $filepath,
      'filemime'  => file_get_mimetype($file_drupal_path),
      'filesize'  => $fs,
      'uid'       => $uid,
      'status'    => $status,
      'timestamp' => time()
    );

    drupal_write_record('files',$file);
    return field_file_load($file_drupal_path);
  }

}

This code drawn from memory and without interpreter (I've got too much time on my hands this morning) so be wary of typos I may have introduced. As with anything, not responsible for death of poodles as a result of the use of this code.


Different content in same blocks through different contexts This is probably simple and has likely has already been asked but I can't find it anywhere else on here.

I currently have context, delta, and omega installed.  I'm currently using the content block to hold my slider on the home page but it keeps on showing up everywhere throughout the site.

Same for the postscript first and second blocks.  I have two different views in there and they keep showing up throughout the site, everywhere those blocks exist.

My question is, is it possible for me to fill those blocks with different content, or should I create my own blocks for the home page instead?

Also, is there a good video tutorial somewhere on using delta and context or just basic page ordering in drupal?

Thanks,

Solved this through using delta.  What's not mentioned above is that I was using Omega 3 when I had this problem.  I've not used it yet, but I believe Omega 4 handles this differently.


db_insert in Drupal 7 without field names I have the following INSERT in a db_query, but feel like I should convert it to a db_insert, but can't figure out the syntax:

INSERT INTO {mytable} VALUES (23, 'foo', 'bar', 42)

This example is fairly short, but I do work with some legacy tables that have MANY fields.

$insert = db_insert('variables')->values(array(23, 'foo', 'bar', 42));
$insert->execute();

The above gives me "NoFieldsException: There are no fields available to insert with. in InsertQuery->preExecute()".

How can you perform an insert with db_insert without needing to specify each field name?
I can make it work in D7 with db_query([INSERT...]); but drupal_write_record does not work.

You can not do this with db_insert().  You could probably dig into the InsertQuery class and get it done, but that's no different than what you're already doing IMO.

I have never seen INSERT without specifying column names, for good reason, although apparently you can (mysql api).  If you do this, it makes it more difficult for someone else to understand what you've done, and impossible to alter the table structure without causing headaches.

You can look at the waydrupal_write_record() uses drupal_get_schema() to create the fields if you'd like to automate the process (although it would probably take just as long to write the $fields array one time).


Problem with LDAP mapping I've successfully used the LDAP Integration module to use LDAP authentication with Drupal. Now I'm trying to create an address book with information from LDAP.

I've tried the following solution:

Changed the ldapdata.module, the part that states which fields can be mapped between LDAP and Drupal (e.g. mail => mail). This fails when I try to add more mappings. I believe this maps to the users table in Drupal, but when I try to add a field to that table and map a LDAP attribute to it, nothing goes into the database. My plan was to then use Table Wizard with Views to create the address book. Using Table Wizard and Views I was able to extract everything I wanted from the users table, but the problem of entering data into the table is still not solved.

If you have any ideas, any at all, I'd really appreciate it.

Enable the LDAP Query module and run your own query like below.

//Lets say you have the user details loaded here
global $user;

$ldap_query = new LdapQuery('ldap_user_query');
$ldap_query->baseDn=array('DC=CORP,DC=AD,DC=YOURCOMPANY,DC=com');
$ldap_query->sid='corp.ad.yourcompany.com';
$ldap_query->qid='ldap_user_query';
$ldap_query->name='ldap_user_query';

//Enable the Query.
$ldap_query->status=1;

$ldap_query->filter='(&(objectClass=user)(name=' . $user->field_full_name[LANGUAGE_NONE][0]['value'] . '))';
$user_data = $ldap_query->query();

//use the user data to update other fields.
dsm($user_data);


How to delete nodes without taking a lot of time? My site has about 200 000 nodes. When I want to delete let say 200 nodes it takes about 2hr. I have also installed commerce module, views and a lot of the usual modules. What can I do to speed things up?

Usually I use 2 approach from the command line. If you call a page from the browser to accomplish the task this will use more time and resources.

1. You can create your own module named drush_delete

Inside the drush_delete.drush.inc file put this code:

<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

Install the module, run drush cc drush to clear the drush cache and use the command like this:

To delete a node use:

drush node-delete 1
drush nd 1

To delete multiple nodes use:

drush node-delete 1 2 3
drush nd 1 2 3

EDIT: I just remeber that I have a collection of drush commands in github at https://github.com/adrian-cid/drush_commands.

2. You can use the Drush Entity module

Deleting node with nid 1 and 2

drush entity-delete node 1 2

Deleting all the nodes:

drush entity-delete node

Deleting all the articles nodes:

drush entity-delete node --bundles=article


View commerce product image and price fields In Drupal 7 commerce I ran into a problem.
I want to display the latest 3 items placed in the show_product content type, with attributes from the store. There are several entities in the store, displayed in the same node with the product reference field, all with different attributes and images.
Imagine every online clothing shop will face the same problem regarding sizes and colors.
So, in Views I need a relation on "Content: field_prodref - product_id" to show the attributes from the entities.
The view shows all the products from the store. Is there a way to bypass this so the view shows only the show_product display node with price field and image?

I'm pretty sure you'd have worked out the *the latest 3 items placed in the show_product content type* part already:

Add filters, Node: Type, Node type: show_product
Add sort criteria, Node: Post date, Sort order: Descending
Items to display: 3

For the attributes part, the tricky one, instead of defining a relationship in the existing view, you'd be better off creating a whole new view, which would list the attributes of product passed in as argument.

To make it all work together, you'll attach the latter view to the former one using one of  Viewfield (7.x-dev), Views Field View (7.x-dev) and View reference modules.

An example, using Viewfield. To the show_product node type add a hidden View field called Attrview. Set it to "Always use default value". Set the default value to the attribute listing view. The argument is "%nid". Exclude its display from node teaser, full view etc.

In the first view, then, along with Price and Image, also add Attrview as a field. Done!


How to add more information about authors with the Bibliography module? We are setting up a bibliography for old and very rare resources with Drupal 7 and the Bibliography module. We need to have more information about authors (picture, biography, nationality). We have seen that we could link authors to users but in our case authors don't require to have a real user account (because most of the time authors are dead).

My questions:

How can we add more information to authors?
Is it possible to create some kind of user account without login, password and e-mail ?
Would it be possible to create a specific content type for authors (with fields for picture, biography and nationality) and link it to the biblio author, and in that case how could we do this?

Create another content type like "BookAuthor" with 1 node for each such Author. Then add fields to this content type for attributes such as picture, biography and nationality.

Assume you have a content type like "Ressources" (or just create one). Add a field in that content type using the Entity reference module for it (probably with multiple values allowed). That way you can add one or more "links" in each Ressources-node to relevant nodes of type BookAuthor.

PS: just to avoid possible surprises, I would not call the content type "Author" (which has a special meaning in Drupal, so better to not confuse Drupal with the same name for your extra content type).


Importing 'body' into 'paragraphs' I need to migrate an ordinary D7 multi-value long text field 'body' into D8 paragraphs . As paragraphs seem to be a reference, the migration will probably be more complex than just direct field mapping. Moreover, my target paragraphs include multiple fields, not only the text body but a title as well.
Any idea or link how to accomplish this task?

Paragraphs are entities in and of themselves - it's most straightforward to migrate the paragraphs separately, then populate the reference to the migrated paragraphs within the "parent" node migration.


How do I Group Repeatable Fields Programatically? I'm in the middle of coding a custom entity in Drupal 8. Currently, I'm defining fields using the baseFieldDefinitions method. I've run into a small problem now where I have a subset of fields that need to be grouped together and repeatable. For example, I have a checkbox, a text box, and a select box that all need to be associated while allowing someone to click an "Add" button to produce another set of those three fields.

It seems that if I was using the UI to create a custom content type, then I could use Paragraphs to handle this, but I wasn't able to figure out how to do that in code, and all the modules that are used in Drupal 7 as example of how to do this either don't exist in D8, or point to using Paragraphs instead.

Some ideas that I had:

Create all three as repeatable fields in baseFieldDefinitions and override the form to present them as a unit and write some ajax to make it work the way I want. I don't think this is ideal because it seems like I'm fighting the framework.
Make this group of fields into their own entity and try to figure out how to add an entity creation form inside my parent entity creation form. I'm not sure if this is possible, but it seems like it should be.
Use hook_schema to create a database table with the three fields that I need and an additional column to tie that record to my custom entity. This is the way I would have done it in Drupal 7, but I'm worried about the long term of running reports in Views using the data that isn't in the Entity itself. This seems like the quick and dirty way to do it but I don't want a Views headache later.
Figure out how to do this in Paragraphs.

Hopefully, someone with a little more experience than I have in D8 can point me to the most preferable way to handle this. Any help would be greatly appreciated.

I would pick option 3: Create a custom field type that holds all 3 values in one table. This works fine with views. This can be done with Drupal console to simplify the process, see generate:plugin:field. I would also create a separate module for the the plugin with the custom field type so you can test enabling and disabling you main module without running into dependency issues. The advantage of this method over all others is all the data is held in one DB table which keeps things simple and is more efficient.

To briefly touch on your other options, 1 seems dirty and prone to problems. 2 is not bad and does give you more flexibility but means more code and more database tables. If you don't need the added flexibility then there is no need. Paragraphs, Option 4 will create as many DB tables as a custom entity but with less flexibility (you can't add methods to the ContentEntityBase) and more reliance on contrib modules. This is only a good option if your a site builder and don't want to worry about coding.


Drupal 7 appending class in uc attribute option radio button I have this code inside mymodule_form_alter:

     foreach ($form['attributes'] as $att) {
        foreach ($att['#options'] as $option => $value) {
  // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $att['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $att['#options'][$option]['#attributes'][] = array('class' => array('my_class'));
            }
        }
    }

Unfortunately

  $att['#options'][$option]['#attributes'][] = array('class' =>
  array('my_class'));

Displays unexpected error, I tried different syntax but no success. Any help much appreciated

  Update 27/09/2017

I tried to do this by using after_build I get no errors but it isn't working

// Inside hook_form_alter
 $form['attributes']['#after_build'][] = 'addToCartFormEditQuantity_after_build';

 function addToCartFormEditQuantity_after_build(&$element, &$form_state)
{
    // Each renderable radio element.
    foreach ($element as $attribute) {
        foreach (element_children($attribute) as $option) {
            var_dump($attribute[$option]);
      // Get the name of the option without the price or price adjustment -> string before coma
            $optionName = explode(",", $attribute['#options'][$option], 2)[0];
            if (strpos($optionName, '+') !== false) {
                $attribute[$option]['#atrributes']['class'] .= 'single-double';
            }
        }
    }

    return $element;
}

I managed to get what I wanted  inside theme_uc_attribute_add_to_cart by using:

foreach (element_children($form) as $aid) {
     foreach (element_children($form[$aid]) as $option) {

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

      }
    }

But I really don't want to mess with uc_attribute.theme.inc is there any other way?


import csv to build several nodes all at once I'm new to Drupal. What's the easiest way to create multiple nodes on Drupal 7 all at once? I built a special content type and have the fields data in a CSV file.
Thank you

Yes there is, you can using:
Feeds

Import or aggregate data as nodes, users, taxonomy terms or simple
database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files

Video Tutorial


How to create dependent fields in Entity:baseFieldDefinition? I have created a select list of content types in baseFieldDefinition

$fields['ctype'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Content Type'))
      ->setDescription(t('Choose content type '))
      ->setRequired(TRUE)
      ->setSettings(array(
        'allowed_values' => $ctypes,
      ))
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'string',
        'weight' => -5,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => -5,
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

Does Drupal provides ajax feature to use in baseFieldDefinition ?

Basically I want to generate field list of selected content type using entity.

Does Drupal provides ajax feature to use in baseFieldDefinition ?

Short answer: no

Long answer:

The base field definition method is used to define the entity structure and the database structure.

If you are trying to display different form items when the toe changes then you should do that on the form object level. By adding a #ajax attribute to the type field.


How to add comment form to drupal pages not having node and content type? mymodule.module

function mymodule_theme() {
return array(
    'mymodule_results' => array(
        'variables' => array('var1' => null, 'continent' => null, 'country' => null, 'location' => null, 'query' => null, 'total' => null,'comments'=>null),
        'template' => 'templates/mymodule_results'
    ),
    }

mymodule.pages.inc

function mymodule_details($beaches = null) {
 drupal_set_title('Beaches Details');
 if (!isset($beaches->comment_count))
    $beaches->comment_count = 0;
return array(
    '#theme' => 'mymodule_results',
    '#beaches' => $beaches,
    '#attached' => array(
        'library' => array(
            array('iks_libraries', 'jquery.tinycarousel'),
        ),
    ),
);
}

mymodule_results.tpl.php

<?php if ($comments): ?>
<?= render($comments) ?>

I need to include the comment form in the template page, But i have not created a content/node type for this. I'm displaying the results in the template page.

Comments needs to be attached to a content. If you want to use built-in comments module, you need to:

Use "simple page" content type to create dummy nodes, or create similar one

it might be wise to strip your dummy content type from everything except title and comments
revoke edit and delete rights, no one should be able to do it

In your module's install file, make sure this content type is enabled and create a dummy node for each of pages you need comments on
Set node's paths to match paths of the pages, so people cannot access them directly
Setup Global Redirect or similar to always redirect from /node/$nid to path
In your module load node and pass it to theme so you could render comments in tpl.php file

That would be about it, if you need more details on any of these points, I guess it'll be worth a separate question.


How do I get comments to be indexed? I'm not sure if it's actually doing this; I can't see any options for comment fields in the configuration. How can I check? Does it say explicitly somewhere?

Apachesolr Comments

  By default the apachesolr module index comments attached to the node.
  So you can not search comments directly. This module separates
  comments from the nodes and allows you to search them directly.

UPDATE:

For search api apply this patch

diff --git a/modules/callbacks.inc b/modules/callbacks.inc
index dca9e1d..e12be6a 100644
--- a/modules/callbacks.inc
+++ b/modules/callbacks.inc
@@ -80,6 +80,12 @@ function entity_metadata_comment_get_node_properties($node, array $options, $nam

     case 'comment_count_new':
       return comment_num_new($node->nid);
+
+    case 'comments':
+      $select = db_select('comment', 'c')
+        ->fields('c', array('cid'))
+        ->condition('c.nid', $node->nid);
+      return array_keys($select->execute()->fetchAllKeyed(0, 0));
   }
 }

diff --git a/modules/comment.info.inc b/modules/comment.info.inc
index 4321b4c..a9d7fe9 100644
--- a/modules/comment.info.inc
+++ b/modules/comment.info.inc
@@ -136,6 +136,13 @@ function entity_metadata_comment_entity_property_info_alter(&$info) {
     'setter permission' => 'administer comments',
     'type' => 'integer',
   );
+  $properties['comments'] = array(
+    'label' => t("Comments"),
+    'type' => 'list<comment>',
+    'description' => t("The node comments."),
+    'getter callback' => 'entity_metadata_comment_get_node_properties',
+    'computed' => TRUE,
+  );
   $properties['comment_count'] = array(
     'label' => t("Comment count"),
     'description' => t("The number of comments posted on a node."),

Taken from the source https://drupal.org/node/1414688#comment-7037540 and also worth looking at this http://blog.merge.nl/shorts/search-api-indexing-nodes-including-comments


Hook that act on a field being inserted or updated? I've Created a VBO view to "Modify entity values" .It's working fine. I need to perform an action when particular entity field gets inserted/updated.

So far I've tried hook_field_update,hook_field_storage_write, hook_field_insert, hook_field_presave. None of them are working

Any suggestions?

Why not use a hook_entity_update()? This hook gets triggered as soon as an entity gets updated. Inside the hook you should include some logic with respect to your field.


How can I use Pages in drupal 7? I am using Drupal 7.

I want to make different looking pages, but I can't do this because it is always using the main theme block regions, and I can't change my specific page elements. For example, I want to make a page that has a cartoon images and another page that has a movie images on the background, and the block regions can be reordered.
I tried Pages in Structure menu, but I don't understand it. I created one page, and assigned it a URL, but I can't access the page with my URL, as it says "page not found."

The Context module would help here. It allows make 'sections' within your site based on selection rules like the path, views or menus chosen etc. Using Context you can apply a CSS class to the body based on the current section and then make the background image change based on that.

Context also allows you to use alternative layouts and you to re-order blocks as needed, and there are many add-on modules for it to extend its abilities further.


Programmatically load and submit the user form I want to programmatically load the user profile form for a particular user and re-submit it without changing any of the existing values. The reasons are complex but I am dependent on gathering data during the form submit phase.

I can see functions to build an empty form ( drupal_get_form ) and to submit a new form ( drupal_form_submit ), but I can't see how to load the form prepopulated with the correct $form_state.

You can try to prepoulate value of any form programmatically & submit like this

$form_state = array();
$form_id = 'invite_form';
$form_state['values']['email'] = 'abc@xyz.com';
drupal_form_submit($form_id, $form_state);

If you want to gather data during user save as mention in question use hook_user_presave.


Workbench: Allow users to publish revisions without moderation I want to be able to moderate authors who create new nodes, but allow authors to update their existing nodes without moderation. It's not immediately obvious to me how to do this in Workbench.

It seems like I should be able to set up a Rule that will basically have

Event: After updating existing content

Condition: Content's current moderation state is published

Reaction: Set moderation state during save: Published

Something like that. I've tried a lot of combinations, but I can't get it to work.

Also, every time an author saves, it saves as a Draft, which I almost never want. Even though the Default State is set to Needs Review that only applies to new nodes. Revisions of existing nodes are always saved as drafts.

So ideally what I'm trying achieve is this

new nodes default to Needs Review
revisions of existing nodes default to Publised

This is sort of bizarre and I'd love to hear other answers, but after much trial and error with Rules, it turns out this seems to work with the following setup:

Event: After updating existing content [so it's not a new node]

Condition: Content is published [so admin has approved it at least once]

Reaction:
1. Publish Content
2. Set moderation state during save: Published

I would have thought that either #1 or #2 would have been sufficient, but strangely if they are not combined, it always reverts to draft. Also strange, the order doesn't seem to matter. I've had it working #1 then #2 and #2 then #1.


How to add class to individual radio item inside "radios"? I need to style my radios as tabs. So I created a form element like this:

$form['important_categories'] = array (
  '#type' => 'radios',
  '#label' => NULL,
  '#attributes' => array (
    'class' => array (
      'radioTabs',
    ),
  ),
);

foreach ($important_categories as $id_important_category => $important_category_name) {
  $form['important_categories']['#options'][$id_important_category] = $important_category_name;
  if(!isset($form['important_categories']['#default_value'])) {
    $form['important_categories']['#default_value'] = $id_important_category;
  }
}

This properly sets options, and sets first element as default. However, it add classes in two places. Here I wanted it:

<div id="edit-important-categories" class="form-radios radioTabs">

Here I didn't:

<input id="edit-important-categories-22" class="radioTabs form-radio" type="radio" value="22" name="important_categories">

On individual radio, I need radioTab (singular, not plural), and on default one also radioTabDefault.

Is there any built-in method to get this? Or do I need to alter my theme, like I did for labels? If so, what function I should modify?

No there's nothing built-in for this (take a look at form_process_radios(), nothing in there that would let you specify individual classes).

No need to hack core though like in the solution you linked to. Simply implement hook_element_info_alter(), and replace the process function with your own, which will be based on the original form_process_radios(), but that can handle individual classes for options.

function MYMODULE_element_info_alter(&$info) {
  // You might want more advanced logic here, to replace instead of override altogether,
  // in case other modules have already altered the core info.
  $info['radios']['#process'] = array('MYMODULE_process_radios');
}

function MYMODULE_process_radios($element) {
  // ...
  return $element;
}


Drupal automagically changing password hash This issue happened on my  localhost machine while in development but I thought nothing of it since I had multiple drupal projects and was jumping to one another constantly - I figure it was cookies or what not and was constantly resetting my passwords. However I recently went into production and this issue is still occuring.

I have a new drupal site for which I created 2 new users for testing purposes. I realized that after 24 hours or so, the login credentials for these users would not work and I would get :

  Sorry, unrecognized username or password. Have you forgotten your password?

I use these accounts to log in via browsers other than my main one and test the user interface of my production site. After each use I make sure I logout.

I made sure to configure the  $cookie_domain in my settings.php and chmod the file properly but the issue still occurs.

Recently I started tracking the hashes in the user table and low and behold they are magically changing without any human intervention ! What can be causing that ?

Oddly enough, this issue does not happen with the admin account (#1) for which I have yet to logout, and another account which was created but never used. In both cases user_check_password() returns true.

Clearing cache does nothing.

I am running the latest core with latest version of all contrib. modules.
I use SSL everywhere
I have APC and memcache running.
I use a mix of MongoDB and MySQL

The issue was with my own code.

I would load the user object every day to perform operations and change some fields value.

Instead of just passing the new fields as the second argument of user_save(), I would pass the newly changed user object cast as an array, which was causing my password hash to be re-hashed on every call of this function.


Complex View with Contextual Filter and Relationships I have a View of taxonomy terms. I use the Relationship: Content using Categoria Secciones to show, with Aggregation, the listing of the category terms, and next to it, the number of products in that category. That works perfectly. But this is the part where I am stuck: I want to add a contextual filter of Fabricante, so I can filter by another Taxonomy. I have previously, in other ocassions, used contextual filter with a Content View, but not in a Taxonomy View. I have tried to add another Relationship in my Taxonomy View: Content using Fabricante and use this relationship in a contextual filter of type Has taxonomy Term id but it doesn't work.

In summary, I want a listing of taxonomy related to a product (which works) and add the contextual filter of another taxonomy which is assigned to the same product (this is where I am stuck).

Here, if it is of help, the SQL, with the correct TID of the additional taxonomy term, which is 32619. The listing is empty, even if the product is assigned to that taxonomy term.

    SELECT taxonomy_term_data.tid AS tid, taxonomy_term_data_taxonomy_term_hierarchy.tid AS    taxonomy_term_data_taxonomy_term_hierarchy_tid, taxonomy_term_data.name AS taxonomy_term_data_name, taxonomy_term_data.vid AS taxonomy_term_data_vid, taxonomy_vocabulary.machine_name AS taxonomy_vocabulary_machine_name, field_fabricante_taxonomy_term_data.nid AS field_fabricante_taxonomy_term_data_nid, MIN(taxonomy_term_data.tid) AS tid_1, 'taxonomy_term' AS field_data_field_imagen_categoria_taxonomy_term_entity_type, COUNT(DISTINCT field_taxonomia_taxonomy_term_data.nid) AS field_taxonomia_taxonomy_term_data_nid
    FROM
    {taxonomy_term_data} taxonomy_term_data
   LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_hierarchy ON     taxonomy_term_data.tid = taxonomy_term_hierarchy.tid
    LEFT JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_hierarchy.parent =    taxonomy_term_data_taxonomy_term_hierarchy.tid
    LEFT JOIN {field_data_field_taxonomia} field_data_field_taxonomia ON taxonomy_term_data.tid = field_data_field_taxonomia.field_taxonomia_tid AND (field_data_field_taxonomia.entity_type = 'node' AND field_data_field_taxonomia.deleted = '0')
   LEFT JOIN {node} field_taxonomia_taxonomy_term_data ON field_data_field_taxonomia.entity_id = field_taxonomia_taxonomy_term_data.nid
   LEFT JOIN {field_data_field_fabricante} field_data_field_fabricante ON taxonomy_term_data.tid = field_data_field_fabricante.field_fabricante_tid AND (field_data_field_fabricante.entity_type = 'node' AND field_data_field_fabricante.deleted = '0')
   LEFT JOIN {node} field_fabricante_taxonomy_term_data ON field_data_field_fabricante.entity_id = field_fabricante_taxonomy_term_data.nid
   LEFT JOIN {taxonomy_vocabulary} taxonomy_vocabulary ON taxonomy_term_data.vid = taxonomy_vocabulary.vid
INNER JOIN {taxonomy_index} field_fabricante_taxonomy_term_data__taxonomy_index ON field_fabricante_taxonomy_term_data.nid = field_fabricante_taxonomy_term_data__taxonomy_index.nid
   LEFT JOIN {field_data_field_imagen_categoria} field_data_field_imagen_categoria ON taxonomy_term_data.tid = field_data_field_imagen_categoria.entity_id AND (field_data_field_imagen_categoria.entity_type = 'taxonomy_term' AND field_data_field_imagen_categoria.deleted = '0')
WHERE (( (field_fabricante_taxonomy_term_data__taxonomy_index.tid = '32619') )AND(( (taxonomy_vocabulary.machine_name IN  ('secciones')) )))
GROUP BY tid, taxonomy_term_data_taxonomy_term_hierarchy_tid, taxonomy_term_data_name, taxonomy_term_data_vid, taxonomy_vocabulary_machine_name, field_data_field_imagen_categoria_taxonomy_term_entity_type, field_fabricante_taxonomy_term_data_nid

I have been able to completely solve it. Using a contextual filter, but somehow I had no the options listed in the first edit, so I needed to create the filter first, and then edit again, maybe because I was using a relationship (not very user intuitive, BTW). So here it is important to use the relationship and complete the values below (all outlined in red). Now it works perfectly, the taxonomy terms are listed with the grouped count of items, and filtered by a different taxonomy, with the content Producto joining both taxonomies.


Views conditional filter Is it possible for me to apply a filter in a view on a field only if that field is not empty? In other words if the field is empty the filter is not applied (and the row is shown), and if the field is not empty the filter is then applied and determines whether to show the row or not based on the field value.

My particular use case is a job expiry date. If no expiry date is entered I want the job to show, but if an expiry date is entered, then this determines if the job is displayed or not based on the current date.

It's possible to set up 2 filters:

Filter operating on date (as you described)
Filter "job expiry" field is empty

Then use the drop-button right of Filter crieria, go to And/Or, Rearrange and change the operator for group to OR

Let me know, if you need further assistance.


A custom route to an entity form will not pass the entity I want a custom route to the normal user form. So, I've added an entry to the routing file that directs my custom route to the canonical form of the User entities:

my_profile_form:
  path: '/user/{user}/my-profile-form'
  defaults:
    _form: '\Drupal\user\ProfileForm'
    _title: 'My profile form'
  requirements:
    _role: 'administrator'

When I try to open /user/1/my-profile-form with my browser, I see the following error message:

  Error: Call to a member function getEntityTypeId() on null in Drupal\Core\Entity\EntityForm->getBaseFormId() (line 106 of ...web/core/lib/Drupal/Core/Entity/EntityForm.php)

It seems that with my custom route the form does not know who the user is.

What magic must happen to inform the form about the user?

You can try using _entity_access

my_profile_form:
....
  requirements:
    _role: 'administrator',
    _entity_access: user.update
   user: \d+

See EntityAccessCheck