How to get the list of all entity reference fields and their params? I'm trying to build a new widget for the entity reference module.
(nested checkboxes = tree according to entity references between nodes)

The only answer I'm looking for is :
"How to get the list of all entity reference fields and their params? (child and parent node)

Thank you for your help!

Ludovic

Edit : working on D7

Here is my custom function that gets id's of all files referenced entities and their parents. Also get's all field names, entity types and bundles of entityreference fields.

function _my_module_get_entityreferences_settings() {
  $child_ids = $field_names = $settings = array();

  // Get all entityreference field names
  $query = db_select('field_config', 'f');
  $query->fields('f', array('field_name'));
  $query->condition('f.type', 'entityreference');
  $query->distinct();
  $rows = $query->execute();

  foreach ($rows as $row) {
    $field_name = $row->field_name;
    $field_names[] = $field_name;
  }

  // Loop all entityreference fields. Get all child and parent Ids
  foreach ($field_names as $field_name) {
    $table = 'field_data_' . $field_name;
    $target_id = $field_name . '_target_id';

    $query = db_select($table, 'f');
    $query->fields('f', array('entity_id', $target_id, 'entity_type', 'bundle'));
    $query->distinct();
    $rows = $query->execute();

    foreach ($rows as $row) {
      $settings[$row->entity_type][$row->bundle][$field_name] = $field_name;
      $child_ids[$row->{$target_id}] = array(
        'id' => $row->{$target_id},
        'parent' => $row->entity_id,
      );
    }
  }

  return array(
    'childs' => $child_ids,
    'settings' => $settings,
  );
}

Maybe you don't need all this stuff. When you get $field_names array you can use

$field = field_info_field($field_name);

to get settings of current field. You can find here referenced bundles, field type, handler_settings etc.


Dynamic field title D7 Basically I want to be able to have a user be able to specify a title for a long text and summary field. Functionality being that you could have this with only one field:

day 1: doing something
this is what we did on day 1

day 2: doing something on day 2
this is what we did on day 2

Basically I want one field input for my content type creation form that correlates a title and the paragraph to go with it. I thought of a shoddy way to do it by creating a separate content type and bringing in the copy with a views block but I feel like there should be a much simpler way to allow a user to input a title to attach to a long text and summary field.

Not sure, but this sounds like it could be a job for the Field Collection module.


Get the field type of FieldItemList I need to find all FieldItemList's with a certain field type.

/* @var FieldItemList $field */
foreach ($p->getFields(FALSE) as $field_name =>  $field){
  kint($field->getPluginId()); //NOPE
  kint($field->getFieldDefinition()); //NOPE
  kint($field->equals(array('MY_FIELD_TYPE'))); //NOPE
}

I would expect there is a simple way of finding out the field type of a FieldItemList.

its this one:

$field->getFieldDefinition()->getType()


Gallery that can be added to a node via node edit page? I want to have a gallery that I can easily add/edit/delete photos of from a node creation page and if a user adds a gallery it adds it to the node.

So let's say I want to have a gallery on a page, I would add all the title, body, then I would add 3 photos. And that would create a node with a title, body, and a image gallery with 3 photos. Similar to what I can do in wordpress for each page.

Or something that would function similar to what I want.

Any ideas?

I usually use Galleria module to do so:
https://drupal.org/project/galleria

Turns image fields of nodes into Galleria galleries with this JavaScript (JQuery) image gallery.


Should I add a div class to a fields TPL file or just change my CSS file? I am starting to understand how to edit the CSS of individual views on my site. I use the Views module (release 2). I know Views 3 makes life easier in these things but for now I have to use Views 2.

I have a comment block on my site. I wondering if it is best/easier to add some kind of div class to a fields TPL file or wether I could just change it in my CSS file. I seem to have tried both in my time with various success. I really struggle to find out what part of the div class I need to change in a view when viewing it with Firebug.

This for instance:

  view view-comments-recent view-id-comments_recent view-display-id-block view-dom-id-5

Would I make the css something like

  .view-comments-recent view-id-comments_recent view-display-id-block view-dom-id-5 body {
        font-family:Arial, Helvetica, sans-serif;
        font-size:12px;
        line-height:16px;
      }

to change the text in the comment field?

I feel it might be better to create a views-view-field--comments-recent--block--comment.tpl.php file and then do something like this:

 <div class="mynewclass"><the print output bit> </div>

And then add this:

.mynewclass body {
font-family:Arial, Helvetica, sans-serif;
  font-size:12px;
  line-height:16px;
}

Or maye that would be like so:

.mynewclass p {
font-family:Arial, Helvetica, sans-serif;
  font-size:12px;
  line-height:16px;
}

Could anyone help me with what I am trying to do? I feel like I almost have it.

Which way would be best do you think?

You should be able to set a custom css class for each field, but otherwise your technique of drilling down using css classes is fairly common practice.


Facebook like box as popup I have the facebook like box in a block position and i want to make this block popup for first time visitors only. The popup will open only if the user visits the website for first time and will open once for every visitor.

Is it possible to implement this feature with existing modules? I am not a programmer.

Thank you

From Comments:

If you want to do a popup for first time visitors, try the Popup announcements or Popup on load modules.


String Manipulations in Drupal I've been retrieving information from  a database for display.

function myid_user_page_form(){
    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query->fields('t1', array('firstname','middlename'));

    foreach ($result as $record) {
        $info['firstname'] = $record->firstname;
        $info['middlename'] = $record->middlename;
    }
}

In my case, all data stored in my database is all uppercase. For example:

$info['firstname'] = "ALYSSA"
$info['middlename'] = "ENGANIO"

I want to make "ALYSSA" to "Alyssa" and make "ENGANIO" to "E.". How will I do that in Drupal?

Drupal can help you doing this by its unicode functions.

https://api.drupal.org/api/drupal/includes%21unicode.inc/7

"ALYSSA" to "Alyssa" would be

<?php
  $name = drupal_ucfirst(drupal_strtolower($name));
?>

And "ENGANIO" to "E." would be:

<?php
  $name = drupal_strtoupper(drupal_substr($name, 0, 1)) . '.';
?>


What methods are there to load more ROWS into a View display without reloading the page? I have a basic View showing 2 node teasers at a time. I want to be able to have a button below it that says load more. Once you click it, it will load the next two. I know that there is the module "views_load_more", but there seems to be a bug with that module that causes duplicates. There is a patch for this issue, but it doesn't solve the problem from what i have tried.

I was wondering what other modules or methods to achieve this same functionality?

I was thinking of continuing to use the views load more module, and just use jquery to detect if there are duplicates and then remove them. But that way seems to be a bit hacky.

The Views Infinite Scroll module is an alternative solution for ajax pagers in views however I haven't used it so I cannot comment on how well it works.

It also works a little differently to views load more so it may or may not meed your requirements.


Is Git now the only way to install Drush? Going in circles trying to figure out the right way to install Drush on a Linux CentOS system.  I have Git set up, but as I'm not planning to contribute to Drush code at the moment, it's not unambiguously clear that I should be using Git.

Some directions say to use PEAR, but when I go to the Drush project page, the directions say to get Drush 6 from Git.  Tutorials I have found demo wget and PEAR, not Git.  And the Git project page View says, "Use our Github project for contributing code, or reporting bugs, or requesting features," none of which applies.

Could an experienced Drupalista please answer the following?

Is Git now the only method of obtaining Drush?  Someone asked a
similar question more than a year ago when PEAR was still
recommended.
If Git is the way to go, I have read that drush should not be installed within the website directories, so which directory is it recommended to be in when I invoke the following?

git clone --branch 7.x-5.x http://git.drupal.org/project/drush.git

I'm looking forward to using Drush.  Thanks!

Drush moved to GitHub a few weeks ago.  The official home is now: https://github.com/drush-ops/drush

The current preferred method is to install with composer:

composer global require drush/drush:6.*

If you are working with Drupal 8, or need a patch that hasn't been backported, then you can work with the latest version:

composer global require drush/drush:dev-master

You can also use composer to install a particular version.

You can install it manually; and normal GitHub retrievals apply.  You can download the master (link is on the main page), or clone the repo locally.  When you clone locally, you can checkout any tag you want.

I have it installed in my home directory, eg

cd ~
git clone https://github.com/drush-ops/drush.git drush

After, you need to run composer

cd ~/drush
composer install

I then put ~/drush/ in my $PATH:

export PS1=$PATH:~/drush/

Everything should work as normal.

Sidenote.  Even if you don't want to contribute back, tracking your whole site with git is a great way to handle dev/live, and for backing out oopsies.


Load nodes by property, including empty ones I want to render a node with certain properties set. For example, I want to load every node which ONLY has field_a and the other fields are empty.
If I use
$this->nodeStorage->loadByProperties(['type' => 'node_type', 'field_a' => $value]);

-> this will load every node which has field_a, but the other fields are not necessarily empty. I tried setting all the other fields to null, but it throws an InvalidQueryException. How can I change that query to IS NULL or which function can I use?

loadByProperties() executes an entity query with ->condition() for each property. You can't use this for empty fields, you need
$query->notExists('field_example');

according to How get empty record on date field with entityQuery?


Can I have more than one child content type for a book content type? I have two content type I selected as book content type: Text_book_type and audio_book_type.

Now, I need that these content have different child content type:

chapter_type for text_book_type and audio_chapter_type for audio_book_type.

Is there a way in Drupal 8 to achieve this?

Yes you can create two different Content types for your chapter nodes, just like you have different Content types for your book nodes.

The "Parent-Child" relationship you describe is usually accomplished with Entity references.

Add Entity reference fields to your chapter_type and audio_chapter-type and configure them to reference text_book_type and audio_book_type nodes respectively.

Then when creating a chapter node you'll be able to choose which book node it belongs to.

