Custom attribute in views fields I am trying to add custom attribute with elements like "data-url" and "data-text" in views fields, it shows something like "data-text="test text"> as output on front end.
How can i add them so that they work as attribute and not print as text ?

It's not initially obvious where and how to make these changes, fortunately it's not too hard to rewrite the output of the fields in views.

You can make a new views template fields from the display:

Other > Theme:Information link

Then edit the code adding your HTML around the Php and dropping it into your theme templates folder.

Or another way which I find is a lot quicker especially when there is a lot of changes going on in a development of a site, use the global custom text field or write the content fields.

I will use the title field to add an attribute as an example for you to follow.

In your view:

*edit Fields > title*

*Rewrite results >* tick *Rewrite the output of this field*

In the text field add the following code using the tokens options provided and editing your HTML to your requirements.

<h2 class"yourclass" data-text="test text">[title]</h2>

Save the view and you will see your attributes in your Views display.

To add to this if you use the field Global text you can hide each of your fields then rewrite the HTML to whatever you need to, adding HTML for each token in the row.


Dropdown menu with descriptions only in sub-menu elements in Drupal 7? I'm trying to implement a dropdown menu in my custom theme. At the moment, this means I have a region for the primary and another region for the secondary menu.

According to the design I would like implement, the description of a menu element should be visible - but only for sub-menu elements, like in this menu:

My problem is the following:

I can't find a way to handle different levels of menus accordingly, i.e. to add the markup of the descriptions only where necessary and the different classes on ULs.

How should I implement this kind of menu?

[I've installed the Menu Block module for some help with this. It adds several new hooks that might be useful, but we will see...]

Thanks for checking out this question!

Within your theme's template.php, you can override the theme_menu_link() function.

Target the $variables['element']['#original_link']['depth'] variable to check for the depth of the current menu item.

The variable $variables['element']['#original_link']['localized_options']['attributes']['title'] holds the "description" value entered on the menu item's edit page.


Download D7 module using Composer for D8? I'm using Drush 10, and I can't use dl to download a module, since the command was removed to push Composer use. Is there a way for me to download a Drupal 7 module into a Drupal 8 site using Composer, so that I can use Drupal 7 to 8/9 Module Upgrader on it?

The project I want to download doesn't have a D8 version yet, and it has no composer.json.

If I were you, I would just use wget.

Copy the Zip file url, ex:

sudo wget https://ftp.drupal.org/files/projects/views-7.x-3.24.zip

and then

sudo unzip views-7.x-3.24.zip


Search filter result score I'm seeing an interesting anomaly (?) I'm trying to get to the bottom of. I've set up a view with an exposed filter Search: Search Terms. I am trying to mimic the result set offered by standard drupal search module, but am finding interesting results based on the score.

When I search for "term1" (no quotes) in both standard site search, and within the view:

result set is similar, but not the same.
actual score returned for items in sitewide search, and views search are different.

So I guess, my question really is "where is the search modules' results score coming from, and how can I recreate it within a view?"

I should add I am not using any special search modules at all, just core search module.

Core search sql, as viewed from devel:

SELECT i.type AS type, i.sid AS sid, SUM((45.0578814438 * i.score * t.count)) AS calculated_score
FROM search_index i
INNER JOIN node n ON n.nid = i.sid
INNER JOIN search_total t ON i.word = t.word
INNER JOIN search_dataset d ON i.sid = d.sid AND i.type = d.type
WHERE (n.status = :db_condition_placeholder_0) AND( (i.word = :db_condition_placeholder_1) )AND (i.type = :db_condition_placeholder_2) AND( (d.data LIKE :db_condition_placeholder_3 ESCAPE '\\') ) GROUP BY i.type, i.sid
HAVING (COUNT(*) >= :matches)
ORDER BY calculated_score DESC
LIMIT 10 OFFSET 0

From the created view:

SELECT node.title AS node_title, node.nid AS nid, node.type AS node_type, SUM(search_index.score * search_total.count) AS score, 'node' AS field_data_body_node_entity_type, 'search_test:page' AS view_name
FROM
{node} node
LEFT JOIN {search_index} search_index ON node.nid = search_index.sid
LEFT JOIN {search_total} search_total ON search_index.word = search_total.word
WHERE (( (node.status = '1') AND( (search_index.type = 'node') AND( (search_index.word = 'test') ))))
GROUP BY search_index.sid, score, node_title, nid, node_type, field_data_body_node_entity_type, view_name
HAVING (( (COUNT(*) >= '1') ))
ORDER BY score DESC
LIMIT 10 OFFSET 0

There are a few things affecting the difference in results. I'm sure you noticed the queries differ slightly.

The first and core issue is that the search module's main table is search_index, so each row is built around entries in that table and then joined outward to get more information. Your view is built around the node table and joined the other direction to search index.
The core search uses inner joins to get node data, which will be more limiting in its result sets (see this answer.)
The search_dataset table isn't joined from the Views search (see this answer for an explanation of why.)
Core search multiplies the search scores by relevance, which shouldn't affect their ranking, but looks confusing. See line 496-500 of search.extender.inc.

I know I only answered the first half of your question, but I hope this helps. I'm not sure it's possible to get a View to exactly mirror your search results without considerable customization.


Configuration Form Access Denied I am porting a module to Drupal 8. I have correctly setup the path in routing.yml but it always says access denied even I am logged in with user 1.

routing.yml

flood_control.flood_control_config_form:
  path: '/admin/config/flood-control'
  defaults:
    _form: '\Drupal\flood_control\Form\SettingsForm'
    _title: Flood Control
  requirement:
    _permission: 'administer site configuration'

.links.menu.yml

flood_control.flood_control_config_link:
  title: Configure Flood Control
  description: 'Configuration Form for flood control'
  parent: system.admin_config
  route_name: flood_control.flood_control_config_form

What am I missing wrong?

Can be just a typo, look at requirement, you missed a 's'.

  requirements:
    _permission: 'administer site configuration'

Look at here for a complete skeleton. (or a collection of modules examples here)


How can I configure drupal to share modules between two installations on the same server? Say I want to run siteA.com and siteB.com from the same remote server. How can I share the modules but not site specific configuration. I don't want them to have the same titles use the same modules but it seems a waste of space to be installing the same modules if they are running on the same server.

Please note: I selected the answer below because it looked like an answer. However, seems to be useful only if the server is local? I do not use the terminal to connect to my site. I wouldn't be sure how to go about that either other than trying to do it via some shh connection.

There is a great way of accomplishing this, it's called multi-site.
See http://drupal.org/documentation/install/multi-site
and http://drupal.org/node/43816 for a start.

A great project that offers multi-site hosting is Aegir. In Aegir you can even create multiple platforms that run 1 or more sites.
See http://aegirproject.org

1 thing: you can not run multiple sites from a subdirectory if you run with Aegir/Drupal, that won't work with how Drupal is designed, but if your running on some GNU/Linux, then you might be able to symlink something together.

It's true you can use the sites/all/* folders to share modules/themes/libraries, but 1 thing is missing:
In the sites/ folder, you have to create a directory, containing the config files, files directory (etc) for every individual site that you want to run.

You could also offer multiple sites from 1 directory via an alias, but that's not what your looking for now i believe, just as an extra bonus tip. ;) Hope this helps a bit.


Change ID of webform hidden element How can I change the ID of a hidden element (created with the Drupal 6 webform module) using hook_form_alter()?

The ID that it outputs is something like '#edit-submitted-component-name'. I need the ID to be something very custom and I need to avoid changing it with Javascript. The form API does not support the #atrributes token on hidden elements, so I can't set the ID via hook_form_alter();

Any suggestions would be really helpful. Thank You.

I had a similar issue to deal with. I need to generate form IDs programmatically so I implemented below code.

function voci_comment_form($form, &$form_state, $cid) {
     $form['#attributes']['id'] = 'voci-comment-form-' . $cid;
     $form['#attributes']['class'][] = 'voci-comment-form';
     $form['body'] = array(
      '#title' => 'Post a comment',
      '#type' => 'textarea',
      '#resizable' => FALSE,
      '#rows' => 1,
     );
     $form['comment'] = array(
      '#type' => 'submit',
      '#value' => 'Comment',
     );

      return $form;
   }

It's true that you can set $element['#attributes']['id'] and that will apply to the form field.

I hope this helps... :)


How to switch OG group members in bulk to another group D7. I have Organic Group (OG) installed. Out of the approximately 150 groups on my website, one is sticky and titled "Welcome New Members." It has about 2,000 members.
Recently, a problem developed with that group only and a user gets a 500 error when posting. Another kind of error is "The website encountered a difficulty. Please... blah blah."

The other groups seem to be working fine.

I could be wrong, but it seems to me that the easiest way to fix this is to create another group and transfer all the group members, along with their posts to the new group. Then I could delete the original group and its content.

Looking at the data base table "og_membership" I see that all members of all groups are mixed together in the same table.

I need to extract those nodes and users that belong to that one group. I guess a dump of selected users and nodes based on the group ID could do the trick. But how do I upload them back into the same table with a different gid or etid so they also belong to the new group? Or is there a way in the data base to "search and replace" a group ID (gid) with another?

I have tried the following formula but I am being told it is the wrong syntax (etid is the entity ID:)

update [og_membership] set [etid] = replace([etid],'[776]','[10177]');

Any pointer would be greatly appreciated. :)

OK. Finally got it right. The easiest way to do this is to do a dump of the og_membership table into a text file.

Then run a "search and replace" for the gid, replacing the old gid with the new one. A simple word processor is ideal for this. Any string replacement can be handled this way.

Then importing that text file into the og_membership table.

Voila! All members have switched to the new group and they don't even know it! :)


Add a class to a row in a view i'm trying to create a module that adds a 'new' class to a row based on the date it was published.

So i thought of doing something like

if ($data > 10 days ago){
  $this_row addclass new
}

But whats the best way to do this? I would like to put this in a module so i can simply turn it on and off and avoid problems with template files from ds.