You can use Views to list all child nodes on a book page through that reference field, if you need such a list.


Use form_alter to add placeholder text to a Views Exposed Filter min/max field I have an exposed "List Price" field in a View using the "in between" operator (so that users can search for content between this price and that price), and I need to add the text "Min Price" and "Max Price" as placeholder text for the Min and Max fields. I had success using the custom module below to add placeholder text to other exposed fields using the "is equal to" operator, but I have had no luck using the same module code to affect the min/max fields. Here is my working module code:

<?php
function bootstrap_primary_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_exposed_form") {
    if (isset($form['field_productname_value'])) {
            $form['field_productname_value']['#attributes'] = array('placeholder' => array(t('Product Name')));
    }
  }
 }
?>

and here is the code that does NOT work for the "min" portion of the price field:

<?php
function bootstrap_primary_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == "views_exposed_form") {
    if (isset($form['field_listprice_value[min]'])) {
            $form['field_listprice_value[min]']['#attributes'] = array('placeholder' => array(t('Min Price')));
    }
  }
 }
?>

Can someone please guide me on what I am doing wrong and how I can make it work? Could it possibly me the "[min]" portion of the module code that is tripping things up?

In case it helps, here is the full code for the List Price field:

            List Price

  <input type="text" maxlength="128" size="30" value="" name="field_listprice_value[min]" id="edit-field-listprice-value-min" class="form-control form-text">

  And
 <input type="text" maxlength="128" size="30" value="" name="field_listprice_value[max]" id="edit-field-listprice-value-max" class="form-control form-text">

...and here is the full code for the field that the module worked on:

            Product Name

 <input type="text" maxlength="128" size="30" value="" name="field_productname_value" id="edit-field-productname-value" class="form-control form-text" placeholder="Product Name">

Thanks!