I can only find a way using hook_views_pre_render to add a class to all the rows, but nothing about adding it to one specific row. Maybe i need to use another hook?

Writing a view handler would be the perfect way to do this. The handler itself will be almost as simple as your example code.

However getting everything right to get the handler called from views isn't easy. A good example to learn from is the maillog module. It integrates its log table with views and adds a custom handler.


How to add a custom field which dynamically renders different output according to certain conditions? I am writing a module which adds a new field. Similar to the serial module, the field cannot be changed or filled anyhow when creating a new node.
I just want the field to create a different output according to certain conditions, for instance if the user has a certain role or not.

For instance, when a user visits a node of a content type which has this field enabled, check for php conditions and then output different html.
Is the user a guest or registered? If guest, output a link which says "register to do this".

It would be really cool if this would then automatically work with views? Like a view which outputs this field for every node of that content type.

Ive tried using computed field but this module computed the result once and then displays this all the time... only solution would to alter the cache db, which seems a little unsmooth to me.

I already added a field using the examples module, so this is what I got so far:

function proposal_field_field_info() {
  return array(
    // We name our field as the associative name of the array.
    'proposal_field' => array(
      'label' => t('Proposal Field'),
      'description' => t('Adds proposal feature'),
      'default_widget' => 'proposal',
      'default_formatter' => 'proposal_field_simple_text',
    ),
  );
}

Computed Field seems to meet your needs.

  These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views.

Emphasis mine. Either require it in your module and use it, or use it's code, it is open source after all.


What is the correct way to setup Drupal file permissions on a VPS? I am testing a Drupal site on Google Compute Engine. I have a problem with file permissions.

I would like to be able to access and edit my files trough SFTP and still have Drupal functioning as it's supposed to.

Letts say my user for SFTP is 'user'. If I do sudo chown user:www-data -R /var/www/ I can edit files via SFTP. But then I can not make changes or add files in Drupal (for example add a new module trough Drupal, even clearing caches doesn't seem to work).

If I do sudo chown www-data:www-data -R /var/www/ evrything in Drupal works, but I can not make changes to files trough SFTP.

I have tried adding both users ('user' and 'www-data') to a group called 'drupal' and running the command sudo chgrp drupal -R /var/www/ but this doesn't fix the problem.

user:www-data are the correct permissions IMO. For security reasons, the web server should not be able to write to the file system, except for files and temp folders. You haven't mentioned suhosin or anything so I'm assuming you have a typical setup.

Drupal have unfortunately made the above a bit confusing by including a method to update modules via the UI (v. bad idea IMO, swapping security for convenience).

If you still want to do it, it can be solved with *nix permissions on most platforms; the exact nature will depend on your server's architecture and setup. There's an example here and in the comments of the official docs page to get you going, but generally speaking just search for how to manage these permissions for your server type generically - there's nothing Drupal specific about the commands you need to run, so you're closing off a lot of potential help if you include Drupal as a keyword in your searches.


Drupal Simpletest for Image Upload The following code is working fine for uploading images. The node is being created but the uploaded images (under /sites/default/files/simpletest) are getting deleted after each complete test suite run.
Here the sample code
public function testArticleCreate() {
  $edit = array();
  $edit['title'] = $this->randomName(8);
  $edit["field_description[und][0][value]"] = $this->randomName(16);
  $field_name = 'field_image';
  $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = 'sites/default/files/test-image.png'; // existed
  $this->drupalPost('node/add/article', $edit, t('Save'));
  $this->drupalGet("node/1/edit");
  }

Screenshot

Getting 404 not found for the image path (sites/default/files/simpletest/505284/test-image.png)
Any suggestions?

I came to know that it's by design but not a bug. We can do nothing with the uploaded images. The SimpleTest files will be deleted automatically after successful test suite run.


Removing Duplicates with hook_views_prerender I have a view (filtering on content) that is returning duplicates. I am trying to used hook_view_prerender to remove those duplicates... but even after running this, I still get duplicates... Any ideas? Here's my function (and yes I know the function is running):

function customedm_views_pre_render(&$view) {
  $used_nids = array();
  if ($view->name == 'new_resources'){
    echo ('hi');
    foreach ($view->result as $row){
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
      }
    $view->result = $new_view_result;
    }
  }

You do not need to do this - simply use Distinct.

Edit the View, open the Advanced section -> Query Settings -> check the "Distinct" checkbox and save the view.

Edit:
In case you do use Distinct already, there are some cases where this can occur. Here is an issue discussing this - https://www.drupal.org/node/1765730, and this one has a code example that manipulates the result similarly to what you are trying to do - https://www.drupal.org/node/1223448#comment-4757898


Add value to a custom composite element in webform via hook_update_N Testing out some bits with webform. I have created a webform via my module. In it I have a number of elements including a custom composite. Inside the custom composite I have several elements, one is a select element with a list of options (i.e. allowed values).

Now comes time I need to do some updates. That is run hook_update_N on an existing module/set-up.  I have updates for all other fields (not webform) working correctly. Rough code shown below:

/**
  * Update for mymodule to add more options to the paragraph and webform custom composite.
  */
 function mymodule_update_8001() {
   // Updates the paragraph allowed field
   $fields = \Drupal::entityTypeManager()->getStorage('field_storage_config')->loadByProperties(array('field_name' => 'myfield'));

   foreach ($fields as $field) {
     $allowed = $field->getSetting('allowed_values');

     // New value(s) to add here.
     $allowed['test'] = 'bob was here...';
     $field->setSetting('allowed_values', $allowed);
     $field->save();
   }

   // Code to update the custom composite element to go here.

 }

I know it is rough code, ignoring that, still getting my head around the changes to Webform too.  I know the \Drupal::entityTypeManager()->getStorage method doesn't work for webform composite custom elements and can't see any update function in the composite example module.

So the question is how to I get the options (allowed values) of a select in a custom composite from the webform so I can edit, add, update, etc... when I do other updates to my module?

The method noted in How do I programmatically update the allowed values of a list field? works for basic fields but with for dynamic options. It will not cover what I need here as (a) it is not performing an update of existing fields and (b) doesn't appear to work with custom composite in WebForm, or at least I cannot get it to work, with a select.

After trawling through the Webform source think I have an answer.

/**
 * Update using hook_update_N for mymodule to add more options to a webform custom composite.
 */

function mymodule_update_8001() {

    . . .

    // Update a composite element in a webform
    $webform = \Drupal::entityTypeManager()->getStorage('webform')->load('webform_id');
    $elements = $webform->getElementsDecodedAndFlattened();

    // Add new options here.
    $elements['my_composite_id']['#element']['my_composite_element_id']['#options']['my_new_option'] = 'My new option text';

    $webform->setElements($elements);
    $webform->save();

    . . .

}

Please let me know if there is a better way.


How do I configure the database using php_server module I am trying to set up an existing site locally. It seems that Drush cannot find the site. When I run drush cc all, I get this error.

  No Drupal site found, only 'drush' cache was cleared.

I think the issue may be with my server configuration. I am using the PHP Server module, and I'm not sure how to get it to point to the database.

This is what drush status returns, for your reference:

 Drupal version         :  7.41
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database username      :  root
 Database name          :  quorum
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/7.0/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/Cellar/drush/8.1.11/libexec/drush.php
 Drush version          :  8.1.11
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/Jillian/ideometry/quorum-dev
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default

This is because you are running the drush command in directory where your project code doesn't exists. I think you are getting logged in to home directory of a server where the project code does not exists. Your project code is in another directory. for e.g

-opt
 -webcode
  -project_code
-home
-etc

So you are getting loggedin in the home directory but your code is inside /opt/webcode/project_code. You need to reach to project_code directory first and then run the drush command.

You can use filezilla if you are not aware of the directory stucture. It will help you to know which directory has your project code.


Add image field programatically in D7 I'm moving a bunch of info from an xml feed into drupal nodes. I'm a little hung up on adding the image. I'm using php copy() to copy the image from a url to my drupal directory. From here, I'm not sure how to insert the field info into the node in such a way that an fid and all of the required data is generated. What is the preferred way to do this?

OK, what I came up with here:

function save_my_image($uri) {
  //copy file into drupal files directory
  $contents = file_get_contents($uri);
  //then save into drupal's file system
  $file = file_save_data($contents);
  return $file;
}

file_save_data() (http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_data/8) will handle creating an fid for the file and keeping track of it generally.. then simply add the fid to the node in question and you should be golden.


Get a dropdown for Views: Filter: Taxonomy Term Name I'm using taxonomy term name to filter views based on their taxonomy. I've tried basic or Better Exposed Filters and setting a relationship but still no option for a drop-down select menu.

I can't use filter by "Taxonomy Term: Term" because this uses the TID not Term Name in URL.

If your views is based in content type, you should use the term reference field in the filter. Example:

I have a content type of services composed of title, body, service category(term reference).
In my services views, I will add service category as filter. In my Better Exposed Filter, I can configure that service category if I want a drop down filter or autocomplete.

Using taxonomy term name shows autocomplete filter.

I hope it helps


href link assigning callback action - ajax I have a situation where I would like to define a href link and when it is clicked, for it to trigger an ajax response such as sending back some information which can then be shown on the page...

Part 1. Creating the link... So I've created the link via:

    $url = Url::fromUserInput('#');

    $nxt_button=Link::fromTextAndUrl('Submit Application',$url);
    $nxt_button=$nxt_button->toRenderable();

    $nxt_button['#attributes'] = [

    ];

    $output['link1']=array(
        "the_link"=>$nxt_button,
    );

Now in the '#attributes' I assume i could put something like 'callback' => 'name of function to be run' ... but, if the function to be run resides in another object say 'ajax_test_script.php' how would I do that?

Part 2. Say the server side responding code, was in a different class called 'ajax_test_scirpt' and the function to call is 'start' ... If I was sending back information via:

$response=new AjaxResponse();
$response->addCommand(<<what goes here>>);
return $response;

And these lines of code were inside the function 'start'... What would I put as the input parameter for addCommand, if I wanted the response to behave such that it could call the javascript function outlined below, which would be attached to the page (e.g call readMessage passing in the parameters needed by the readMessage function):

(function($, Drupal) {
/**
 * Add new command for reading a message.
 */
Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
    // Place content in current-msg div.
    $('#current-msg h2').html(response.subject);
    $('#current-msg p').html(response.content);
    // Remove from unread list.
    $('#msg-' + response.mid).remove();
    // Add message to read list.
    $('#read-msgs').append('<li>' + response.subject + '</li>');
}

})(jQuery, Drupal);

Any help is appreciated.

For anyone needing help on this, as the information out there seems to be either related to forms only or seems rather over convoluted... ajax callback can be added to normal links, by defining the link as outlined above (in the question) - but adding the '/nojs/' prefix to the Url defining portion of the code and adding the class 'use-ajax' in the attributes section of the code e.g. :

// Define the link.
$url = Url::fromUserInput('/nojs/ajax_call_url');
$the_link = Link::fromTextAndUrl('Submit Application',$url);
$the_link = $the_link->toRenderable();

$the_link['#attributes'] = [
  'class'=>'use-ajax',
];

// Add the link to your render array.
$output['link1'] = array(
    "the_link"=>$the_link,
);

Now in the 'name of your module'.routing.yml file add the route to where your ajax callback function is... as '/nojs/' is used (as it has to be by the looks of things) it means your path must be defined with the prefix '/ajax/' followed by the path of your choice e.g.:

path: '/ajax/call_ajax_url'

the _controller attribute in the routing.yml file, will be defined to point to where your ajax callback command is defined... e.g. will point to whatever object and function holds the

    $message="hello";
    $response=new AjaxResponse();
    $response->addCommand( new HtmlCommand("#current-msg",$message);
    return $response;

Hope this helps someone - as it took a while for me to find the info necessary to resolve this issue.


Is there a ready made gruntfile available for Drupal Bootstrap Child Theme (SASS) This applies to Drupal 7.

I am fairly new to grunt and can't really make much sense of out of a gruntfile. I've just started with a drupal child theme (which has been created off bootstrap SASS startkit).

Can you point out a readymade grunt file which I can use to watch and compile my scss (output as css) and minify js.

module.exports = function(grunt) {
grunt.initConfig({
compass: {
 dist: {
    options: {
      sassDir: 'sass',
      cssDir: 'css',
      environment: 'production',
    },
  },
},
watch: {
  css: {
    files: ['sass/*.scss'],
    tasks: ['compass'],
  },
},
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.registerTask('default', ['compass']);
};


How can I read Yaml files? I have been trying to figure out how to decode ( also try to encode) my YML file so I can have full control over on PHP array. I try this...

And as you can see, I did not get the information inside of the YML file.

My question is what I'm doing wrong ? Why is not showing me the information inside of /core/modules/toolbar/toolbar.breakpoints.yml file?

Here is code snippet...

use Drupal\Component\Serialization\Yaml;

$breakpointEncoded = Yaml::encode('/core/modules/toolbar/toolbar.breakpoints.yml');
var_dump($breakpointEncoded);

The arg to decode is:

  The raw data string to decode

So you need (e.g.):

$breakpointEncoded = Yaml::decode(file_get_contents('/PATH/TO/core/modules/toolbar/toolbar.breakpoints.yml'));


What file and directory permissions do I need in my Features directory? I just tried to generate a feature on my test system and Drupal complained that the web server didn't have write permission for the Features directory. I changed the permissions from the normal 750 & 640 for modules directories to 770 and 660 and it worked fine.

I can't see any documentation that says you need to do this so I'm concerned something isn't set up correctly.

Should this work with the 'normal' permissions?

This is because Feature is doing something that's a little bit out of the ordinary ;-)

This is also one of the reasons I have my filesystem laid out as follows:

 sites/all/modules/
  - custom // Custom code.
  - contrib // The actual features.module is here.
  - features // This is for my Feature modules.

Because this means I can set the permissions on my Features differently to the contributed modules directory. Usually 760 I think. Then so long as the features directory is owned by a group that Apache is a member of, everything should work as expected. I do sometimes have to run a chown -R from my Drupal root, but that's because *nix admin has never been a strong point of mine.

Obviously everything on my world facing servers (read: not my local machine) is more secure than this, as should yours be.

That said, on my local machine I always end up forgetting something and just chmodding everything to 775 because I'm in a hurry.


hide all of node form except a file upload field Bit of a weird one....

I'd like to call a node edit form into an overlay but have it only show a file upload (cardinality unlimited) fieldset and the save button

I know I can program the formAPI bits, get the files and save the node myself, but In this (possibly strange) case I'd like to use the existing form.

Obviously can CSS it, but I'd rather have it in PHP.

So far I've set up a loop in a conditionally invoked form alter that finds form elements and then... well, unsetting/hiding them gets them off the screen but then the upload field doesnt work

foreach($form as $key => &$value) {
  if(is_array($value) && isset($value['#type'])) {
    if(  !in_array($value['#type'], array('hidden', 'value'))
      && !in_array($key, array('field_my_file_field', 'actions'))) {
      unset($form[$key]);
      //or $form[$key]['#type'] = 'hidden';
    }
  }
}

I'm guessing I'm compromising the form array, so it's not working in a callback somewhere.

Any ideas? Or a better suggestion for getting just the field upload fieldset onto a page?

Thanks!

You can use Field Permission module to hide all those fields which you don't want to show on node edit or node create form for all user type which you want.


How to replicate this form with exposed filters I'm wondering how can I achieve something like that "Browse Listing" block (on the right) with exposed filters - http://demo.rlisting.com/rlisting/result
Should I create Content type for each Property type and add Listing type as a vocabulary or to use only one content type for all properties and then add property and listing types as vocabulary or as text fields with select list?
And more importantly how Min & Max range could be created?

using drupal 7.14, views 3.3

You should create a view, with display page and add some exposed filters.
Then you have to enable the function "Expose form in block", or something like this, that creates a block with your exposed filters.


Can't get fid of the saved file after file_save_data I have been trying to get the fid of the file which my custom module is saving and every time I end up getting the error "Trying to get property of non-object in report()". I have tried file_object->id() and file_object-> fid ->value but neither are working. This is my code in .module file:

function file_write($source , $name) {

$uri =  file_default_scheme() . '://'.$name.'.txt';

$file_object = file_save_data($source, $uri, FILE_EXISTS_REPLACE);
return $file_object;
}

And this is where how I call it and try to get fid:

$file_object = file_write($source, $name);
$fid = $file_object->fid->value;

Is there anything wrong with the code?
I also tried using other methods, but no luck so far.

In Drupal 7, $file_object->fid should work.

Looking at the code you have tried ($file_object->fid->value, file_object->id()), I guess you have been mixing up Drupal 8 and Drupal 7 documentation.


Site search not picking up all pages I've only so far added 5 or so nodes to my site. I've noticed that not all nodes are coming up in the search results. What I mean is searching for their title doesn't find them :S
It works for some but not others. Why would this be the case>

The search table is created on cron job. So the sites that are added before the cron job would be displayed. Could you try running the cron and then try to do the search.


Why won't this update in hook_update_n() run in batches correctly? I am working on this issue in the Feeds issue queue: https://www.drupal.org/node/2341407

I am trying to make the updates to the importers run in batches. I can't figure out why this won't run in multiple batches when there are multiple importers. What happens is instead of seeing a progress bar reload a few times when running update.php, it loads once and processes all importers in a single batch.

The code works well except for batching. Below is the code. Thanks in advance!

<?php

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['total'])) {
    // Load all importers.
    $importers = feeds_importer_load_all(TRUE);
    $sandbox['total'] = count($importers);
    $sandbox['current'] = 0;
  }

  foreach ($importers as $importer) {
    $processor = $importer->processor;
    $config = $processor->getConfig();
    foreach ($config['mappings'] as $id=>$mapping) {
      // Act on mappings that do not contain a colon.
      if (!strpos($mapping['target'], ':')) {
        // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
        $info = field_info_field($mapping['target']);
        if (!empty($info)) {
          // Act on file or image fields.
          if (in_array($info['type'], array('file', 'image'))) {
            // Add ':uri' to fix the mapping.
            $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
          }
        }
      }
    }
    // Add the updated config and save the importer.
    $processor->addConfig(array('mappings' => $config['mappings']));
    $importer->save();

    drupal_set_message(t('@importer fields have been updated.', array('@importer' => $importer->id)));
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('@importers importers processed.', array('@importers' => $sandbox['total'])));
  }
}

Why are you expecting it to work as a batch, it's doing exactly what you're asking it to do and processing all the importers in the foreach loop!  foreach ($importers as $importer)  It's not magic, it can't assume that's what you want to batch  :o)

Try this instead (obviously I haven't tested it, I've just typed it straight into the text editor here - but it's essentially your code so it should be fine);

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['progress'])) {
    $sandbox['importers'] = feeds_importer_load_all(TRUE);
    $sandbox['progress'] = 0;
    $sandbox['max'] = count($sandbox['importers']);
  }

  $importer = array_pop($sandbox['importers']);
  $processor = $importer->processor;
  $config = $processor->getConfig();
  foreach ($config['mappings'] as $id => $mapping) {
    // Act on mappings that do not contain a colon.
    if (!strpos($mapping['target'], ':')) {
      // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
      $info = field_info_field($mapping['target']);
      if (!empty($info)) {
        // Act on file or image fields.
        if (in_array($info['type'], array('file', 'image'))) {
          // Add ':uri' to fix the mapping.
          $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
        }
      }
    }
  }
  // Add the updated config and save the importer.
  $processor->addConfig(array('mappings' => $config['mappings']));
  $importer->save();

  $sandbox['progress']++;

  // Set the value for finished. If progress == max then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['progress'] / $sandbox['max']);

  if (empty($sandbox['importers'])) {
    return t('@importers importers processed.', array('@importers' => $sandbox['max']));
  }
}