Found the solution!!! (here: https://www.drupal.org/node/2280069#comment-8844805)

  if (isset($form['field_listprice_value']['min'])) {
    $form['field_listprice_value']['min']['#attributes'] = array('placeholder' => array(t('Min Price')));
  }
  if (isset($form['field_listprice_value']['max'])) {
    $form['field_listprice_value']['max']['#attributes'] = array('placeholder' => array(t('Max Price')));
  }


Set value for date field in hook_form_alter How can I set the default date for a date field in hook_form_alter().?

I tried:

$form["field_price_date"]["und"][0]['value']['#default_value'] = $curDate;
$form["field_price_date"]["und"][0]['value']['date']['#default_value'] = $curDate;
$form["field_price_date"]["und"][0]['value']['date'] = $curDate;
$form["field_price_date"]["und"][0]['value'] = $curDate;

None of the above work.

The date field's a funny one, normally the field column name is the last in the array (like the first example you tried), and the default value is set on that.

For a date field though, the default value is an array, and it's one level further up, e.g.:

$form["field_price_date"]["und"][0]['#default_value']['value'] = $curDate;

For future reference, install the Devel module and use the dpm() function to print a breakdown of the form array to the screen (dpm($form);). It makes debugging this kind of thing so much easier.


Multiple images in field and views I have a view that creates JSON for me. The view has a field that multiple images, title, body and some other data fields on it. The image field can have multiple images. How can I show  all the images? I know multiple field settings would show all the images but then it would loop all the info multiple times (as many times as there images) and I don't want this to happend.

I have also tried "Display all values in the same row" and putting Simple separator as "," but it only shows the first image.

What I want is the JSON would be something like this:

"nodes" : [

{
  "nid" : "124",
  "title" : "This is the node title",
  "field_shot_desc" : "Short description text",
  "Body" : "
Curabitur blandit tempus porttitor. Nulla vitae elit libero, a pharetra augue.
\n",
  "field_images" : "http://www.domain.com/sites/mytheme/files/styles/browser-thumb/public/rest1.jpg","http://www.domain.com/sites/mytheme/files/styles/browser-thumb/public/rest2.jpg",

},

So the images would be separated with , or something so I can manipulate them in JS later.

Here there is a piece of code I wrote for the same problem. It checks if the field is an array and start a for loop to print the field. I've used this in an external page who gets json through a json view from drupal.
I hope this can help you. If you rewrite it in a simple way, please let me know.
I'm using drupal 6, with NO "Display all values in the same row".

This Check if the field has got more than one img:

var image =  your_img_field;
    function isArray(image) {
   if (image.constructor == Object)
      return true;
   else
      return false;
}

If the field has got more than one img, it counts the array and return the size:

if (isArray(image) == true) {
Object.size = function(image) {
    var size = 0, key;
    for (key in image) {
        if (image.hasOwnProperty(key)) size++;
    }
    return size;
};
var size = Object.size(image);

Here the for loop to print (in my views the array starts from 1)

for (i=1; i<size+1;i++){
$("ul").append("

");
}
}

If the field img has not more than 1 img it prints the single img.

else {
$("ul").append("

");
}

PLEASE, CHECK QUOTES AND DOUBLE QUOTES IN THE IMG TAG


How to keep underlying file when deleting a Filefield value I have a Content Type with a FileField (Image, in particular). When one of these values is deleted, then Drupal deletes the underlying file as well (as long as no other nodes reference the same file).

I don't want the underlying files to be deleted, I want them to remain in the filesystem. Are there any hooks or other techniques I can use to make sure it remains after its FileField value is deleted?

This has already been answered:
https://stackoverflow.com/questions/2101754/drupal-filefield-remove-file-from-node-but-leave-on-server


not able to map all my product Attributes in commerce feeds I'm using Feeds commerce to import all my product variation.

Here is my product variation definition

SKU
Price
Color
Size
Images

In the Feed Importer, I'm not able to map the Color,Size and Images. Anybody know why theses fields attribute is not showing up in the mapping dropdown.

Thanks

https://www.drupal.org/node/1031064 Try the dev version.

I had the same problem and after updating to the dev version all the missing fields were back. Seems there was a bug


How can one determine if a view is empty using views_embed_view()? I need to add a header to the page markup if a call to views_embed_view() retrieved any content, and hide it if not. Unfortunately, an empty view produces this markup:

<div class="view view-related-content view-id-related_content view-display-id-block view-dom-id-a62e1bda4cd2427adcbfba7ad95dec6e">

</div>

(I've left the spacing in to be as accurate as possible).

The view is set to hide results when the argument for the (only) contextual filter is not present.

How can I determine whether the view actually has any results, without incurring any extra DB overhead?

I'm looking to do this just with API functions as overriding templates for something so trivial is not palatable. I'm also not looking for any hacks (e.g. measuring the length of the return string and hiding the header based on that).

You could use views_get_view_result() which returns an empty array if the view has no result to display.


Different link paths for view nodes I am using Drupal 7 and I have a block view in my home page. This block view selects nodes from two different content types. Only the titles from these nodes are appearing in the block view. By clicking on these titles I want to redirect in two different pages, based on the content type each view node belongs.

e.g For the view node with title : "Meeting on 3th September", I want to redirect on ".../drupal/meetings" page,but for the view node with title "Announcement of program" I want to redirect on ".../drupal/news" page

What is the way for redirection from view nodes to different links according the content type of the view nodes?

Thank you.

I solved the previous problem as follows:

1.In my block view I added the field "Type", and i clicked the option "Exclude from Display"

2.In the field "Title" of the view, I disabled the option "Link this field to the original piece of content" and i rewrote the title with the rule: [type].

3.I added a redirection rule from each type to the corresponding link


programmatically add body classes with template preprocessing Is there a way to add body classes programmatically through template preprocessing without the use of a Javascript or a drupal module?

If so how would one do that? p.s. Using omega theme.

E.g.: I need to add a class to the body to change a particular background color.

You can add your class to body element by adding THEMENAME_preprocess_html() to your template.php
Like :

function MY_THEME_NAME_preprocess_html(&$variables) {
  // Compile a list of classes that are going to be applied to the body element.
  // This allows advanced theming based on context (home page, node of certain type, etc.).
  $variables["classes_array"][] = "blue-bg";
  $variables["attributes_array"]["class"][] = "blue-bg";// For Omega based themes
}

Refer this link for more details.


How can I have custom content as last page? I have a view which shows nodes of 3 specific content types. The content shown is coming from the parent node with entity reference fields where the nodes can be selected to be shown in the view.
I was wondering how I could add custom content, or maybe a node to the end of a that view without having to select it on the parent, because this is always the same content.
What I want is like have the view display a node or some programmatically custom content. It should be there as last page. For example I have a view with 4 nodes, the pager should show 5 and have the 5th page be the node/content I want. I don't want to have to add it every time on the parent node with the entity reference field. It should be there by default.

Probably the easiest way to do this would be to add a footer to your view. If you are on the admin screen for your view, you should see options for Page Settings, Header, and Footer in the middle column.

If you "Add" content to the Footer area it will always output below your view content. There are several options including to display a rendered node.


Is it possible to create an installation pack in Drush make? I already have a Drupal 7 running. Is it possible to create an installation package using Make from my current setup. My goal is I have a Drupal 6 version which I need to convert to D7. For the sake of automated deployment I want to replace my D6 core once finished running the scripts to disable modules, features, and custom theme with my Drupal 7 setup before running update.php.

I have code to generate an installation profile from an existing site; it is still a work-in-progress in the issue queue here: http://drupal.org/node/1368242.  Presently it works with D7, but does not yet generate the necessary installation scripts for D6.  It still does a lot of useful work for you, though, and is a good place to start.

However, if your goal is to upgrade your D6 site to D7, what you are really looking for is Drush Site Upgrade.


Set restriction on user by country for language translation content How do I restrict individual user by country to see a restricted list of languages
in the Internationalization module? For example, I would like to restrict users from China, to see only Chinese translations.

I'm trying to get the country by global $user; but it is not working.

You can use Translation Access module.

This module provides per-language access control for creating and updating nodes by adding a list of checkboxes for each available language to the user add/edit form (only visible to users with 'administer users' permission).


Use a form to filter table data in a module I have made a module in Drupal 6 that builds a page that shows some data taken from an external database.
I want to add a form that let the user filter the data (for example, limit the data output to a specific city instead all the cities).
How can I get the value of the submitted form and use it as a filter condition on the page rendering function? The $form_state variable doe not exist when running the page function and I have no way to load the value.

It sounds like your problem is about passing the selected value to your page rendering function, upon form submission.  There are a few different ways to pass that value from within the form_submit function, including via a URL argument, or setting a cookie, or using some javascript to post the value - or even using variable_set() in the right circumstances. There might be easier better ways than those, and I'd like to know what they are if they exist.

Here's a way to do it via a URL argument:

In the form_submit() function, pass the select data to the page rendering function via drupal_goto().  Eg: drupal_goto( 'this/page/' . $form_state['values']['city']
Be sure that your page rendering function can accept the right argument.
in your hook_menu:
'page arguments' => array( 2 ),
(or you can just grab the argument using arg( 2 ) from within the page rendering function)

I'm not saying this is necessarily the best way to get the job done, but this should work.


How to limit the length of a tag? I'm using the default taxonomy tags with nodes. If users forget to enter the commas to separate the words it will generate one really long tag.

What's a good way to do a validation?

You want to use hook_form_alter for this to add custom validation to core forms

http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_form_alter/7

Create a form_alter_hook in your module and add a validation function to the taxonomy field in your form:

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "<your contenttype>_node_form") {
        $form['#validate'][]='yourmodule_taxonomy_length_check';
    }
}

Then just create a validation function to implement your logic, ex:

function yourmodule_taxonomy_length_check($form, &$form_state) {
    if (strlen($form_state['values']['<taxonomy_field_name>']) > <your value>) {
        form_set_error('<taxonomy_field_name>', 'Term is too long');
    }
}

For your taxonomy_field_name, you want to use the 'name' value of the taxonomy field in your target content type.


How can I filter by a term when on a sub-page of that term? I have a non-hierarchical taxonomy and 2 content types.

I need to make these pages with Views:

Mysite.com/something/termA/ContentTypeA
(This will display nodes of content type A that are tagged with termA.)

Mysite.com/something/termA/ContentTypeB
(This will display nodes of content type B that are tagged with termA.)

Mysite.com/something/termA/ContentTypeA
(This will display nodes of content type A that are tagged with termA.)

Mysite.com/something/termB/ContentTypeB
(This will display nodes of content type B that are tagged with termB.)

In actual fact there are a lot of terms so I need these pages to be from 1 or 2 Views (EG with dynamic filters). I cant just make 4 Views with static filters.

I could create 2 Views, one for each content type. Filtering by the content type is simple so my issue is just that I need to figure out how to filter by a term when you are on a sub page of that term, not on the term's page itself.

Eg filtering by termA on this page is easy:
Mysite.com/something/termA/

But how do you filter by termA when on this page?
Mysite.com/something/termA/ContentTypeA

I'm a little confuse on what you're trying to show but I think you can do what you want with contextual filters.

To do so:

Add taxonomy to the filter critera (Has taxonomy term ID)
In the first section (when not available), select Provide default value
Type : Raw Value from URL
Select your path component (let say 2 for your term1, categories would be 1)
In the "When the filter value IS available or a default is provided" section, check "Specify validation criteria"
Validator : Taxonomy
Check the appropriate vocabulatory
Filter value type : Term name converted to ID

What that filter will do is check a part of the url and match it against the vocabulary. If a term is matched, let say term1, it will show nodes that have the term. You can add multiple filter to validate multiple part of the url. It's pretty much the same for the content types.

So /term1 could filter all node with term1. term1/activities could filter all term1&activities... You get the idea. Just don't hide the view if the filter doesn't validate, make it show all results.


Show block content inside custom node template I've created a custom template (node--<mytype>.tpl.php), and I'd like to display the calendars from the Availability Calendars module. I don't understand how to load them.
I've tried with this code, but it doesn't work.
$block = module_invoke('availability_calendar', 'block_view');

Can you help me?

First, you have to make your block available inside your node.tpl.php, so edit template.php and add the following:

function YOURTHEME_preprocess_node($variables) {
  $YOURBLOCK = block_load('MODULENAME', 'BLOCKDELTA');
  $variables['YOURBLOCK'] = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
}

Then, on your node.tpl.php you can print $YOURBLOCK; anywhere you want.

And yes, you have to call two "private" functions from block module, see http://api.drupal.org/api/drupal/includes%21module.inc/function/module_invoke/7#comment-15884


View of nodes with no taxonomy term How can I create a view of nodes that are not tagged with any taxonomy term? Note, terms will be added in time and I wont be able to update the view each time.

Thanks

you create a filter for "Content: Has taxonomy term" and then select "Is empty (NULL)" as the operator.


How to check a user's current userpoints balance with Rules? I am interested in creating a rule that checks a user's userpoints and then the rule performs an action.

Currently the Rules module doesn't have such condition. I read that this is possible to do with a Rules Component, that is used as a Rules Condition.

Could someone help me on this please?

I finally found a solution:
I created a rule set,where I add two rules:
1)Load the user points
2)Data comparison of user points

After creation of the Rule set,I created the main rule where I added as an action the Rule Set.Done!


How to make a view that only shows content a user has not voted on I'm working on a project that asks a group of users with a specific role to vote on content produced by users with a different role.

The group who votes is supposed to try and vote on each item, so I'm trying to make a view that will give them pages of the content.

I would like the view to only show the content that they have not yet voted on, so when they have voted on all items, nothing is displayed in the view.

An effective solution to this problem can be found in http://drupal.org/node/513088.

As suggested by Cthos, one should first set up a "Relationship" in the view setting ("advanced" settings in Drupal 7), then use this relationship as a regular filter (no need for contextual filter here).The proposed procedure is:

Relationships
    Node: Votes
        "Require this relationship": no
        "Value type": No filtering
        "Vote tag": Normal vote
        "Restrict to current user": yes
Filters
    (Votes) Votes: Value
        "Relationship": use the one from above
        "Operator": "Is empty (NULL)"


enabling users to upload pictures from their harddrive in wysiwyg I have wysiwyg module with IMCE enabled so I can browse the server of my site is located for pictures I can upload to add to my content. But the idea now is to have users that are bloggers to be able to upload pictures from their harddrive on to the site using a wysiwyg editor (in this case CKEditor).

Anyone experience with that and know how to do that or know of a good tutorial for this. When searching for an answer online I found info that explained how to add CCK fields to my content type but this is not what I want. I want bloggers to be able to choose where they put the pictures in text and how many.

I have used the WYSIWYG image upload module successfully on my previous D6 sites. It has good documentation and a simple interface to do what you need.


Q: How to control theme colors for Drupal 7 mass contact email I'm using the Corporate Clean theme as the basis for my site.  I've customized some theme colors to my liking.  I have installed the Mass Contacts module to send bulk email.  I've specified in the mail system configuration to use the Corporate Clean theme.  The customizations do not appear to cause the following problem since I can't see any color settings that reflect what I'm seeing with the problem.

Problem:

The email that is received (via Thunderbird) is displayed with a dark gray background and light gray lettering.  It is readable, although, I'd like to make it easier on the eyes.  On my phone, it is unreadable - the text actually shows as black text on a dark gray background.  I'm assuming that the color is specified somewhere in the theme or css.  However, I have not been able to locate the settings that would allow me to change the color combinations.  I've read a similar, but, old post but did not quite understand if there was a solution mentioned.

I'd like to get a better understanding of how to control the theme colors for email.  Can anyone tell me how the colors are controlled and how I can change them?

After re-reading the post I mentioned several times, I found one of the comments to actually be the answer to my problem.  That post, created by dwils03, indicated:

  In case anyone was looking for a quick and dirty fix, I just included
  a blank mail.css file in my theme's folder. The result is an
  html-formatted, NON-STYLED email.

I did the same and added an empty mail.css file in my theme folder and it solved my problem.


Batch API passing data to finished function I am creating a batch import and I would like to pass two different counts to my finished function. For example in my 'operations' function I check for an NID if it exists update the node if it doesn't then create it.

In my 'finished' function I want to do something like:

 batch_import_finished($success, $results, $operations) {
   if ($success) {
     $message ='Nodes created: '.$nodesCreated. '<br />';
     $message .='Nodes updated: '.$nodesUpdated;
   }
   else {
     $message = 'some errors';
   }

  drupal_set_message($message);
}

Hope this makes sense.

First, make sure you set the finished process in your batch process.

$batch = array(
      'title' => t('Merging content ...'),
      'operations' => array(
         array('batch_import_import', array($col1, $col2),  //Note we pass 2 variables here.
       ),
      'finished' => 'batch_import_finished', // set this!
      'init_message' => t('Connectng to the base site ...'),
      'progress_message' => t('Processed @current out of @total.'),
      'error_message' => t('An error occurred during processing'),
      'progressive' => FALSE
    );
...
batch_set('admin/content');

Then, in your worker function, you can take the last argument passed to it as $context.

For an example, from above example above, your worker function should be something like this:

function batch_import_import($col1, $col2, &$context) {
  //do the stuff.
  if (!isset($context['results']['created'], $context['results']['updated'])) {
    $context['results']['created'] = 0;
    $context['results']['updated'] = 0;
  }
  $context['results']['created']++; // is_new == TRUE or some logic.
  $context['results']['updated']++; // add some logic to determine created or updated.
}

and then in the finish function, you get $context['results'] as the second argument.

batch_import_finished($success, $results, $operations) {
   if ($success) {
     $message = t('Nodes created: @count', array('@count' => $results['created'])).'<br />';
     $message .= t('Nodes updated: @count', array('@count' => $results['updated']));
   }
   else {
     $message = t('some errors');
   }

  drupal_set_message($message);
}

I have also corrected the $message as you can use t() function here.
Note that you pass $context by reference.
See batch_api examples for more information. This is just some code copied from a module I was developing the other day.

In the finished function, $operations contain unprocessed items.


How to modify field_suffix after form submit? I have a form with a custom suffix (#field_suffix) for a field. I need to change the suffix value after the form has been submitted. Which hook should I use to achieve this ?

Sample Code :

$form['field_test']['#field_suffix']='Suffix-1';

Edit:
I want to show "Suffix-1" when editing form and "Suffix-2" during display of content.

I found a solution to achieve this functionality.

function hook_node_view($node, $view_mode, $langcode) {
$node->content['field_test'][0]['#markup'] = $node->content['field_test']['#items'][0]['value'].'Suffix-2';
}


form_get_errors() is NULL when calling it in an AJAX form callback I have a form with a bunch of required fields that all have the same callback. Here's a single field example:

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'callback_show_buttons',
      'wrapper' => 'formwrapper',
    ),
  );

formwrapper is a wrapper around the entire form:

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

Here's the callback, inspired by this guy's code:

function callback_show_buttons($form, &$form_state) {
    $allajaxchanges = array( '#type' => 'ajax', '#commands' => array() );

    if ( form_get_errors() ) {
        $form_state['rebuild'] = TRUE;
        $allajaxchanges['#commands'][] = ajax_command_replace( "#formwrapper", render($form) );
    }

 return $allajaxchanges;

If I inspect form_get_errors(), it is always NULL, no matter if I validate the form in code or not. drupal_get_messages() is also completely empty, and theme('status_messages') also has nothing in it (these solutions were suggested here). These methods do return something if I submit the form in a non-AJAX way.

Anyone have any idea how to check if a form has errors in it if these don't work?

I found a way to make this work.

I haven't fully investigated this for issues yet but it works with and without javascript enabled.

My use case was only running  my validation if other validation passed:

/**
 * Custom validation function for some form.
 */
function MODULE_NAME_custom_form_validate(&$form, &$form_state) {
  if (isset($form_state['storage']['errors']) && !empty($form_state['storage']['errors'])) {
    return;
  }
  // Do our extra validation here since other validation passed.
}


Blog entries and blog listing page are different content types? So I've noticed that Drupal sets the blog listing page as a different content type to the blog articles. This is a bit awkward because I want to set blocks that are specifically for the blog section.

In admin I can choose to restrict by content type: News Articles (the blog entries), or choose the pages on which the block displays displays: so list the page /blog which is the Blog listings page.

How can I have harmony and set a block for blog listing and blog entry pages excluding the rest of the site?

Thank you

One way to do this is to use the Pathauto module to automatically set your blog URLs.  Set URLs for content of type blog to be blog/[node:title]; then, on the blocks configuration page, you can simply set the pages to be blog and blog/*, which will then show the block only on your blog pages and index but nothing else.


How do I pass a value to a content type field with a custom submit please and thank you for your patience in helping me learn

I have created a content type called response (Through Drupal, not in a custom module)

In the content type I have a field called field_response_number which is a text field.

When I create new content for the response content type and press submit I want to first submit the form, then run a custom submit afterwards that populates my field_response_number based on the result of a custom function.

I can submit and call my custom form submit function fine, but how do I get the total returned from my custom function to populate the field_response_number please

So my work flow is

Create new response content
Submit results in form and then call custom submit handler
Get count from DB
Populate the field_response_number with the result
Display result

Can anyone assist please, as I think I'm almost there

My code is as follows

function testmodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ( $form_id == 'node_response_form'){
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'testmodule_form_submit';
      }
    }
  }
}

function testmodule_form_submit(array $form, FormStateInterface $form_state){
  // This works
  //$result = testmodule_get_node_count('response');
  //drupal_set_message($result);

  How do I populate my field_response_number here please
}

//This handles incrementing by one I want to use to populate the field_response_number with
function testmodule_get_node_count($content_type) {
  $query = "SELECT COUNT(*) FROM {node} n ".
           "WHERE n.type = :type";
  $total = db_query($query, array(':type' => $content_type))->fetchField();
  return $total;
}

Many Thanks for your assistance

I guess you have multiple options.

You set the field value in the alter as a #value, this is not editable by the user, not like #default_value. Then drupal will save it automatically on successful save.
You set the field value in the validate callback into the $form_state variable. Not too elegant, but the drupal will save the value automatically (normally) on successful submit.
You create a custom submit (as you did) and then you load your node (D7: node_load($nid) D8: \Drupal::entityTypeManager()->getStorage('node')->load($id);), set the field value (D7: $node->field_name[LANGUAGE_NONE][0]['value'] = 'something'; D8: $node->set('field', 'field_value');), and then save the node (D7: node_save($node);, D8: $node->save();).
You can use hook_ENTITY_TYPE_insert() to update your field and save the entity again. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/8.2.x)
You can use hook_ENTITY_TYPE_presave() you just set the field value here, you don't need to save it. Drupal's next step will the save. (https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_presave/8.2.x)

For D8 a bit more detailed: https://www.heididev.com/how-programmatically-update-fields-value-drupal-8
And also, maybe the entity is already loaded, check this: https://www.drupaleasy.com/quicktips/drupal-8-getting-entity-id-formstate


Toggle translation in a multilingual site I'm building a bi-lingual site (English and French) with Drupal 7. I want to create a link at the top right corner of my site that toggles a page between English and French. How do I do this?

I have also installed the Internationalization module. I haven't used it yet. Maybe that can help my situation.

For example, say I am on the page http://example.com/home.  How do I figure out the french equivalent of that page, its URL, and print it to the right hand corner of my site?

I recommend using the Language icons module. It will provide a block where languages can be toggled with a Flag. Btw the i18n (at least in D6) provides a similar block but with no flags, you can use this instead too and add the flags with a little CSS. HTH.

http://drupal.org/project/languageicons


How to combine Image and Video fields in a views slideshow in a single carousel? I have a content type called Cities and it has an Image field. Using the Views Slideshow module with jquery.cycle I am able to create a block which takes the Image from the content and creates a slideshow.

However I have a requirements to be able to add the videos also in the same slideshow. So, I added one more field in the content type as Videos field where I can post the Youtube video URL.

Now the Dilemma is to display this video also in the same slideshow as the image, so, the slideshow would continue with mixture of Images and Videos.

My question is how to combine these two fields image and videos in views slideshow, to create a single slideshow/carousel?

You should be able to simply add both fields.  To help matters along you should can add a bit of logic to only show one field if both are populated.  To do this follow these steps:

First decide which field to show if both have values, for the purposes of this example I'll say that it's video but reverse everything if you want it to be the image field.
Make sure you view has "Fields" selected next to "Show:"
Add the image field and tick "Exclude from display"
Add the video field
In the settings for the video field under "Rewrite results", click on "Rewrite the output of this field" and then on "Replacement patterns"
Copy the token that relates to your image field (including the surrounding [ and ])
untick "Rewrite the output of this field" and click "No results behavior"
Paste the token you copied (including the [ and ]) into the "No results text" box.
Save.

Then the view row will show the video unless there is no video in which case it will show the image.


Get user register form fields in edit profile form page So the user register form fields are not displaying in the corect order in the edit profile form page. I have set the order of the fields from admin panel user manage fields admin/config/people/accounts/fields

The fields are rendering properly in the register form however in the edit profile page, the order is messed up.
Is there a way to get the register form fields by using drupal_get_form('user_register_form') in the edit profile page and then render it from the from array? I have tried loading the register form fields but it gives me no result.

You can edit all forms in drupal using hook_form_FORM_ID_alter

So The only thing you need is the FORM_ID , to get that you can open any desired form , then using firebug or some tool like that you can recognize the ID of form.

in your special case the form ID of user edit form is : "user_profile_form" , so you can create a custom module and implement YOURMODULE_form_user_profile_form_alter()

inside print elements as you desire.


List all Configured Menus in the System Is there a developer tool, module, or code snippet that will show all the menu items currently configured in a Drupal system?

If not, would it be "safe" to invoke the menu hook myself to collect this information?  In other words — do individual menu hook listeners (implemented by module developers) alter system state in such a way that invoking the menu hook twice during a page request would be a "bad thing".

Newish to Drupal, not new to programming. I'm specifically interested in a programmer's view of the menu.

You could use menu_get_menus, or use a modified version of its code:

https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_get_menus/7

It returns an associative array of the menus names, either the custom one, or also including the system menus.


Identify submit button in webform I am trying to add additional submit buttons to the webform to navigate between different steps. I have added button like below:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'mywebform_id') {

    $form['actions']['submit_button_step_1'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 1'),
      '#submit' => array('custom_navigation'),
    );

    $form['actions']['submit_button_step_2'] = array(
      '#type' => 'submit',
      '#value' => t('Go to Step 2'),
      '#submit' => array('custom_navigation'),
    );
  }
}

function custom_navigation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  $value = $form_state->getValues();
  //echo '<pre>';print_r($form['actions']);echo '</pre>';exit;
}

But, I'm using same custom submit handler both the custom buttons. How I identify which button has clicked by user? And based on user click I need to redirect user to corresponding wizard page.

Below codes work for two submit buttons given at webform for identify which button is click.

function modulename_form_submit(&$form, FormStateInterface $form_state) {

  $myurl = FALSE;
  $triggerElement = $form_state->getTriggeringElement();

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE BUTTON ID') {
    $myurl = Url::fromUri('internal:/SETYOURFIRSTACTIONPATH');
  }

  if (isset($triggerElement['#id']) && $triggerElement['#id'] == 'COMPARE ANOTHER BUTTON ID') {
    $myurl = Url::fromUri('internal:SETYOURSECONDACTIONPATH');
  }

  if ($myurl) {
    $form_state->setRedirectUrl($myurl);
  }
}


Modifying user view to display correct gender In Drupal 7.21 with ulogin 7.x-1.10 I get following records in the database for male (having sex=2 in the JSON array below) and female (they have sex=1) users:

  5 | 25583 | facebook      | 597287941             | a:7:{s:3:"sex";s:1:"2";s:7:"profile";s:32:"http://www.facebook.com/farber72";s:3:"uid";s:9:"59728
7941";s:10:"first_name";s:9:"Alexander";s:8:"identity";s:32:"http://www.facebook.com/farber72";s:7:"network";s:8:"facebook";s:5:"photo";s:55:"http://gr
aph.facebook.com/597287941/picture?type=square";}

 10 | 25593 | mailru        | 6189724215193505959   | a:8:{s:7:"network";s:6:"mailru";s:8:"identity";s:36:"http://my.mail.ru/mail/masaeva_alla/";s:3:"u
id";s:19:"6189724215193505959";s:10:"first_name";s:27:"\320\220\320\273\320\273\320\260 \320\220\320\275\320\264\321\200\320\265\320\265\320\262\320\27
5\320\260";s:3:"sex";s:1:"1";s:4:"city";s:31:"\320\222\320\265\320\273\320\270\320\272\320\270\320\271 \320\235\320\276\320\262\320\263\320\276\321\200
\320\276\320\264";s:5:"photo";s:48:"http://avt.appsmail.ru/mail/masaeva_alla/_avatar";s:7:"profile";s:36:"http://my.mail.ru/mail/masaeva_alla/";}

And I have this part in my own custom Drupal module:

function pref_user_view($account, $view_mode, $langcode) {
  global $PREFIX;

  $ulogin = @$account->data['ulogin'];
  if (isset($ulogin) && is_array($ulogin) && array_key_exists($ulogin['network'], $PREFIX)) {
          $uid    = $ulogin['uid'];
          $city   = $ulogin['city'];
          $prefix = $PREFIX[$ulogin['network']];
  } else {
          $uid    = $account->uid;
          $city   = $account->field_city['und'][0]['safe_value'];
          $prefix = 'DE';
  }

  $account->content['stats'] =  array(
    '#type'   => 'user_profile_item',
    '#title'  => t('Досье:'),
    '#weight' => 3,
    '#markup' => sprintf('Статистика игр и репутация', $prefix . $uid),
  );
  $account->content['map'] =  array(
    '#type'   => 'user_profile_item',
    '#title'  => t('Карта:'),
    '#weight' => 4,
    '#markup' => sprintf('',
      MAPS_URL, urlencode($city), AVATAR_STYLE),
  );
}

This produces the following user page with wrong gender:

I realise that my question is very chaotic and apologize for the Russian language content here - but I had developed my module over a year ago and don't remember it well.

How could I fix the gender displayed above, do you have any ideas, suggestions?

Please give me a kick start.

Have you checked your Manage fields to make sure your select options are correct?

1|Female
2|Male

Your custom code doesn't do anything with the gender so I'm not quite sure why you posted it.

Also I would verify if you have english to russian translation going on that they map correctly to the right english version.


Adding HTML just to a block I've added a node as a block to my home page (using nodesinblock module). I've got it looking basically like I want it to look with the teaser appearing in the block, but I'd like to add a 'read more' link (or button) to the bottom of the block.

Note: I do NOT want this 'read more' link to appear on the full content node, just the block.

Anyone know how to add some html specifically to a block on the home page?

I just tried this module today when I saw your post, if you don't want the 'read more' to appear on a full content node display you could create a new display template and add the php path/read more html link on the template you created then choose it from the render mode of node in block settings.

But I'm a little curious, why did you not use views block instead? it's a lot easier, you could just put the read more link on the footer.


Installing a New Site with Drush and Ansible I'm trying to create an Ansible Role to run on a VM that creates a new site (so my colleagues don't have to memorize the drush si --db-url command and automate the entire process.

I'm running into a problem where the drush si command is getting the error: Command site-install needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.  We know this means that we're trying to run Drush from a non-drupal environment, so even when I add the 'chdir' arg to my playbook, it still gets this error.

The command in the playbook looks like this:

- name: Site Install with Drush
  command: |
    drush si standard --db-url=mysql://{{ mysql_username }}:{{ mysql_password }}@127.0.0.1:3306/{{ mysql_dbname }} --sites-subdir="domain.edu.{{ drupal_uri }}" --db-prefix="d_"
    chdir=/vagrant/d7core/

I found in a comment somewhere deep in the internet that there is a hidden -r option to specify the drupal root within a drush command.

The new play looks like this:

- name: Site Install with Drush
  command: |
    drush si standard --db-url=mysql://{{ mysql_username }}:{{ mysql_password }}@127.0.0.1:3306/{{ mysql_dbname }} --sites-subdir="domain.edu.{{ drupal_uri }}" --db-prefix="d_" -r /vagrant/d7core/ -y
    chdir=/vagrant/d7core/

Note, I also added the -y option, because it will count as an ansible error when it asks you to confirm that you want to DROP ALL ON db.

Because this was hidden functionality and it took me an hour and a half and it was a random comment somewhere that I found that in, I figured I'd make it an official SO question so anyone else looking to automate a workflow could hopefully find this faster.


How to use fivestar as sort criteria? In Drupal 6, I have added fivestar widget to 'Story' nodes. Now I want to make a view to sort the stories according to their average fivestar ratings. But I don't see Fivestar among the 'Sort criteria', so how can I do the sorting based on Fivestar?

To start with, just enable the top_content default view which comes with the VotingAPI module. Its Fivestar display has the sorting set up as follows:

Relationship: Vote results
Add sort criterion: Vote results: Value, Relationship: Voting results


Disabling view blocks cache I have added a views block through my twig template file (page.html.twig) through Twig_tweaks. It looks like this {{ drupal_view('view_name', 'block_name') }}.

I would like to disable caching for that particular block, but changes to the preprocess_views_view, seem to have no effect. Any suggestions to disable caching for just this one views block?

Any help very much appreciated.

You can use

function hook_block_view_BASE_BLOCK_ID_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  //Change the title of the specific block.
  $build['#cache']['max-age'] = 0;
}

Also note that this does not disable the page cache for anonymous users. If you need that too, then you also need:

  \Drupal::service('page_cache_kill_switch')->trigger();


How do i configure admin email on a shared host? where is that email going? Can someone explain where the admin emails go once the site is up and running? how does it integrate with email accounts on a shared hosting environment?

to test i sent an email to admin@mynewwebsite.com and it didn't bounce. but also, on the shared hosting account no such email address exists.

not sure really where it's going at this point?

any help or advice would be appreciated.

Go to Configuration > Site information (admin/config/system/site-information)

and change the "E-mail address" in Site details.

Greetings.


How to validate a config entity form? I have a config entity with a form which extends Drupal\Core\Entity\EntityForm, which has a public form() and a public save() methods. They both work fine and dandy. I want to validate some information before saving the form. As far as I can tell there's a validateForm() method already built in via the class it extends.

I can't seem to find much information on how to do that. I've tried the obvious, simply setting a return false in the validateForm method but it doesn't seem to be called at all.

I don't have much experience with Drupal in general so I'm obviously doing something wrong.

If anybody could point me in the right direction here, I'd be grateful.

I'd also like to keep the field values in case of an error. I can only assume that that happens by default, but then again I may be wrong.

You can override the validateForm method in your own form class. Just declare a method like so:

public function validateForm(array &$form, FormStateInterface $form_state) {
  // Your custom validation code.
}

Since the Drupal\Core\Form\FormBase (parent of Drupal\Core\Entity\EntityForm) class has no validation, just a blank method, there is no need to call the parent method from your own class.


Specifying display of a new Paragraph type with images using HTML/twig? I created "figure" Paragraphs type, which contains an image field and a caption field. How (from start to finish) do I specify in HTML/twig how to render this new Paragraphs type?

As an example, how would I specify that the output would generate following code?

caption

In Drupal, the specifying the generation of HTML from Paragraph types (as well as other types in Drupal) is done via the misnomer "theming."

First create a
sub-theme.
Next, copy the
/modules/contrib/paragraphs/templates/paragraph.html.twig file into
your sub-theme's templates folder and name it
paragraph--figure--default.html.twig.
Add the following code below the set classes closing brace %} which specifies the parameters for the image you'd like to display.

{%
  set imagestyle = {
    '#theme':      'image_style',
    '#style_name': 'large',
    '#uri':        content.field_image['#items'].entity.uri.value,
    '#alt':        content.field_image['#items'].entity.alt,
    '#attributes': { class: 'myimage' },
  }
%}

Last, replace {{content}} with the code below:

<figure>
    {{ imagestyle }}
    <figcaption>{{ content.field_caption }}</figcaption>
</figure>

Note: Using {{ content.field_image }} directly inside <figure> instead of specifying a structure with theme image_style will not work.


Block visibility role section is missing I am doing development in drupal 8. All of a sudden, I see that block visibility role section is missing.

How can I bring the block visibility role section back?

There is a bug in Rules 8.x-3.0-alpha6 that hides the core block visibility conditions. Please upgrade to Rules 8.x-3.x-dev. See https://www.drupal.org/project/rules/issues/3160347


How to remove width and height from image field images in Views? I'm using Views to generate some HTML, and this includes a field from a Views field.

My problem is, the layout needs the images to be reponsive (height and width based on the parent element), but this is being broken by Views writing in the width and height as HTML attributes which override all the CSS.

I've tried the answer to this question which uses hook_field_attach_view_alter() to remove the width and height from the output array - but it doesn't work, the width and height are still written into the HTML.

Checking the width and height values at the time hook_field_attach_view_alter() is called, it seems it's a timing problem: it looks like this is called before the image preset is applied. E.g. my image preset is 190px x 190px scale and crop: at the time hook_field_attach_view_alter() is called, the width and height are the original width and height of the image, then the 190 gets written over whatever changes the hook makes.

Is there another hook I can use for the same effect?

I also tried using Rewrite results in Views to re-create the image from its component parts. The problem is, it has access to everything except the actual image URL or URI:

Is there a way to access the image URL or URI in the replacement patterns for Views rewrite for an image field?

It feels clumsier than I'd hoped and requires a module, but I found a solution:

Install image_url_formatter module, which creates an image field display that is just the url but still allows you to choose from available image styles
Change the image field in the view to use the new "Image URL" display.
Use the Views rewrite feature to rebuild the image (<img src="[field_image]" alt=... />).


Inspecting HTTP headers when requesting a route generated from Views I have a content view with a REST Export display, and I want to inspect the HTTP request headers and look for a custom header, denying access to the view if the header's value is not on a whitelist. I was planning to use a hook called early in the view, like hook_views_pre_view(), and maybe some of the tools provided by Symfony's HttpFoundation to grab the request headers, but I'm not sure how to put all together. Any suggestions?

You can add a _custom_access requirement to any route via a custom RouteSubscriber extending off of RouteSubscriberBase. This requirement will add a method which can check the request headers to take action accordingly.

Define your event subscriber class in your mymodule.services.yml:

services:
  test.route_subscriber:
    class: Drupal\mymodule\Routing\MyRouteSubscriber
    tags:
      - { name: event_subscriber }

Within your src/Routing/MyRouteSubscriber.php class file extend RouteSubscriberBase with an alterRoutes(RouteCollection $collection) method:

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class MyRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Add _custom_access to the my_view_machine_name REST export display
    if ($route = $collection->get('view.my_view_machine_name.rest_export_1')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Controller\MyCustomAccessController::access');
    }
  }
}

Within your src/Controller/MyCustomAccessController.php class file, perform the AccessResultlogic:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Custom controller adds additional checks to REST data export view.
 */
class MyCustomAccessController {

  /**
   * Checks access for a specific request.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {
    $allowed = FALSE;
    $request = \Drupal::request();
    // @TODO: Add logic based off of $request->headers.
    return AccessResult::allowedIf($allowed);
  }
}


Removing Unwanted CSS I have removed default css files using a code below, but still it is showing some unwanted css files

<?php
function _phptemplate_variables($hook, $vars)
{
 $css = drupal_add_css();
 unset($css['all']['module']['modules/system/system.css']);
 unset($css['all']['module']['modules/system/defaults.css']);
 $vars['styles'] = drupal_get_css($css);
 return $vars;
}
?>

In firebug GOw.css is appearing I dont know from where, can anybody please tell me how can I resolve this?

To find where a specific stylesheet is coming from, scan your Drupal directory for that file's name. This is the easiest way to find it.

To disable a stylesheet, you can either use preprocess hook, or add the following to your theme's .info file:

stylesheets[all][] = css/removed/GOw.css

Just make sure that the file does not exist, and Drupal won't include it.

Hope this helps.


file upload works with only one specified extension but not more than one I can't figure out what is wrong with this code for file uploads. I am trying to specify multiple extensions for the file upload - it works with a single extension, but if I specify more, it fails and only accepts the last item in the list, even though the error message appears to be self-contradicting. If no extensions are specified the system default list works correctly, but I need to add some extensions.

I am enclosing the minimal code, since after trying everything, modifying this code was the only difference between success and failure:

This works (regardless of the extension)

$file = file_save_upload('sequencefile',
    array(
             'file_validate_extensions' => array('seq')));

This fails on 'jpg', but works on 'seq'; moving jpg to the end of the list works for jpg, but then fails for the others.

$file = file_save_upload('sequencefile',
     array(
             'file_validate_extensions' => array('jpg, jpeg, png, gif, txt, doc, docx, ab1, seq')));

The error message on a jpg file is as follows, even though jpg is clearly in the list:

"The specified file mbpdpermissionsP2.jpg could not be uploaded. Only files with the following extensions are allowed: jpg, jpeg, png, gif, txt, doc, docx, ab1, seq."

What am I missing? it should be very simple and yet I can't get it to work.

thanks!

Don't use a comma separation, separate extensions just with space

'file_validate_extensions' => array('jpg jpeg png gif txt doc docx ab1 seq')));


View showing a list of tagged nodes related to term reference field Drupal 7

Taxonomy vocabulary = Company activity (Activity 1, Activity 2, Activity 3 ….). This vocabulary has an OG group field.

Content type 1 = Company with an entity (terms) reference field showing the list of the terms of the activity vocabulary. The widget is “radio button box” and the administrator of the Company, during the creation of the content, may tag and save the appropriate activities performed. This content type has an OG group field.
Example: Company 1 --> tag Activity 1 and Activity 2 – Company 2 --> tag Activity 1 and Activity 3

Content type 2 = Request of Service. Any Company can create a new request of service and first of all choose the needed activity in a entity (terms) reference field (fiel_tipologia_macchina) showing the list of the terms of the activity vocabulary. The widget is “selection list” – only one choice. This content type has an OG group audience field.

Now the question: In Content type 2 (request of service) I need to add a field that show the Company qualified to perform the requested service.
Example: the service requested is “Activity 1” --> show Company 1 and Company 2.

The field has to be a radio button box so the author of the request can choose the company to send the request (one or more company).

I think that I have to use a view (page or block) but I am not able to find the right relation and contextual filters (entity reference or OG).

Thank you in advance for help.

I have accomplished something along the lines of what you describe with a combination of a hook_form_alter and some Javascript. The following should help you set up something that will interactively enable/disable possible company choices based on the selected activity. Take note that it really only works if those inputs are selects and not Drupal's default autocompletes.

In a hook_form_alter directed at the "Request" node and node edit forms, create a simple of array of arrays, where the key is the term IDs of the activity, and the subarrays are the node IDs of the companies. Here is some pseudo-code, since I don't the actual structures of your entities:

$nested_array = [];

$term_query = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery();
$term_ids = $term_query->condition('vid', 'activity')->execute();

foreach($term_ids as $term_id) {
    $node_query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $node_ids = $term_query
      ->condition('type', 'company')
      ->condition('field_ref_activity', $term_id, 'IN')
      ->execute();

    $nested_array[$term_id] = $node_ids;
 }

 $form['#attached']['drupalSettings']['company_activities'] = $nested_array;
 $form['#attached']['libraries'][] = 'my_module/my_module.library_name';

The above makes the nested arrays available to the front end for on-the-fly manipulation. Create a library for your module with this jQuery-based Javascript. Again, pseudocode which you'll have to modify to your form structure:

function limitCompanySelection(selected_activity) {
    let allowed_companies = drupalSettings.company_activities[selected_activity.val()];

    $('company-input-selector option').each(function(){
        if ($.InArray($(this).val(), allowed_companies)) {
            $(this).prop('disabled', false);
        }
        else {
            $(this).prop('disabled', true);
        }
    });
}

Set the above function to run on initial load and every time the selected activity is changed, finding the selected activity and passing it into the function.


Updated by in content I have an article type where a content admin role can Create an Article. There are 10 Content Admins in system. If one content admin creates the node, I can see eg: Submitted by username. If user2 edits the same article, I want to store who edited it and when in database and display the edited by: OR Updated by:

Its same like in SE websites, you can see who edited the post at what time. How do I do this in Drupal 7 ?

P.S. I am still new in Drupal and haven't explored all the big ocean of Modules in Drupal, so, there might be easy solutions for these things somewhere which I couldn't come across using Google Search.

Node Revisions are stored in node_revision table.This table keep track of what user edited what nodes as separate revision.

Also the last uid who has revised/updated the node is available in $node entity.So try something as below in your theme template.php

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Gather last updated author info
  $revision_uid = !empty($node->revision_uid) ? $node->revision_uid : 0;
  if (!$revision_uid) {
    $revision_username = variable_get('anonymous', 'Anonymous');
  }
  else {
    $revision_user = user_load(array('uid' => $revision_uid));
    if ($variables['is_admin']) {
      $revision_username = l($revision_user->name, 'user/'. $revision_uid);
    }
    else{
      $revision_username = $revision_user->name;
    }
  }
  $variables['revision_username'] = $revision_username;

Then just <?php print $revision_username; ?> in your .tpl files.

Reference Link:

https://drupal.org/node/236523

Since above code will show only the last editor info,if you want to get all users
you can query the node_revisions table.


How do I get the absolute URL when using l()? I want to get New product from l(), and I
call it as l('New product', 'node/123'), but this function generates a URL that is not absolute.

How can I generate an absolute URL with l()?

You can make a link absolute with:

l(t('New product'), 'node/123', array('absolute' => TRUE));

See l() and url() for more.


Why do Drupal Form Builder properties have hash marks (#) in the key? Possible Duplicate:
  What are “#” properties?

This one's more out of curiosity than anything.

If you look at the Form API Reference, you can see that all properties have number signs/hash marks (#) at the start of the key.

My question is, why is it like this? Why bother having these hash marks in front of property names, other than "That's the convention somebody somewhere decided", and to occasionally cause people grief when they forget to add one?

Quite curious. Thanks!

If you don't add a hashmark you're not setting that property, but are instead defining another level of a render array element. Consider this example:

$form['your_name'] = array(
  '#type' => 'textfield',
  '#title' => 'Your Name',
  'title' => array( // I am an entirely new element, whose key is "title".
    '#type' => 'textfield',
    '#title' => 'Your Title',
    '#description' => 'Example: Sir, Mr, Bossman, Chieftan',
  ),
);

This example is silly, but it should describe why a hashmark is used to set a property. If your question is really "why use a hashmark instead of an exclamation point, an ampersand, or some other random character?", well, I don't know. I've seen the hash symbol used to define properties in other languages and APIs.


Unset regions for specific content type I want to create a special content type that doesn't include the logo and main navigation. I have a helper module and have added the following section before renenabling it but it doesn't seem to be having an affect. What might I be doing wrong?

function myhelpermodule_page_alter(&$page) {
  if (current_path() == 'node/add/specialcontenttype') {
    unset($page['header']);
  }
}

Just in case I got "header" wrong, I've tried it with 'footer' and other regions to test it out and it seems to be having no affect at all.

Create a hook suggestion in page preprocess and theme that page

for eg:

function yourthemename_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

Now clear the caches
Duplicate page.tpl.php and rename it as page--specialcontenttype.tpl.php

Then, remove the <?php print render($page['header']); ?> etc.. from it


Available options to implement a knowledge base or FAQ repository? I just started with Drupal 7 in an enterprise environment. It's running on IIS7 with MySql as the backend.

I'd like to see this Drupal site host a Knowledge Base or FAQ repository. I did some searches for modules and I haven't found any popular solution.

Ideally, as software/product 'issues' arise and solutions are documented, I want the issue and solution to be easily entered and searched by a small (<100) developer and help desk community.

Any suggestions about how to accomplish this? I'm still getting a grasp on the taxonomy, maybe proper use of taxonomy is all thats really needed?

Ticketing system

Implement a ticketing system, using the Support module. Popular/great module, to the extend that you can live/agree with the design / assumptions / etc of this module. Definitely worth considering to "get started". Here is a list of features (from its project page):

  Ticketing activity is illustrated with colorful charts (depends on the Chart API module).
  Tickets can be assigned to users (and users can view all tickets assigned to them).
  Tickets support states (new, active, pending, closed, etc) and priorities (low, normal, high, critical, etc).
  Configurable email notifications for new and updated tickets.
  Email integration allows tickets to be created and updated via email, with support for attachments. New users can be automatically created. Ticket properties can be updated via email (using included support_mailcmd module).
  Highly configurable client and user ticket overviews, highlighting tickets that haven't been updated for a long time.
  Fully integrated with Drupal's search functionality, users can only search for tickets they have access to.
  Supports an unlimited number of clients, each with their own configuration and access permissions.
  Tickets are nodes, ticket updates are comments.

Wiki system

Implement a wiki system, using modules such as these ones (excerpts are from their project pages):

Wikitools:

  ... provides some settings to get a more wiki-like behavior. It aims to be lightweight; all features are optional, and it provides no database tables of its own.

  Some of the features of this module are:

  Node Creation: Let users create new nodes when they type in a node name which does not exist.
  Node Search: Let users search for nodes when they type in a node name which does not exist.
  Automatic Redirect: If a title of a moved page is entered, redirect automatically.
  Unique Titles: Enforce that titles are unique over all wiki node types.
  Move Protection: Disallow change of node titles for users without administer nodes permission.
  Underscore as Space: Treat underscores as spaces when doing a node-lookup by title.
  Dash as Space: Treat dashes as spaces when doing a node-lookup by title.
  Custom wiki 404 pages: pick and choose from links to create, links to search, and an inline node add form.

  The module can be used in conjunction with the flexifilter module (of course), the freelinking module by hijacking freelinking links, or together with the pearwiki filter module for various wiki formats.

Freelinking:

  ... implements a filter framework for easier creation of HTML links to other pages on the site or to external sites.

  The framework uses a wiki style format such as [[indicator:target]] as markup to identify links.

The video about Setting Up a Wiki in Drupal 7 contains an interesting introduction to the modules mentioned above (and some other modules you might also want to consider for this purpose).

There is also the Wiki installation profile (either just use that profile, are review it to get inspiration about possibilities). Excerpt from its project page:

  ... will set up Drupal with the following settings:

  Moderator role which can revert / delete pages.
  Revisions for pages.
  Freelinking - easier creation of HTML links to new or existing pages.
  Edit a section of a page (based on header).
  Mediawiki input format.
  Categorization via free tagging vocabulary.
  Views: All pages / All categories / All Images.
  Recent changes.

Questions & Answer site

Implement a questions & answers site (similar to "Drupal Answers" here ...), using the Answers module (Disclosure: I'm a co-maintainer of it), for which a Demo site is available.

To experience it yourself, here are the steps to try it out:

Head over to this sandbox site.
Just accept the defaults to create a sandbox demo site (hit the create sandbox button, and wait for the process to complete).
Login to the site (using the suggested defaults).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Note: you may also want to enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x). After you do, return to the question you created before, and see how the look-and-feel of both the question and related answer(s) below it changed ... Here is a sample screenprint of it:

Groups of users

If your target audience consists of multiple groups of users, then you might want to use the Organic Groups module also.

A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

As an alternative you may want to consider the Group module, which only exists as of D7, but already has a pretty stable D8 version also.

Roll your own cookies

After you become more familiar/experienced with Drupal, you could just build your own custom solution. With only site building techniques (using contributed modules), you could probably get pretty far. E.g. using modules such as the Frequently Asked Questions module.

However, I you want more flexibility and (way) more facilities that can be perfectly tuned to your specific needs, then you should consider using modules such as:

Views (Video tutorials: Learn Views).
Rules (Video tutorials: Learn Rules).
Flag (Video tutorials: Learn Flag).
Message (More docu in its Community Documentation).


Remove novalidate attribute from webform for client side validation I have installed webform and client side validation extensions on my drupal project. The problem is in the webform's form element novalidate attribute is appearing, which cancels the client side validation.

In webform general settings I have unchecked the disable client side validation:

And finally in my form settings I have unchecked the disable client side validation:

Cleared cache but the novalidate attribute is still showing. Is there any way to remove this attribute from the form?

The Clientside Validation module is automatically adding the novalidate attribute to the form.


Reset all votes on a content type every week I am trying to build a website where people vote on individual nodes of a content type using the rate module. Is it possible to reset these votes say every 7 days or every 30 days, so that another round of voting can take place. How would I do this within drupal. I do not want to have to go through phpmyadmin to clear the voting api cache. I would prefer if this is done from within the website I'm building.

Is this possible?

There's many ways to accomplish this. The voting data for the Voting API module is stored in the votingapi_vote & votingapi_cache tables. Essentially, you need a way to target the vote data you wish to eliminate in these tables (e.g. via a DB query) and then build some process on which to regularly execute it (e.g. a cron run).

A crude example would be a custom module that evokes hook_cron() to check the last query execution and fire it if it hits its time threshold:

/**
 * Implements hook_cron().
 */
function MYMODULE_cron() {

  // Clear the vote every week.
  $vote_clear_timestamp = variable_get('MYMODULE_vote_clear_timestamp', 0);
  if ($vote_clear_timestamp <= strtotime('-1 week')) {

    // A more targeted process would use db_delete() to target criteria
    db_query("TRUNCATE {votingapi_vote}");
    db_query("TRUNCATE {votingapi_cache}");
    variable_set('MYMODULE_vote_clear_timestamp', time());
  }
}


json migration to nodes I have a json file with 572 items. I have created the migration script and it runs ok, except that the end results says

  processed 572 items (1 created, 571 updated)

It looks like instead of creating one node for each item, only one node is created and then overwritten, so that only the last item shows.

I am guessing that I have problems with the item_selector: nlm from my json file with starts with

{
  "nlm": [
    {RECORD # : .....},
    {RECORD # : .....},
    ...
  ]
}

But changing the item_selector to anything else gives an error and the script doesn't run.

Any idea of how to get the script to create 572 nodes will be helpful.

Thanks

Edit:
my migration script looks like this:

langcode: en
status: true
dependencies: {  }
id: importjson3e
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: null
label: 'New JSON migration'
source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  include_raw_data: true
  urls: 'http://example.com/json/nlm_0119.json'
  track_changes: true
  item_selector: 'nlm'
  fields:
    -
      name: year_added
      label: YearAdded
      selector: YearAdded
    -
      name: month_added
      label: MonthAdded
      selector: MonthAdded
    -
      name: record_number
      label: 'RECORD # '
      selector: 'RECORD # '
    -
      name: Title
      label: 'TITLE '
      selector: 'TITLE '

  ids:
    record_number:
      type: text
process:
   type:
     plugin: default_value
     default_value: new_books
  title: Title
  field_year_added: year_added
  field_month_added: month_added
  field_record_number: record_number
destination:
  plugin: 'entity:node'
migration_dependencies: null

Uncomment your selectors, and your item_selector should be:

nlm/ and not just nlm.

I had this same issue when I was setting up a JSON migration and that was the first thing I ran into.


Dynamic language negotiation by multiple top level domains I am porting www.example.com, the German version is at de.example.com, the French is at fr.example.com and so forth. I could enter these domains in admin/config/regional/language/detection/url but I would like them to be subdomains: if one visits www.example.test then (www,de,fr).example.test should work, and if one visits www.example.local then (www,de,fr).example.local should be the translated domains and so forth. It seems I need to make the results of $config = $this->config->get('language.negotiation')->get('url'); dynamic. I am at a complete loss at how to implement this:

I could write an entirely new plugin based on LanguageNegotiationUrl. If I started with a copy of it, I could drop processInbound and half of getLangcode but the rest would need to stay -- and given how little change needs to happen, that's a lot of code to keep in sync with core.
I could patch LanguageNegotiationUrl factoring out the four $config['domains'] interactions into a method and then extend accordingly. Much less maintenance pain than the previous one but at the same time, it's a core patch. Of course, composer-patch applies them after updates but still, a core patch for this?
I could write a config override which overrides language.negotiation but it seems the overrider doesn't get the data loaded. So I'd need to get the domain map from somewhere else, for example by re-reading it from the config storage. That's really, really wasteful.
I could write a "super saiyan config override" by decorating the config factory service so when the language.negotiation is get() then do something with it, like put the dynamic overrides in setModuleOverride. OK, that's not a lot of code, great, the proxy script will write most of it, even better, but now all config calls are a hair more complex and a hair slower.

Any clean ideas I missed...?

This sounds to me like the perfect use case for environment specific configuration. No runtime changes required. Just like you would swap the email addresses in your environments that are used to send emails and would swap the API keys in dev/test environments, you would swap this configuration there as well. You could use something like https://www.drupal.org/project/config_split for example.


Getting the first URL alias for a node in a SQL query For some backups and exports, I need to fetch the URL-aliases for each node in SQL.
The url_alias taqble, however, has no foreign key to the node table (nid) nor the other way around, it seems.

Is there some hidden join-table somewhere? A neat trick to fetch the node and its alias in a JOIN?

Since the value in the src column in the url_alias table is predictable for nodes you can just query it directly, without the need for any joins:

$nid = 1; // node id
$src = 'node/' . $nid;
$query = db_query("SELECT dst FROM {url_alias} WHERE src = '%s'", $src);

If you definitely want to use a join though, something like this will work:

SELECT n.nid, ua.dst
FROM {node} n
INNER JOIN {url_alias} ua ON ua.src = CONCAT('node/', n.nid)


Executing drush in a bash script I'm under MacOSX and I'm struggling for hours trying to figure out how to make drush run from a bash script.
So let's say I create a named build, then I make it executable.
now I begin the script like this:

#!/bin/bash
drush cc drush

In the terminal if I make ./build, it brings me result like : Drush: command not found
So how can I make it work?

Thank you for your answers!

Got it!
If you call the script directly it doesn't work, better if ou source it like this: source build, then it works.
Anyway, I don't know if it's the better way to call this script.


I want to add an include_path but don't have access to php.ini I was thinking I could use the php function set_include_path() to accomplish this, but I'm not sure which file I should include this in. template.php perhaps?

settings.php would probably be the safest bet.

The template.php file might well be included too late in the process to have the desired effect, but settings.php is included indirectly from drupal_bootstrap() so should take effect before any of your custom code has a chance to run.

If you don't want to alter settings.php in that way you could implement hook_boot() in a custom module which is also invoked very early on in the page build process.


Form storage is cleared after ajax submission I am creating a form with "add more" functionality. Form builder retrieves values according to  form built. keys are generated using uuid service. I also have to save them. So they are saved into form storage.

$form_state->get('links', $links)
...
$form_state->get('links')

On the next ajax submission storage is empty?!
Also I use a block configuration form. So it uses sub-forms. May be the problem is related with. This is related problem. How to prevent SubFormState storage leaking into parent?

You say this is about building the form. If you display a form on a page, then this form is rendered, but the form object is not stored yet. This happens later when the form is submitted, then you can use $form_state.

Generally when you build a form this is the same like rendering of non form content. Put the initial values in HTML (in the form elements). Similar to default values for visible fields use hidden fields for other values. You also have to add the correct cache metadata to the form so that the render cache varies by the data and is invalidated when the data is modified.

If you don't want to transport data in a rendered form then use a session or tempstore. This kind of storage is not restricted to form requests, so strictly not connected to this issue, but for logged in users these are easily available and for anonymous you can start a session, which you need to do anyway if you want to personalize a form.


Recommended approach for setting up contact management? I need to develop a contact form that the administrator can reply to and categorize each message (Responded, Transferred, Archived, etc.) received from users.

Which would be the best approach for this?

Here are multiple options for implementing such contact form, as further details below.
Default contact form (D6 or D7)
This is the contact module that comes with Drupal 7 core (though disabled by default). Typically used by Drupal newbies, and commonly known to have quite a few limitations / issues that can be resolved using some of the contributed modules (mentioned below).
Webform (D6 or D7)
The Webform module is the traditional (and mature) solution used in quite a few (close to 500K) sites. Some details from its project page:

... for making forms and surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has an extensive API for expanding its features.

Note: It also has 2 related charting modules, i.e. Webform Chart and Webform Charts, both integrate very well with the Webform module to provide charts about data created via the Webform module.
Entityform (D7 or D8)
The Entityform module is a fairly new solution used in "only" about 18K sites, and only has an RC1 release so far. Some details from its project page:

... enables you to create front-end forms (fieldable entities), which contain fields that you define! These forms use the standard Drupal fields. This means that out of the box, you can use any standard Drupal node field! As of the time this article was written, there were over three hundred "field" modules. And since Entityforms are "Drupal entities", you will automatically be able to use future "field" modules!
The forms can be used to create custom surveys, petition, and personalized contact forms, and other customized form. (For those of you who have used Webforms, this module brings Webform's functionality into the "standard" Drupal field / entity world.)

Note: in D8 renamed to eForm (to avoid name confusion).
Contact forms in D8 core with the Contact Storage module (D8)
This is the contact module that comes with Drupal 8 core (enabled by default now).
Many more details about this can be found in the article about "Goodbye Webform? Contact Forms Are In the Drupal 8 Core", which explains why you will also need the Contact Storage module:

The one key feature that's missing with the Contact module is the ability to store messages sent through the forms. This is odd, because Drupal 8 deals with contact messages as entities. You can add comments to them, for example. You just can't see them!
To solve this problem, you'll need a contributed module called Contact Storage. The author says they hope to have this in core for Drupal 8.1 and that would make a lot of sense, filling this functionality gap.

Some details from the Contact Storage project page:

... will provide storage for Contact messages which are fully-fledged entities in Drupal 8.
This plus core contact module aim to provide functionality equivalent to the base-features of Webform or Entity Form.
The goal is to firm up this functionality in contrib with view to move into core in 8.1.x or later.


hook_node_view OR template_preprocess_page I have some data to be extracted from external sources. I want to display those data in a custom template tpl page ( page--zzz.tpl.php ) . I had implemented hook_node_view in my module, and with the node->nid, output the data to be displayed on a node.tpl.php page.

However, the designer wanted to use the full width of the page, so I had to display the collected data in the page-zzz.tpl page, instead of just in the node.tpl.php, so I have moved my function for collecting the data from my module to the template.tpl.php, and inside the function template_preprocess_page, with the node->nid, I collect the same data.

Is that correct? Everything would have been much easier if I had been able to access to the $page variable inside of the hook_node_view function. I tried but I did not succeed!!!

Please advice me. Now it is working but I am hesitating whether there was need to move the collecting data function from my module to the template tpl page.

hook_node_view() is not really suitable for loading anymore data. There is a hook_node_load() hook, which you'll receive an array of all nodes that site is about to load.
Note that this is only for loading, and that doesn't mean the user is on a node/XYZ page. You will probably need to add a URL argument match to make sure you load only the data related to the given node. Otherwise, pull all the information at once, and store them in each $node variable, which is passed by reference (all PHP 5 objects are).

The reason to use node_load hook over node_view hooks is that all modules implementing preprocess and view hooks now have access to this new piece of node. Otherwise, a hook_node_view is OK.

Secondly, you do not need to load them again in hook_preprocess_page at all. For Drupal 7 and later, hook_page_alter() is recommended. Since you store the data in hook_node_view/load hook, simply place the content in the regions you need. If this is theme specific, hook_preprocess_page() is better, but most of the contribs that take over entire page contents tend to use hook_preprocess_page(). Besides, you will have access to the renderable array because other preprocess functions are not executed at that moment.

You can get the current node like below (make sure you add arg() conditions to check the page router is node/%node)

$node = menu_get_object();

This $node object will contain the data you stored in the load/view hook. Make sure you pass the first argument to hook_page_alter(&$build) by reference, and place the content anywhere you want like god.


Adding missing Input Formats after Minimal Install After a minimal install (v7.22) I've only got the 'plain text' input format and am missing the 'filtered HTML' and 'full HTML' formats. Is there a way to have just the missing formats installed or do I need to manually add them? If I have to manually fill in the details where can I get the information them as after searching I cannot find any details on this.

If you want to set them up exactly as they were in the default installation profile, you can just copy the code from /profiles/standard/standard.install and run it somewhere (e.g. at /devel/php with the Devel module installed):

// Add text formats.
$filtered_html_format = array(
  'format' => 'filtered_html',
  'name' => 'Filtered HTML',
  'weight' => 0,
  'filters' => array(
    // URL filter.
    'filter_url' => array(
      'weight' => 0,
      'status' => 1,
    ),
    // HTML filter.
    'filter_html' => array(
      'weight' => 1,
      'status' => 1,
    ),
    // Line break filter.
    'filter_autop' => array(
      'weight' => 2,
      'status' => 1,
    ),
    // HTML corrector filter.
    'filter_htmlcorrector' => array(
      'weight' => 10,
      'status' => 1,
    ),
  ),
);
$filtered_html_format = (object) $filtered_html_format;
filter_format_save($filtered_html_format);

$full_html_format = array(
  'format' => 'full_html',
  'name' => 'Full HTML',
  'weight' => 1,
  'filters' => array(
    // URL filter.
    'filter_url' => array(
      'weight' => 0,
      'status' => 1,
    ),
    // Line break filter.
    'filter_autop' => array(
      'weight' => 1,
      'status' => 1,
    ),
    // HTML corrector filter.
    'filter_htmlcorrector' => array(
      'weight' => 10,
      'status' => 1,
    ),
  ),
);
$full_html_format = (object) $full_html_format;
filter_format_save($full_html_format);