For hints about my alterations see the API documentation - note that the naming convention changes don't alter anything, I just made them for Drupal core consistency.  The most important thing to note is that all I've really done, is to remove the foreach loop so one importer gets used at a time.

NOTE: For clarification (as it's really not obvious) the percentage shown relates to the number of batch operations run - not the amount of passes through one batch operation.  See _batch_process():

// Total progress is the number of operations that have fully run plus the
// completion level of the current operation.
$current    = $total - $remaining + $finished;
$percentage = _batch_api_percentage($total, $current);

On a normal batch operation you'd pass in several separate operations like this;

$batch = array(
  'operations' => array(
    array('batch_example_one_process', array($options1, $options2)),
    array('batch_example_two_process', array($options3, $options4)),
  ),

And you'd see 50% completion only after batch_example_one_process has completed.  I guess you can see that your code is working correctly though, as it clearly only processes one processor per pass - as long as they all get processed, you can confirm that batch api is working correctly.


How do non administrators add content? In Drupal 7, how do I let the users with a specific role add new articles?

I logged in as administrator, set the permission for the role to allow creating and editing nodes that are articles.
When I login with a user with the role, for example, "NewRole," I do not see any control or dashboard that allows me to create new articles.

How do I start adding new articles as this new user?

You probably don't have the Navigation menu enabled/placed in a region, or have any other links to direct a user to the Create Content page.

As an administrator, either enable that menu or create a link to "node/add" (to allow the users to see all the content types for which they can create a node); you can also add a  link to "node/add/article" in another menu or in your theme.

To allow a user to see the administration toolbar, they must have a role that has the permission to use the administration toolbar. See below:


How to make the Webform submit button use an uploaded submit-image? I am building a D7 website and I want the following feature for the site admin, regarding the Webform module:

When the admin creates a webform, the admin uploads a submit-image and this image is used as the submit button for the webform. so if he uploads a "click-me.png" I want the path to this image to be used in the input[type=image] class="form-submit" src="/path to uploaded image"

Is there a simple way to achieve this, or do I have to seperately hardcode the behaviour I want for each webform?

P.S. By default webform's submit button is of type "text" and not "image", but I easily managed to change this using this excellent solution.

The easiest way to do this would be to write your own module. The place to start looking would be here: http://drupalcontrib.org/api/drupal/contributions!webform!webform.api.php/function/hook_webform_component_info_alter/7


How to export field collection with Drupal 7 views data export plugin? The Views Data Export plugin appears to work perfectly with the data that I have, though I have a field called "Items Bought" consisting of fields ("Item Bought" and "Cost"). For each content type of type "ShoppingRecord" a user could have one or more "Items Bought" field collections (i.e. Bannana $2, Apple $5).

When I add the field to my "page". I noticed that when I create a view with the "Data Export" and use CSV as the option, I am getting blanks for all the rows in the "Items Bought" column. Is there some way to get the plugin to recognize field collections and maybe export them all into the same field in the CSV? All the other fields that are not field collections appear to export properly.

If you only need the first result you can add a relationship in the view. Search for the name of the field collection. Once you add this relationship you should be able to access the field collection items and add them to your output.

If you want all the values you need to search add the field collection to your view rather than the fields directly. You then have the options of how to display the results but these options are limited.


menu item for current page is missing a href tag for anonymous user drupal 8:
Theme used "bartik".

If user is logged in, the active menu item has an  - tag, if not the tag is missing.

Is this the expected drupal behavior? btw. the same happens on the language switcher block.

How can i output the a-href tag for anonymous users? This would make theming menus much easier. Thx for any help or pointing me into the right direction

markup for anonymous user

.....

    c

markup for admin user

......

    c

I fixed this issue by overriding menu.html.twig. You could override menu--main.html.twig instead, if you just want to target the main menu:

menu.html.twig

  ##REPLACE THIS LINE:## {{ link(item.title, item.url) }}
  ##WITH THIS LINE:## {{ item.title }}
  {% if item.below %}
    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
  {% endif %}

I submitted a bug report here: https://www.drupal.org/node/2695619


AJAX / AHAH 'Add More' Button on Unlimited Cardinality Fields Conflicts with Custom Submit Handler I have a node add form with some integer text fields that have unlimited cardinality, which causes an AJAX 'Add More' button to be displayed for those fields. The form also has a custom submit handler that is defined in a custom module.

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

$form['actions']['gaylord_submit'] = array(
  '#type' => 'submit',
  '#value' => t('Add Gaylord'),
  '#submit' => array('inventory_stocking_ticket_form_gaylord_submit'),
  '#executes_submit_callback' => TRUE,
  '#name' => 'edit-gaylord-submit',
  '#limit_validation_errors' => array(),
);

function inventory_stocking_ticket_form_gaylord_submit(&$form, &$form_state) {
if ($form_state['clicked_button']['#id'] == 'edit-gaylord-submit') {
  node_form_submit($form, $form_state);

//do custom stuff here

}
}

Here's my problem: If the custom submit handler function is defined inside the hook_form_alter function & there are no unlimited cardinality fields, everything works great, node is created or modified, form values are saved, & my custom submit handler stuff is performed. If, however, I have a field with unlimited cardinality & my custom submit handler function is defined inside the hook_form_alter function, I receive an error: PHP Fatal error:  Call to undefined function inventory_stocking_ticket_form_gaylord_submit() in /hosting/somesite/com/htdocs/cms_sandbox/includes/form.inc on line 1464 & a white screen of death. If I move the custom submit handler function outside of the hook_form_alter, there's no error even with unlimited cardinality fields, the node is created or modified, & my custom submit handler stuff works, but field values are not saved.

I've further discovered that commenting out the code that creates the AJAX 'Add Another' button in core's field.form.inc makes everything work, even with the submit handler inside the hook_alter & unlimited cardinality fields. Of course there's no 'Add Another' button now, defeating the purpose of having unlimited fields.

I have two questions:

What is causing the conflict & PHP error when the submit handler inside the hook_form_alter is combined with unlimited cardinality fields?
Why won't the custom submit handler save field data when it is defined outside of the hook_form_alter?

If I could solve either of these problems I'd have what I needed. Any help is hugely appreciated.

try this:

function formalter_form_alter(&$form, $form_state, $form_id) {
  // override the default submit
  $form['#submit'] = array('inventory_stocking_ticket_form_gaylord_submit');
  // include the default submit and your custom submit
  //$form['#submit'][] = 'inventory_stocking_ticket_form_gaylord_submit';
}

function inventory_stocking_ticket_form_gaylord_submit(&$form, &$form_state) {
  if ($form_state['clicked_button']['#id'] == 'edit-gaylord-submit') {
    node_form_submit($form, $form_state);

    //do custom stuff here

  }
}


How to limit/throttle speed of Views feed? I have a Views feed that includes all recent content on my website. I run this through an IFTTT applet to auto-post to Twitter.

Is there a way to throttle how many feed items are added to the feed at once, in order to limit the number of tweets that come out of the IFTTT applet?

For example, if I add 10 pieces of content, I'd like the feed to reflect the first five now, and the next five after fifteen minutes.

ETA: I'm not limiting myself to using only Feeds, other modules or suggestions for a custom module are welcome.

This is possible, but not with just feeds.

You'll have to implement some sort of queuing, that looks at previously published nodes to determine if the new group of nodes can be added to the feed yet, or if they need to wait.

You should be able to get this working with some clever rules and a few VBO views.


Alter main menu button text and URL path depending on OG Role I know you can change menu links depending on drupal based roles (authenticated, non authenticated...) and by using Rules module also.

I am using Organic Group roles and I am having difficulties in showing different links on the menu bar depending whether my site's user IS or ISN'T a member of a group.

When he/she signs up a 'join' button is on the nav bar --> after joining a group he can now write content so the 'add' button replaces the join button on the nav bar with the appropriate URL paths.

Can a hook be used to do this?

You can do this using the access callback of the items array in hook_menu_alter. The implementation of the user menu gives a good example.
To make it work with Organic groups, you could declare an access callback function using og_is_member or og_user_access:

function MY_MODULE_menu_alter(&$items) {
  $items['MY/PATH'] = array(
    'access callback' => 'MY_MODULE_custom_menu_access_callback',
    // Assuming your group is a node and the menu appears on the nodes
    // page (/node/[nid]), then array(1) would pass the node ID to your
    // function, which in this case acts as a group ID.
    'access arguments' => array(1),
    // etc...
  );
    return $items;
}
function MY_MODULE_custom_menu_access_callback($gid) {
  return og_is_member('node', $gid);
}

Where MY/PATH would be the path to the entity type representing the group. If you are using a node as a group, this would be node/%. As 'access arguments' we use the arg function. 0 would be node and 1 would be the node ID of the node.


Steps to update vendor files after pulling changed composer.lock file Let's say I work in a group and somebody else did composer update and pushed changed composer.lock file. I pulled it and now I have to do update too, to match the files from changed lock file.

In symfony I would delete vendor dir and run composer install. But in drupal not all files are in vendor dir.

What is the best workflow in this case? Should I manually delete old vendor files (what dirs exactly?) or there is some composer command that will do all the work for me - check current vendor files with versions from composer.lock file and update what has to be updated?

In symfony I would delete vendor dir and run composer install. But in
  drupal not all files are in vendor dir.

  What is the best workflow in this case? Should I manually delete old
  vendor files (what dirs exactly?)

See .gitignore in your project dir:

# Ignore directories generated by Composer
/drush/contrib/
/vendor/
/web/core/
/web/modules/contrib/
/web/themes/contrib/
/web/profiles/contrib/
/web/libraries/

In case you want to do a fresh start with composer install you can delete all files with:

git clean -fdx .

See https://www.git-scm.com/docs/git-clean/1.7.0


How to set header and footer for any drupal_mail messsage? I am working with drupal 7 site.

I would like to know how to create email template for any email sent from drupal system?

Is there any hook or template should I implement in my custom module or override to make it beautiful like any newsletter emails are received.

I want following emails should be theming.

User Activation User
Password reset
Comment Notification etc...

Email template should looks like

<header>
Dear <User>
<Message Body goes here>
Thanks
<footer>

Take a look at hook_mail.  All emails from the system "should" go through that.  You can alter the $message['body'] to add your header and footer.  If you only want to do this for certain emails, you can use an IF condition on the $key.

Edit: I think I pointed you to the wrong hook.  You probably want to use hook_mail_alter to change every email that Drupal sends.


Can not access to the nth product's variation ( n > 1) programmatically I have a product type called gift with 3 different variations.

I add an attribute to it so that a user can choose a custom variation based on the attribute, attribute (A, B, C).

I also have a custom checkout pane, If a user choose the first variation (by choosing the attribute), i can access the variation that is selected. for example by using 2 lines of code below:

<?php
$variations = $gift->variations->getEntity();
?>

Or

<?php
$gift->variations->target_id
?>

But if a user choose another variations except the first variation (for example: variation B), I can not access to that variation.

<?php
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['#order_entity'] = $this->order;

    $order_items = $this->order->getItems();
    /** @var \Drupal\commerce_order\Entity\OrderItem $item */
    $item = $order_items[0];
    $gift = $item->getPurchasedEntity();
    $gift = Product::load($gift->id());

    $variations = $gift->variations->getEntity(); // Just works for first variation
    drupal_set_message('bundle: ' . $variations->bundle());

    // This line of code works for just first variation too
    // $id = $gift->variations->target_id;
}
?>

Regards

Basically, I wanted to get attributes attached to the current variation. According to Bojanz' answer: https://www.drupal.org/node/2893842#comment-12163314, there was no need to use $gift->variations. Bojanz corrected and told me $item->getPurchasedEntity() is the product variation, not the product

So the code would be:

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $pane_form['#order_entity'] = $this->order;

    $order_items = $this->order->getItems();
    /** @var \Drupal\commerce_order\Entity\OrderItem $item */
    $item = $order_items[count($order_items) - 1]; // the last item added to the order
    /** @var \Drupal\commerce_product\Entity\ProductVariation $gift */
    $gift = $item->getPurchasedEntity();
    $attribute = $gift->getAttributeValue('attribute_gift_type');
  }


In Drupal 8 module creation, why don't I have to put the directories "modules" and "src" in the namespace of my yaml file? I watched a tutorial on Drupal module development, and the namespace he used didn't include modules or src in the yml file (it is around 4:30).  I'm sure this is a basic PHP question, but why didn't he have to put in those directories?

"Why", in a general sense, is for convenience. Drupal 8 uses PSR-4 autoloading and maps the respective module namespaces to each module's src/ directory. See drupal_classloader_register():

function drupal_classloader_register($name, $path) {
  $loader = \Drupal::service('class_loader');
  $loader->addPsr4('Drupal\\' . $name . '\\', \Drupal::root() . '/' . $path . '/src');
}


how do i set the first page of my site in drupal 6? I am new to drupal.

I started ctreaing site but facing problem in

how do set my first page in drupal

eg:

when user type

www.mysite.com

he should redirect to first page....

Have you been to /admin/settings/site-information and set the homepage from there? At the bottom put the node address into Default Front Page field, something like node/1 (or whatever node number you want the front page to be)


Create new menu with a module I want to create a new menu in Drupal 8 when I install my module. How can I achieve this?

I don't want to add a link to an existing menu, but create a new one.

You can either include the menu in your modules default configuration by adding a file to config/install folder of the module:

system.menu.menu-name.yml:

langcode: en
status: true
dependencies: {  }
id: menu-name
label: 'Menu label'
description: 'Menu description'
locked: false

You can also create the Menu entity, perhaps in the hook_install() hook.

use Drupal\system\Entity\Menu;

function MY_MODULE_install() {
  $menu = Menu::create([
    'id' => 'menu_id',
    'label' => 'Menu label',
  ])->save();
}


How do I override TwigEnvironment? I have been trying for a few hours to beautify the output that twig generates, such a way that will be properly indented with tabs.
For example, I would like the following output:

To become something like:
For example, I would like the following output:

I would like for this "autoindentation" to happen for all tags, because it makes the markup clean and easier to debug.
So I found this question: https://stackoverflow.com/questions/11878728/rendering-clean-tidy-html-with-twig-templates
And since I have been trying to make drupal load that twig indent extension and that twig lexer extension.

My code so far:

root.info.yml

name: Root
type: module
description: ‘Provides basic cosmetic functionality that should be in core.’
core: 8.x
version: 0.0.1

root.services.yml

services:
  # Override the default Twig Environment so we can add our custom Twig Lexer.
  twig:
    class: Drupal\root\TwigEnvironment
    arguments: ['@app.root', '@cache.default', '%twig_extension_hash%', '@state', '@twig.loader', '%twig.config%']
    tags:
      - { name: service_collector, tag: 'twig.extension', call: addExtension }
  root.twig.Indent:
    class: Drupal\root\Indent
    tags:
      - {name: twig.extension}
  root.twig.Lexer:
    class: Drupal\root\Lexer
    tags:
      - {name: twig.lexer}

and the Indent.php and Lexer.php as provided in that answer.
The problem is that the lexer wold not load because the tag twig.lexer does not exist.

So I tried to add the following code:

namespace Drupal\root;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Template\TwigEnvironment as CoreTwigEnvironment;
use Drupal\root\Indent;

/**
 * Twig environment that uses temporary file storage.
 */
class TwigEnvironment extends CoreTwigEnvironment {

  public function __construct($root, CacheBackendInterface $cache, $twig_extension_hash, StateInterface $state, \Twig_LoaderInterface $loader = NULL, $options = []) {
    parent::__construct($root, $cache, $twig_extension_hash, $state, $loader, $options);
    // Set our own lexer to the Twig environment.
    $this->setLexer(new Lexer($this));
  }

}

and drupal does not let me replace the Twig Environment and comes with the following complaint:

LogicException: Unable to register extension &quot;drupal_core&quot; as extensions have already been initialized. in Twig_Environment-&gt;addExtension() (line 941 of /var/www/konquer.technology/vendor/twig/twig/lib/Twig/Environment.php).
call_user_func_array(Array, Array) (Line: 322)

Is there a way to do this? I can't find any documentation on this topic.
Or maybe another way to achieve my goal of indented twig output

You're using an undefined twig.lexer tag there.

It looks as though you want that tag to work as a service_collector like twig.extension, but calling setLexer instead of addExtension.

For that, you probably need to add a line to your twig service definition, below the other tag:

- { name: service_collector, tag: 'twig.lexer', call: setLexer }

(Note: I don't know if this is actually good architecture. The service_collector tag is normally used when there can be multiple extensions, and multiple lexers would just replace each other. But it should work.)


Copy whole field from one entity to another i want to copy a field from one entity to another while processing a rule.
my current code looks like this:

<?php
    $entity_created->field_ort = $entity_fetched->field_ort;
?>

but instead i get an error message:

Notice: Trying to get property of non-object in eval() (Zeile 3 von /www/www/sites/all/modules/rules/modules/php.eval.inc(125) : eval()'d code).

so i found this site http://drupal.org/node/1000200 which tells me that i need to do this more like this:

<?php
    $entity_created->field_ort['und'][0]['value'] = $entity_fetched->field_ort['und'][0]['value'];
?>

but what about lists and other fields? is there a more generic approach? i need to copy about 5 or more fields.

That issue and the following code seems to have no bearing on the opening problem. Trying to get property of non-object, it literally means that $entity_fetched is not an object. Dump it into a file to see what it is.


How to place all form buttons on top of the page, before the form, in all forms? Since these forms can get quite big sometimes, especially with a lot of files attached and default preview for them.

Related, but not the same: How can I display a form button on top of the form?

You can do that using hook_form_alter() and setting the weight of $form['actions'] to a very small negative number.  Note that this applies only those buttons wrapped in $form['actions']. For other buttons that they aren't, you should add them manually.

function YOURMODULE_form_alter(&$form, &$form_state) {
  $form['actions']['#weight'] = -1000;
  // a button that is not wrapped in actions.
  // assuming it's id is 'submit'
  $form['submit']['#weight'] = -1000;
}


How to check when a user last updated password I would like to display a message to any user who has not changed their password since yesterday (4/21/14).

Does Drupal keep track of when the password was last updated? If so, how can I access that information?

Drupal out of the box does not keep track of password changes.  However, there are modules that do:

Drupal 7: The module Force Password Change keeps track of it. The data is in its schema ($schema['force_password_change_users']), in the field last_password_change (shown below):

'last_password_change' => array (
  'description' => t('A UNIX timestamp referring to the date that the user last changed their password'),
  'type' => 'int',
  'unsigned' => TRUE,
  'length' => 10,
  'default' => NULL,
),

Drupal 6: The module Password Expire keeps track of it. The data is in its schema ($schema['password_expire']), in the field timestamp (shown below):

'timestamp' => array(
  'type' => 'int',
   'not null' => 1,
   'unsigned' => TRUE,
   'default' => 0,
   'disp-width' => '11',
   'description' => 'Date user last updated password',
 ),

You could install one of these modules (depending upon what Drupal version you're using), and just query its table to extract this information as a UNIX timestamp from the field.

It would also be quite trivial to add this by means of a custom module:

You should be able to use hook_form_FORM_ID_alter (where FORM_ID is password_change) to intercept any password changes and record the timestamp for the event along with the uid in a table in the database.


How to extend a function I am new to Drupal. Learning Drupal 8. I am little aware of "hooks", but I am little confused.

For example, I have installed Rate module.

Now, I am trying to do more things based on user's action on RATE, whether vote up/down?

On each vote up/down, add some more details on Node and reward/penalise the node author.

I have tried doing: in my my_module.module file

function my_module_vote_rate_vote_alter($vote, $context) {
    drupal_set_message(t('called '), 'error');
}

But this does not display message.

I know this is third party extension.

But I am more interested in how to know, which alter/hook method I can use within the module/drupal.

I'm not seeing any hook named hook_vote_rate_vote_alter(), and the Drupal 8 version of the module is in development still. Your problem may be there.


Renaming a webform handler - old class stuck in DB despite clearing cache I'm creating a custom webform handler plugin based on the advice here, adding the class, in the correct directory, to an existing module.

I got the class name / some of the docblock info wrong initially - and need to change it.  Having run drush cr, the listing on  /admin/structure/webform/config/handlers seems to be stuck on the old entry.

I get "Cannot declare class ... because the name is already in use" errors when trying to add the handler to the form, for a class name that I'm no longer using, and which, having cleared the cache, definitely isn't in  cache_discovery.webform_handler_plugins in the DB.

I've also swapped browsers.

What am I missing?

Sometimes, especially with a local dev environment, after you have tried every other route the only other avenue is to restart the PHP service and/or reboot the server/VM. This should clear system caches and often times will resolve this issue.


CSS/jQuery not showing in Drupal 7 when upgraded from 6 I have just recently upgraded a large site from Drupal 6 to Drupal 7. When I load up the site it doesn't load any theme at all. Even when I check the admin panel under appearance it  shows the enabled themes, but nothing shows up at all, style wise. When I view the source, it isn't pulling in any CSS or jQuery files at all. Does anyone know how I would go about fixing this?

Also, I am receiving this error 'The specified file temporary://fileoR4rjt could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.'

I thought it may have something to do with the tmp folder/file-system but I can't seem to get anything to work.

Any help would be great. Cheers.

Theming system as a little bit changed on Drupal 7. You should give a look at that page for more informations.

For your file-system problem, you should check the configuration of File system and see where is trying to put the files from the temporary folder.

By default Drupal tries to put that into sites/default/files, so check if the rights of this folder as write/execute/read for the owner and the groupe and if the group is at least the web server.

Also, maybe this problem with file-system can likely fixe your CSS/jQuery problem. So try to fix it before read the documentation from the new theming changes on Drupal 7.


How can I quickly re-save all users on my site? Very similar to this question except I need to save users, not nodes.

Use case: I added a field (single boolean) to a feature so that the field is added to user profiles.  I then pushed the feature to my staging server.  However, existing user accounts do not have the default field value for this field assigned.  Re-saving each account fixes the problem, but there are 1000 users.

How can I quickly re-save all users on my site?

You can use the "Execute arbitrary PHP script" bulk operation in VBO and when you run it enter:

user_save($entity);

You could also run this PHP (you can do so by enabling the devel module and going to devel/php on your site):

set_time_limit(0);
$uids = db_query('SELECT uid FROM {users} WHERE uid != 0')->fetchCol();
$users = user_load_multiple($uids);
foreach ($users as $user) {
  user_save($user);
}

If you don't have many users you shouldn't need the time limit line.

Also, Clive mentions that field_attach_update is faster. To use that replace the user_save line with field_attach_update('user', $user)


Image style results in wrong image I had a very odd error where the image showed as style'ed but was using the wrong source image. When I deleted the style'ed image and reloaded the page, the correct image displayed and was style'ed.

I haven't figured out how to reproduce the error, but I am positive the source image didn't change.

This was likely a file-naming conflict of sorts. ImageCache (the module responsible for generating the image styles) generates a file name for each image style, and then checks for the presence of that file. If the file exists, it is served to the browser, otherwise it is generated and then served.

If you had a file called fruit.jpg that resulted in an image style of /files/styles/some/folder/fruit.jpg, and then deleted the source file, it is possible that the derivative style file wasn't removed (keep in mind, this a theory). If you then uploaded a different image with the same fruit.jpg filename and tried to generate the same image style again, ImageCache would find the previous /files/styles/somes/folder/fruit.jpg and serve that, resulting in the confusion you're seeing.

That said, I do believe derivative image styles get deleted when the source image is deleted, but I'm not sure of the specifics (ex. timing - it may happen during a cron run which wasn't ran).

For the most part, I wouldn't worry about it. Sounds like a onece in a million edge-case.


How to restrict access to view node revisions with Organic Groups Does organic groups restrict access to node revisions as well as the nodes themselves?

I have a node page with a view of the revisions output in a block in the sidebar. OG restricts access to the node itself if the user doesn't belong to that node's group however they can see the revisions in the block.

I have tried creating my own OG permission but the organic groups permissions aren't usable in the view restriction. Not sure what else to try?

Rather than worrying about access to the revisions themselves, you might be able to add relationship to the node itself and then a filter to check it the node is accessible.

I imagine there's a better way to do it, but this might work in the mean time.


Trying to list all articles where category field is empty I have drupal 7 site and I'm trying to listing all articles (with title) and where category field is empty (taxonomy). I'm running this code in my page with ->isNull and without, but not any results. Can someone explain what I'm doing wrong in here and why this is not working?

$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('n.type', 'article')
  ->condition('n.status', 1)
  ->isNull('n.field_tags')
  ->range(0, 10);

  $results = $query->execute();

I'm get this error all the time:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'n.field_tags' in 'where clause': SELECT n.nid AS nid FROM {node} n
  WHERE (n.type = :db_condition_placeholder_0) AND (n.status =
  :db_condition_placeholder_1) AND (n.field_tags IS NULL ) LIMIT 10
  OFFSET 0; Array ( [:db_condition_placeholder_0] => article
  [:db_condition_placeholder_1] => 1 ) in eval() (line 17 of
  /sites/site.com/modules/php/php.module(80) : eval()'d code).

It seems to me your mistake is you are requesting the column field_tags from the table node, which is not a column from node, so doesn't exist.
Unless you have a very specific database structure, your "field_tags" should be contained in the table field_data_field_tags, so you may have to make an INNER JOIN between these tables in your query (maybe using field_data_field_tags.entity_id = n.id), and then check if the n.id exists in field_data_field_tags.entity_id, or (maybe better) use a LEFT JOIN between field_data_field_tags and node, so only the node with a n.id existing in field_data_field_tags will be returned.


Drupal 8.5 REST 406 Not Acceptable I had a REST resource for a custom entity working in 8.3, but when I try hitting it in 8.5, I get a 406 with message": "Not acceptable format: json" in the body.

Here's my config, with json clearly defined as the format:

langcode: en
status: true
dependencies:
  module:
    - basic_auth
    - MY_MODULE
    - serialization
id: entity.MY_ENTITY
plugin_id: 'entity:MY_ENTITY'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

I've tried stepping through code with Xdebug in PHPStorm, but not having much luck seeing where this is coming from.

You have to add this on the end of your endpoint URL:

?_format=FORMAT. So if you want JSON, its ?_format=json.

This is a new change in 8.5.0 requiring this argument, but I could not locate in the changelogs exactly why it is now required otherwise a 406 is returned.

This same thing happened to all my REST endpoints until I added that.


In an Aegir platform how do I change what modules drush enables when a site is created So far I have successfully in setting up Aegir and seting up a number of Platforms using makefiles. Now I want to tinker with one of the platform by adding a number of modules and tweaking some template files.
I realize making these changes within the platform folder will propagate to all of the sites within that platform. What I want to know is, what do I have to change, so that when I provision a new site the new modules that I have added will automatically enabled? Does this have something to do with drushrc.php? it seems there are two, one in the platform and one in the site. I'm also wondering how to get Aegir to set certain values, like auto populating users.

Both requirements (auto enable modules and autopopulating users) can be done by Drupal install profiles or distributions. Install profiles are in Drupal, not in Aegir, but fits perfectly to Aegir.

In short, I recommend you to compile your install profile and use this profile in Aegir.

See more: http://drupal.org/project/distributions


How to hide the unflag link text once the flag is set? I have a node flag abuse and I want to remove/hide unflag link text "non-abuse" once the abuse flag is set.

How to do this in Drupal? Since I am new to Drupal, I can't think of a  solution for this.

Note: I'm using this inside the Panels module.

In Drupal 7 you can use The Flag API (JavaScript) for this

  The flagGlobalAfterLinkUpdate event : This event is triggered immediately after a flag link has been updated. (Flag links appear in
  two flavors: "Bookmark this!" and "Unbookmark this!", and when we
  speak of "update" we mean this change in appearance).

    (function ($) {
        $(document).bind('flagGlobalAfterLinkUpdate', function(event, data) {
            if (data.flagName == 'yourFlagName' && data.flagStatus == 'flagged') { //dont forget to add your flag name
                var flgName = '.flag-'+data.flagName;
                $(flgName).hide('slow');
            }
        });
    })(jQuery);


How to programmatically hide field from display? I want to reproduce programmatically hiding of a field that can be obtain by Manage Display -> Format -> (hidden)

URL: admin/config/people/accounts/fields.

Field I want to hide is added by OG module. Probably. Machine name: og_user_user.

I found one solution based on hook_field_access but I need to find other.

This solution doesn't help me too.

Solution is pretty damn simple. I forgot about field_update_instance function.

To get data for passing to this function there is a need of debug: field_ui_display_overview_form_submit

where all Manage Display forms are submitted.

I end up using custom drush command after all custom modules are installed


How can i get prepared for DRUPAL-PSA-2016-001? The PSA for tomorrow left me a bit uncomfortable. Quote:

  The Drupal Security Team urges you to reserve time for module updates
  at that time because exploits are expected to be developed within
  hours/days.

Does it make sense to put all sites in maintenance mode or take them offline precautionary?
Maybe creating database backups before the announcement takes place isn't a bad idea?

Is there a Drupal way of responding such a pending threat? Or should we just sit and wait what's coming?

1) List all the Drupal 7 projects you maintain.
2) Have a list of used modules by project, you can use fllowing command

 drush pml --no-core --type=module --status=enabled > mylist.txt

3) Once the updates announced, you can search your modules lists to detect which project you really need to update


Drupal 7 : How to break title of content into multiple lines Most of the content-nodes on my site have two parts (English | Arabic). I want to put a line break between the two, so that the broken text does not look awkward. But when I put an html line-break tag, the tag itself shows up in the title.

What to do?

Appreciated...

As I understand you want have your nodes titled using pattern <English name><Arabic name>, and split your title on 'language border' to different lines. As was mentioned node title is used in both places content title, and page title.

So you can use changed pattern <English name>|<Arabic name> and override your template file in your theme. You can use str_replace before displaying title for your node. Also your page title will look ok, without changing theme more; and this solution support titles without | delimiter, or with more then 1.


What would be the correct way of adding a link to existing path into admin menu? What is the correct way to add a link to a menu? I am using Drupal 7 and admin menu module. I would like to add a link to the content menu item so it would be
Content

  Content
  Add Content
  Comments

I created a custom module and in the menu hook I put:

$items['admin/content/add'] = null;

Then in the menu_alter hook I put:

$items['admin/content/add'] = $items['node/add'];

Now the menu link appears where I want and when I click browser takes me to the admin/content/add but instead of showing the different options for creating node there's a text saying:
You have not created any content types yet. Go to the content type creation page to add a new content type.

If I go to node/add I can see the different options to add different nodes.

So my approach seems to be wrong. What would be the correct way of adding a link to existing path into admin menu?

I think the easiest way to do this would be to create a fully fledged menu item and simply forward it on to the node/add page using drupal_goto() as the page callback:

function MYMODULE_menu() {
  $items['admin/content/add'] = array(
    'title' => 'Add Content',
    'access arguments' => array('administer nodes'),
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/add'),
    'weight' => 10 // Use this property to control where in the menu the item will appear.
  );
  return $items;
}


A module to limit number of posts a user can make during a set period of time? I have a number of sites that allows users to post nodes and comments, however bots are getting a hold of these and having their way with my site. I recall seeing a module a while back (but cannot remember it's name) that allows admins to set a time limit between posts. Basically denying posts that made within minutes or seconds of eachother. Any ideas?

Maybe Node limit module can help? I haven't used it but it seems that this may be what you need.


using $_POST values in form alter to add validation it's not the first time that i get into trouble using $_post in a node form alter, this time i'd like some assistance.

basically, i need to pass some parameters to a form (and i should not pass the appended to the url, as query parameters). but $_POST values don't work as expected (they work until reaching validation phase).

So.. in a page i pass as hidden value

<form method="post" action="/node/add/">
    <input type="hidden" name="mydesideredParameter" value="itsValue">
</form>

In the form_alter function of this form, at the very beginning, i try to assign this value to $form_state (and it works, I watchdog it later and it's correct)

if (array_key_exists('mydesideredParameter', $_POST)) {
    $form_state['mydesiredConsequence'] = 'dance';
}

Later, inside form_alter, at the very end, i state:

if ($form_state['mydesiredConsequence'] === 'dance'){
    $form['#validate'][] = 'myDancingFunction';
};

No complains happen on form building, but when trying to submit the form, the validation funcion doesn't get called and php complains about index that doesn't exist no more

Notice: Undefined index mydesiredConsequence

Nothing similar happens when i use this step and the values are in the url(via drupal_query_parameters) , but trying to make this work in $_POST seems a bit awkward. (i obviusly can imagine that the second form-rebuilding ignores $_POST, as it was a former request; but that should be the intended purpose of assigning the value to $form_state).

You should use $form_state['storage']. This will cache your data and make it available throughout the forms lifecycle.


entity reference and exposed filter Hello I would like to ask about views and exposed reference filters. I have problem with displaying my custom view for exposed filter. Can you please help?

Its kind of complex so I will try to describe the structure. I made view which should be used as exposed filter and this view works fine, but cant push it to appear in other view as exposed filter.
All of my users have some cateogies as taxonomy terms. Also every content has this category so I want to show to user only the content which is in category assigned to specific user. There can be more than one category assigned to user. Content has also single value entity reference to manufacturer.
And now I need to have a page for every content type where and I want to display all content in users category with exposed filter of manufacturers. In this filter must not be all manufacturers but only which ,there is content created with this manufacturer and the content is assigned to same category as the user.

Little example for one content type:

  user1 - category: dj, profi video
  user2 - category: hifi
  user3 - category: dj, hifi

  content1 - manufacturer: m1; category: dj, hifi
  content2 - manufacturer: m2; category:dj
  content3 - manufacturer: m2; category: profi video
  content4 - manufacturer: m3; category: hifi

In this point the exposed filter for user1 should display: m1, m2. Or for user2: m3. Or for user3: m1, m2, m3.

You need to set up relationships between the three content types in your View. Essentially, you have to set up relationship user->category, then relationship category->manufacturer, at which point the manufacturer fields will become available in the exposed filters section. There is a great tutorial here how to do this.


Views Long query execution time serious problem I got some serious issue with the views performance. I am just fetching 9 items using the Tagadelic list with 3 filters and 3 sorting criteria. It says query build long query execute time like 46147.48 m, Which is really frustrating.

Query build by view is as below:

Can you please help??

There is no one line answer for you question as there are multiple things that can affect a query running slowly.

What you should do is enable slow query log in MySQL and try to debug from that point why your query is taking so long to execute. Things you can do are,

Tune your MYSQL.
Turn on slow query log.
Use the Explain command to find more info on how your query is executing, http://dev.mysql.com/doc/refman/5.7/en/using-explain.html.
Watch out if the tables are correctly indexed.
Last but not least, you can use hook_views_query_alter if you feel views is not creating the query optimally.


How to debug #states mecanism - trying to get #states to work with inner fieldsets & webform I have a relatively simple webform, with 2 fieldsets and a few other fields. The fields aformentionned have #states  actions configured and behaving proper like in a regular form.

It is in the fieldset shown below I have a problem.
THe fieldset should be collapsed (via #states) and there is nothing I can do to make it so.

The offending fieldset has #states defined in the bottom form_alter, I outlined the error location in caps:

// Implements hook_form_alter()
function formHelper_form_alter(&$form, $form_state, $form_id)  {
switch ($form_id)  {

        case 'webform_client_form_1':

           // Set fieldsets as collapsible
          $form['submitted']['inscription']['#collapsible'] = true;
          $form['submitted']['inscription']['#collapsed'] = true;

          $form['submitted']['inscription']['enfant_1']['#collapsible'] = true;
          $form['submitted']['inscription']['enfant_1']['#collapsed'] = false;

          $form['submitted']['inscription']['enfant_2']['#collapsible'] = true;
          $form['submitted']['inscription']['enfant_2']['#collapsed'] = true;

            //vardump of fieldset
           dpm($form['submitted']);

           // Show datepicker for child one if inscription is part time
           $form['submitted']['inscription']['enfant_1']['jrs_semaine']['#states'] = array(
              'visible' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_1][horaire]"]' =>
                  array('value' => 't_partiel'),
              ),
           );
           // Show datepicker for child two if inscription is part time
           $form['submitted']['inscription']['enfant_2']['jrs_semaine2']['#states'] = array(
              'visible' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_2][horaire_2]"]' =>
                  array('value' => 't_partiel'),
              ),
           );
            // THIS IS THE FIELDSETY THST DOES NOT WORK:
           // set state on second fieldset to be visible only when two is seiected.
           $form['submitted']['inscription']['enfant_2']['#states'] = array(
              'expand' => array(   // action to take.
                ':input[name="submitted[inscription][enfant_1][horaire]"]' =>
               array('value' => 't_partiel'),
              ),
           );
          break;
 }
}

Now, in the drupal docs (example module) there is a fieldset shown  with working code using  as the state to change, and it seems in the docs fieldsets are clearly supported, alas not the one in my webform.

I am using the same condition that is working on the other field so I assume the problem is not with the selector. In light of this fact, I have no clue of what even to really look for but I really want to figure it out.

Is anyone familiar enough with #states to tell me how I could debug the js in this case?

I know it is in /misc/states.js, I just don't know what to look for in states.js, or even if this is what is preventing the fieldset from collapsing.

update: Reposted the full hook_form_alter function as per request.

Can you add the full code for both form items?

If the element needs to be collapsed at start-up you need to add '#collapsed' => TRUE,

It also looks like there's an error in you're selector as pointed out in comments


Add target blank to an image link How do I add target='blank' to a href in a Drupal 8 custom module? Below I have the image being wrapped by the uri. I don't know how to add target='blank'

  $element[$delta] = array(
        '#theme' => 'image_formatter',
        '#item' => $item,
        '#image_style' => '',
        '#url' => $uri,
      );

I think (not checked) that you need to add "target" => "_blank"  ((note underscore)) to the #attributes array. However, that attribute must appear on an  element that encloses the , not the  itself, and I'm not sure if adding it to the structure in your question would do that... have a go.

If it doesn't work, simplest option is to override the twig template in question and then extend attributes with "attributes.setAttribute('target', '_blank')" in the appropriate place.

Determine the right file name to override the twig template with by using twig debug (look in the sites/default/local.services.yml for the setting to change).
, and then view-source of the page (noting there are now lots and lots of html comments), find the existing image html and look before it to see the table of possible templates. There is lots more about this in the official Drupal documentation on twig.


why does drush tag 8.0.0-beta14 returns all zero for config core.extensions After a fresh install of d8 with several core modules activated (block, breakpoint, database logging, field, filter, internal page cache, node, system, toolbar, update manager, user, views, views ui), extracting the config indicates that all the above are off:

# drush8 @myproject.dev config-get core.extension
module:
  block: 0
  breakpoint: 0
  config: 0
  datetime: 0
  dblog: 0
  entity_reference: 0
  field: 0
  file: 0
  filter: 0
  image: 0
  node: 0
  page_cache: 0
  system: 0
  text: 0
  toolbar: 0
  update: 0
  user: 0
  views: 0
  views_ui: 0
  minimal: 1000
theme:
  stark: 0
  classy: 0
  seven: 0

stark is, in fact, the default activated theme and seven is the admin theme.

The plan is to dump the config from the dev server and then import it into the stage server; but this is tricky if the config dump from dev is "blank."

Is this what's supposed to happen?

I'm using drupal version 8.0.0-beta12, and drush version 8.0.0-beta14.

The numeric values in core.extension are the module weight; if a module is disabled, then it does not appear in the list at all.


Use node title as page title in views full node page display I'm using views to link a menu-item to the last node added of a certain content-type.

To accomplish this, I've set up a view to display a 1 full node sorted by post date.

this all works just fine, but now I want to use the node title as page title () instead of the view page title. I also don't want the node title to link to the node again.

Does anyone know how I can do this?

Thx in advance.

I finally managed to pull this off by writing a small module using following code:

function MYMODULE_preprocess_views_view(&$vars) {
  // Get my view
  if ($vars['view']->name == 'MY_VIEW_NAME') {
    //get the title of the node shown in the view
    $nid = $vars['view']->result[0]->nid;
    $node = node_load($nid);
    $my_title = $node->title;

    /* Code to dynamically set title here...
       Override view's title since drupal_set_title() is not working.*/
    $vars['view']->build_info['title'] = $my_title;
  }
}

This module changes te views page title and uses the nodes title as page title instead.

Now you can remove the linked nodetitle in the node--YOURTYPE.tpl.php


Index View donot show 'Contains' operator for (exposed) filter I have created an indexed view, for facet search.
Now I want to put a text field from which search provides a result, that contains that string from the title.

Now, title here donot have operator, 'Contains' which is required to filter matching titles.

I am using Global Populate filter as exposed filter.
I tried using hook_views_query_alter which donot work with index view of search api.
How should we do this?

I used hook_search_api_views_query_alter from search_api_views.api.php.

function MYMODULE_search_api_views_query_alter(&$view, &$query) {
  // Altering the title filter to operator LIKE which is not available in the
  // views itself.
  if ($view->name = '[VIEWNAME]') {
    if (!empty($query->where[1]['conditions'][0][1])) {
      $query->where[1]['conditions'][0][1] = '%' . $query->where[1]['conditions'][0][1] . '%';
      $query->where[1]['conditions'][0][2] = 'LIKE';
    }
  }
}


Bulk create Nodes from SQL I have an ASP.NET website using MySQL.
1 table('books') holds more than 1000 books, each record has unique ID, name, writer etc.
I want to import those books into Drupal. I'm planning to create Custom Fields(name, writer etc) for a New Content Type.

Is it possible to create Nodes like this from SQL file?

Possible, yes.  Recommended, no.  I do a lot of importing from outside sources, and would never entertain using direct SQL INSERT statements.

I would export your existing database in another format, and pursue one of standard approaches.

The easiest is probably Feeds.  In your case, I would export as CSV, and then use the CVS imported built into feeds.  Based on your description, it sounds like you have a one-to-one mapping, and the CSV importer is good for this.

The Migrate module can also handle moving data from one source into Drupal.

A more robust solution would be to create a custom importer, build up a $node, and then use node_save.  There are a lot of nuances with this, and this is not a good approach unless you are familiar with the Drupal API already.


Is there any way to take a preexisting field with content, and generate taxonomy from it? I have a content type called 'classes' in the content type is a text field called 'instructor'. I also have a separate content type called 'instructor profile'. The two content types 'classes' and 'instructor profile' are not tied to together in anyway unfortunately (not setup by me).

I would like to tag the existing 'instructor profile' content type with their 'classes'. So for example, if you are looking at the instructor profile, you can see what classes he/she teaches. The easiest way to do this would be take the existing 'instructor' text field under 'classes' and generate the vocabulary so I can match those up with "instructor profile' under a view later on by tagging the Instructor's profile with the right vocabulary.

However, I can't seem to find a module that will take an preexisting field and generate terms from it (or convert that field into a free-tagging taxonomy term). Any idea?

It sounds like a job for an entity reference field

For example, add a "field_classes" entityreference field to "Instructor profile" referencing the class nodes that instructor teaches.

Alternatively, add a "field_instructor" entityreference field to the "Classes" content type, referencing the instructor profile(s) for that class.

Using Entity Reference, each content type can easily list the related instructors and classes.


Is there an alternative to themegarden.org - one that has Drupal 7 themes? I like themegarden.org and I think it'll be a useful tool to help me explain to clients and colleagues how content and presentation can and should be separated. It looks like Theme Garden only caters for Drupal 4.7, 5 and 6. Does anyone know of a D7-compatible site where I can browse themes as easily?

I haven't come across a really good site for Drupal 7 themes. Here are some sites that might be helpful:

http://www.leveltendesign.com/blog/colin/10-free-drupal-themes-7x
http://omega.developmentgeeks.com/
http://www.themesnap.com/drupal-themes.html (paid)
http://adaptivethemes.com/drupal-themes/all (paid)


Execute a view in code and pass multiple arguments to an exposed filter? I am executing a View in code of a paragraph preprocess to allow dynamic listings. The user selects which content types they would like to show, and the View should return nodes of those types with the same taxonomy selected. The idea is they can add multiple paragraphs with different configuration, leveraging the same View just with different arguments.

In this view, Content Type is an exposed filter, set to allow multiple. Here is the code in the preprocess_paragraph hook:

$types = $paragraph->field_related_content_types->getValue();
$content_types = [];

foreach ($types as $type) {
  $content_types[] = $type['target_id'];
}

$view = Views::getView('related_content');
$view->setDisplay('related_content_display');
$view->setArguments(['type' => $content_types]);
$view->setExposedInput(['type' => $content_types]);
$view->preExecute();
$view->execute();

if (count($view->result)) {
  $variables['results'] = $view->buildRenderable('related_content_display', ['type' => $content_types]);
}

'type' is the filter name in the View. If I change it to only allow one value and pass it as a string, it works. So it seems like a syntax issue, but I cannot figure it out.

The method seems to indicate that this is possible:

  /**
   * Sets the arguments for the view.
   *
   * @param array $args
   *   The arguments passed to the view.
   */
  public function setArguments(array $args) {
    // The array keys of the arguments will be incorrect if set by
    // views_embed_view() or \Drupal\views\ViewExecutable:preview().
    $this->args = array_values($args);
  }

It looks like you're you doing an exposed filter and contextual filter for the type. As setArguments is for contextual filters and setExposedInput for exposed filters. If you've only got the exposed filter for type you should be able to remove setArguments and the 2nd argument on buildRenderable (which you dont need if you're doing setArguments)

I've got something very similar with an exposed type filter and just pass it an array to setExposedInput  and it seems to works

$view->setExposedInput(['type' => ['news','page']]);


How to pass default values on node form through form_alter when using confirm_form? My confirm form should consists part of node form but with disabled fields. I mean after I submit node form I rebuild it and append confirm form in hook_form_alter()(Before it I change submit callback and set 'reduild' flag in form_state in it).

But this form not containing filled values. I guess this is because I make rebuild but as I know there is no other way to display confirm form.
So the question is how to do it? How to fill values filled on previous step?

First phase submit callback:

function mymodule_content_confirm_form_submit($form, &$form_state) {
  $form_state['storage']['confirm'] = 'save';
  $form_state['storage']['values'] = $form_state['values'];
  $form_state['rebuild'] = TRUE;
  return;
}

Form alter the part where confirm form appends:

  $show_confirm_form = isset($form_state['storage']['confirm']);
  if ($show_confirm_form) {
    // We need this form for panels and we can't remove it so we just hide.
    foreach (element_children($form) as $id) {
      $element = &$form[$id];
      if (!empty($element['#type']) && in_array($element['#type'], array('hidden', 'value'))) {
        continue;
      }
      $element['#disabled'] = TRUE;
    }
    $message = t('Are you sure you want to save all these changes?');

    $form = confirm_form($form, t('Levels & Content'), current_path(), $message, t('Confirm'), t('Cancel'));
    $form['actions']['cancel']['#href'] = current_path();
    $form['actions']['cancel']['#attributes']['class'][] = 'button';
    $form['actions']['cancel']['#options']['path'] = current_path();
    $form['actions']['cancel']['#options']['query'] = $destination;

    $form['actions']['submit']['#submit'] = array('mobitek_custom_content_node_form_insert_values_submit', 'node_form_submit');
    return;
  }

This is my dirty solution of the problem, I use $form_state['complte form'] instead $form:

$refill_fields = array(
  'form_build_id',
  'form_id',
  'form_token',
  '#id',
  '#token',
  '#build_id',
);
foreach ($refill_fields as $refill_field) {
  $form_state['complete form'][$refill_field] = $form[$refill_field];
}


How can I prevent user data being cached and showing the wrong username? I have built a Drupal 8 site, we are showing the user name and last name on a block, this is my code on preprocess from .theme file:

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

$firstname = $user->get('field_firstname')->value;

$firstname = $firstname;
$variables['firstname'] = $firstname;

Then in the block im doing: Hello {{ firstname }}

And it shows the last user, not mine. When I do drush cr then I get the correct name, why? How can I fix this and already display the right username?

You are retrieving the user name from the current context and the user entity, but then you make it a dumb string value to pass it to the template. Include the cache metadata to define where this value is coming from and under which circumstances it could change:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$firstname = $user->get('field_firstname')->value;

$variables['firstname'] = [
  '#plain_text' => $firstname,
  '#cache' => [
    'contexts' => ['user'],
    'tags' => $user->getCacheTags(),
  ],
];

More info https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays


how to prepopulate a flexifield in form_alter? I have a flexifield with name:

field_flexi_pricing[0][value][field_pricing_day_price][0][value]

how do i fill in a default value for this flexifield in form_alter?

do a form alter and add your value as a default value using the default value key,

http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/5#textfield

'#default_value' => //my value;

you can always print $form in your form_alter after you have altered your $form, to have a better look at your flexifield array, and chck if the default value is set like it is shown in the forms api reference link above. :)