drupal_mail() sends two emails, second email is empty I'm using the following code for sending out an email with drupal_mail()

$module = 'example_module';
$key = 'key';
$language = language_default();
$params = array();
$from = 'email@email.com';
$send = TRUE;
$message = drupal_mail($module, $key, $order->mail, $language, $params, $from, $send);
$message['subject'] = 'Subject';
$message['body'] = $message_body;

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);

I get two emails after the function that contains this runs, one email is perfect, the other email is completely empty.

The function that contains the code above only runs once, I tested by printing out some text with dsm().

How can I fix this?

Thank you!

The drupal_mail() function you call will send an email.

Then when you call $system->mail($message); that will send a second email.

Here is an example of how to use drupal_mail (taken from here):

/**
* Implements hook_entity_insert().
*
*/
function dummy_module_node_insert($node) {
  $module = 'dummy_module';
  $key = 'dummy_key';
  $language = language_default();
  $params = array(
    '@url' => url('node/' . $node->nid, array('absolute' => TRUE)),
    '@title' => $node->title,
  );

  drupal_mail($module, $key, $mail, $language, $params);
}

/**
* Implements hook_mail().
*/
function dummy_module_mail($key, &$message, $params) {
  $message['subject'] = t("@title event registration confirmation", $params);
  $message['body'] = array();
  $message['body'][] = t("Hello", $params);
  $message['body'][] = t("Node has been created @title (@url).", $params);
}

The user who posted this code originally labeled it as "The propper way to use this:" and I've had success using this code before.

$module = 'example_module';
$key = 'key';
$language = language_default();
$params = array();
$from = 'email@email.com';
$send = FALSE; //                               <-- HERE
$message = drupal_mail($module, $key, $order->mail, $language, $params, $from, $send);
$message['subject'] = 'Subject';
$message['body'] = $message_body;

// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);

Just set $send = FALSE; to disable the blank email your code is correct as well


Search API path make SEO friendly I am using Search API. I make a view of all the indexed entities and uses Taxonomy term as Contextual Filter. But the path of view is not SEO friendly. The path is like http://www.example.com/en/Real%20Estate.

I want to make this path SEO friendly and convert this space(%20) to dash.
In views I am getting configuration "Convert dashes into spaces" for contextual filter.

I tried to alter the views  and implement hook_views_pre_render, hook_views_post_render, hook_views_post_build and hook_views_post_execute. This time it is not showing the results.

Can anyone help me regarding this?

I managed to do that with the following code:

/**
  * Implements hook_views_pre_view().
  */
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   /* Search page view */
   if ($display_id == 'search_page' && !empty($args[0])) {
     $args[0] = strtr($args[0], '-', ' ');
   }
}

You should also adjust the search form ofcourse..

Facet Pretty Paths module to the rescue https://www.drupal.org/project/facetapi_pretty_paths


How to secure individual fields I am looking for a good way to add security at a field level based on a group.  Different groups will use the same content type. Does OG handle this requirement. I don't want to make the full node private.

I think you are looking for Field Permission module. It says :

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.


How to Override CSS for a core module? I would like to make some changes to the core toolbar module across all my sites, and I don't want to modify the actual core's css.  It looks like I should be able to override the core css found in modules/toolbar/toolbar.css by simply copying this file into my sites directory at /sites/modules/toolbar/toolbar.css.  I tried doing this, cleared the Drupal cache, but nothing happened.  What am I missing?

Ben Your solution is not ideal, as you now have your own version of the toolbar module, and should there be any bug fixes and security fixes, you will not benefit from those, without upgrading your version of the toolbar module.

Solution 1.

CSS will by it's design overwrite itself, since the theme CSS files will be included last, any rule you make in your theme that is identical to what's in the toolbar will take presedence.

Solution 2.

Sometimes it can be a pain to revert styles to browser default, if that is the case, creating a css file with the same name as the one you want to remove and including it in your theme, will make Drupal skip the one in the module and use the one in your theme. In this case creating a toolbar.css file anywhere in your theme and adding it in your info file, will remove the toolbar.css file from the toolbar module and fix your problems.
Remember to clear cache

Solution 3.

If by some reason you have problems making solution 2 work, you can instead remove the css file using hook_css_alter, this only works in Drupal 7+

I did this:
http://drupal.org/node/176046

Basically copied the core toolbar directory into the /sites/all/modules directory.  Then made the changes I needed.  For some reason I had to try this a few times before it actually worked.  I don't know if it was due to errors on my part or some extreme server caching.


How to run jquery codes before and after ajax call? I want to create a loading code while the ajax call is not yet complete, AND enable my jquery code after calling the ajax of drupal form. The ajax I'm referring to is the "Add new field/Add more" of unlimited field. I don't have a custom module for that. I'm just using what drupal already has.

This is the code that triggers the Ajax of the form:

$('input[name="field_collection_add_more"]').mousedown();

I can't use the $(document).ajaxComplete(function(){}); nor ajaxStart
function of the jquery because I only want my functions to run on that specific ajax call for that specific field.

How can I use the beforeSend: and success: when the ajax add new field is running?

Thank you in advance for the help!

/**
 * Special Effects AJAX framework command.
 */
Drupal.ajax.prototype.commands.nameOfCommand =  function(ajax, response, status) {
  alert("Hello I'm Maged Eladawy...")  ; // this will be executed after the ajax call
}

More details

You can read that article Understanding JavaScript behaviors in Drupal.
And if you want your code run after ajax call back, you need write code same example

Drupal.behaviors.exampleModule = {
  attach: function (context, settings) {
    // Code here.
  }
};

  Here are some examples:

  CTools calls it after a modal has been loaded.
  Media calls it after the media browser has been loaded.
  Panels calls it after in-placeediting has been completed.
  Views calls it after loading a new page    that uses AJAX.
  Views Load More calls it after loading the next chunk    of items.
  JavaScript from custom modules may call    Drupal.attachBehaviors() when they add or change parts of the page.


Create relation N:N and specify properties for each relation I have two content types: "Car" and "Options".
My cars can have different options, so I could associate options to a car with References Module. But my problem is I'd like to specify the price of the option for each car/each relation.

Example:

Seat    - Airbag - 100 €
Citroen - Airbag - 88 €

The relation is not only a node reference, it has "metadatas".

For the moment, I plan to develop my own module, maybe "Relations" module will be the solution, but I tried it with no success.

How can I solve this problem?

If there is an existing contrib module for that, that would be Relation. It works at the level of Entities. It should provide a generic API/framework that can be used for what you describe.

If Relation doesn't fit your needs or is not ready for you, then writing a custom module would be the only option. For a custom module, I would work at the Entities level (with the help of the Entity API module), not directly in SQL. While Drupal doesn't provides scaffolding for Entities, it provide helper functions such as field_attach_form() or field_attach_insert() to deal with fields on entities. Unfortunately, the documentation on how to properly use entities is still scarce. The Model module is an attempt to help there since it aims to provide a model entity and entity administration interface to kick-start your entity development.

As you point out, you have the option to develop your own module. In this case, that would be my advise.

Nodereference module (packaged in the CCK bundle) is not a generic relations-module. It can be used for what the description says it is: Defines a field type for referencing one node from another.
With some creativity one can abuse this to create generic N:N and 1:N and even polymorphic relations, but that is never optimal; both technical/performancewise as usabilitywise.

Things you cannot do (well) with this module:

Associate things to things other then nodes-to-nodes.
Keep the SQL and tabledefinitions optimal for your specific cases, filters and searches.
Validate across relations: If child misses a required field, don't proceed with parent.
Atomic updates and inserts: If Relation X fails, don't write its parent Y (or roll it back)
Implement businesslogic: e.g. An order is either unshippable OR has a shipping-address associated.

However, Writing your own solution comes with a lot of downsides, most notably:

Drupal (6) has no ORM, Drupal 7 has one, but is underused. You will be doing all the DBA interaction "by hand". Required effort one might not expect in a "framework"
Drupal gives no scaffolds, APIs and such for CRUD-actions: you will be writing all the forms, pages, storage- and update- handlers by hand. Obviously using Drupal-APIs, but nonetheless, often over 2000 lines of PHP just to manage some "items" and their associations. Nodes on the other hand, do come with such benefits "for free".
Drupal has little or no validation-helpers. You will be writing all your validations in your own PHP. The FormAPI comes with basic (but solid) mass-assignment-protection, but offers little validations on things like dates, lengths[1], sizes, ranges etceteras.

[1] As such, many contributed modules (and even core) have quite often bugs where the input allows a lot longer texts or numbers then the database can store according to its schema: simply because developers did not write validators for them.


Get parent of an entity reference I have an entity reference inside node. How can I retrieve the parent node?

I tried with the following code, where $node is my entity reference, but it doesn't work.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->getTitle(),'CONTAINS');

What is wrong in the code? What code should I use?

An entity reference field is implemented from the \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem class. If you look at the code for EntityReferenceItem::preSave(), you will notice it is setting its target_id property to $this->entity->id().

public function preSave() {
  if ($this->hasNewEntity()) {
    // Save the entity if it has not already been saved by some other code.
    if ($this->entity->isNew()) {
      $this->entity->save();
    }
    // Make sure the parent knows we are updating this property so it can
    // react properly.
    $this->target_id = $this->entity->id();
  }
  if (!$this->isEmpty() && $this->target_id === NULL) {
    $this->target_id = $this->entity->id();
  }
}

I take your code should be changed to the following one.

$entity_ids = $query
    ->condition('type', 'user')
    ->condition('status', 1)
    ->condition('field_product_document', $node->id());

The change makes also sense: A node title cannot be used to uniquely identify a node, since there could be more nodes with the same title; the node ID uniquely identify a node on a Drupal site.

You should be able to get the referenced entity using

$parent = $node->field_product_document->entity;


Simpletest for Sending Mail I've written the following testcase to send an email. In test results output it says

  "1 e-mail was sent during this test."

but acutally it's not.

I tried another way, I put the function in menu callback (test-mail) it's sending mail when I access the URL. But if I access the URL in simple testcase like
$this->drupalGet('test-mail'); the result still says the same "1 e-mail was sent during this test." but was not.

So is it by design? Is there any other way to send mail?

 public function testSendMail() {
  $this->sendmail();
 }

function sendmail() {
  $from = 'fromaddress@gmail.com';
  $to = 'toaddress@gmail.com';
  $message = 'testcase mail';
  $language = 'en';
  $module = "test_mails";
  $key = "notification_mail";
  $send = TRUE;
  $subject = t("subject line goes here", array(NULL),array('langcode'=>'en'));
  $params = array(
    'body' => 'hello from krishna',
    'subject' => $subject
  );
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  return 'Mail sent succesfully';

  }

 function test_mails_mail($key, &$message, $params) {
 switch ($key) {
   case 'notification_mail' :
     $message['subject'] = $params['subject'];
     //the email body is here, inside the $message array
     $message['body'][] = $params['body'];
     break;
 }
}

You need three functions.

1) module_submit.
2) Create a function to send the mail.
3) create hook_mail.

a complete example: file sendmailtest.info

name = sendmailtest
description = sendmailtest
core = 7.x

file sendmailtest.module

<?php

function sendmailtest_menu() {
 $items['sendmailtest'] = array(
   'title' => 'send mail test',
   'page callback' => 'drupal_get_form',
   'page arguments' => array('sendmailtest'),
   'access callback' => TRUE
 );
 return $items;
}

function sendmailtest($form, &$form_state){

 $form['submit'] = array(
  '#value' => 'Send Mail Test',
  '#type' => 'submit',
 );
 //Fundamental devolver el objeto-array form
 return $form;
}

function sendmailtest_submit($form, &$form_state){

 drupal_set_message('Test ok');

 sendmailtest_send($form_state['values']);

}

function sendmailtest_send($form_values) {
  // All system mails need to specify the module and template key (mirrored from
  // hook_mail()) that the message they want to send comes from.
  $module = 'sendmailtest';
  $key = 'sendmailtest';

  // Specify 'to' and 'from' addresses.
  //$to = $form_values['email'];
  $to = 'jeremiselxi@gmail.com';
  $from = variable_get('site_mail', 'admin@example.com');

  // "params" loads in additional context for email content completion in
  // hook_mail(). In this case, we want to pass in the values the user entered
  // into the form, which include the message body in $form_values['message'].
  $params = $form_values;

  // The language of the e-mail. This will one of three values:
  // - user_preferred_language(): Used for sending mail to a particular website
  //   user, so that the mail appears in their preferred language.
  // - global $language: Used when sending a mail back to the user currently
  //   viewing the site. This will send it in the language they're currently
  //   using.
  // - language_default(): Used when sending mail to a pre-existing, 'neutral'
  //   address, such as the system e-mail address, or when you're unsure of the
  //   language preferences of the intended recipient.
  //
  // Since in our case, we are sending a message to a random e-mail address that
  // is not necessarily tied to a user account, we will use the site's default
  // language.
  $language = language_default();

  // Whether or not to automatically send the mail when drupal_mail() is
  // called. This defaults to TRUE, and is normally what you want unless you
  // need to do additional processing before drupal_mail_send() is called.
  $send = TRUE;
  // Send the mail, and check for success. Note that this does not guarantee
  // message delivery; only that there were no PHP-related issues encountered
  // while sending.
  $result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
  if ($result['result'] == TRUE) {
    drupal_set_message(t('Your message has been sent.'));
  }
  else {
    drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
  }

}

function sendmailtest_mail($key, &$message, $params) {
  switch ($key) {
    // Send a simple message from the contact form.
    case 'sendmailtest':

      $message['subject'] = 'Test subject';

      $body= 'Test Body';
      $message['body'][] = check_plain($body);
      break;
  }
}


Drupal Menu Page Callback Function went wrong with arguments I am new to Drupal, and I was trying a small example from Book "Pro Drupal 7 Development", this is an example of basic menu system, here is code:

function menufun_menu() {
$items['menufun'] = array(
    'title' => 'Greeting',
    'page callback' => 'menufun_hello',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
);
return $items;
}

function menufun_hello($first_name = '', $last_name = '') {
return t('Hello, @first_name @last_name'，
    array('@first_name' => $first_name, '@last_name' => $last_name));
}

But I got HTTP 500 Error all the time:

  The website encountered an error while retrieving 'http://example.com/SampleDrupalSite/'. It may be down for maintenance or configured incorrectly.
  Here are some suggestions:
  Reload this webpage later.
  HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

When I tried function menufun_hello() without page callback arguments, it was all okay. Here is code without parameters:

    function menufun_hello() {
    return t('Hello!');
    }

May I ask what was wrong with this? (Plus, I've googled before I post it here).

Really embarrassed to say I made one tiny small mistake in this line of code:

return t('Hello, @first_name @last_name'，
array('@first_name' => $first_name, '@last_name' => $last_name));

I was typing the first comma while switched to Chinese Simplified PinYin, correct code should be:

return t('Hello, @first_name @last_name',
array('@first_name' => $first_name, '@last_name' => $last_name));

After I changed it, everything is okay now. Thank you all for paying attention to my silly question.

500 Internal Server Error
How To Fix a 500 Internal Server Error

By Tim Fisher, About.com Guide
See More About:browser error messagesie problemsfirefox problemschrome problemssafari problems
How You Might See the 500 Error

The 500 Internal Server Error message might be seen in any number of ways because each website is allowed to customize the message. Here are several common ways that you might see the HTTP 500 error:

"500 Internal Server Error"

"HTTP 500 - Internal Server Error"

"Internal Server Error"

"500 Error"

"HTTP Error 500"
500 Internal Server Error messages can show up in any browser in any operating system.

The 500 Internal Server Error displays inside the Internet browser window, just as web pages do.

Cause of HTTP 500 Errors

The 500 Internal Server Error is a very general HTTP status code that means something has gone wrong on the web site's server but the server could not be more specific on what the exact problem is.

That's not a lot of information to go on but there are a few things you can do.

How To Fix the 500 Internal Server Error

The 500 Internal Server Error is a server-side error, meaning the problem is not with your computer or Internet connection but instead is a problem with the web site's server.

Even though the issue is not yours to fix, there are some things you can try:

Reload the web page. You can do that by clicking the refresh/reload button, pressing F5, or trying the URL from the address bar again.

Even though the 500 Internal Server Error is reporting a general error on the web site's servers and not your computer, the server error may only be temporary. Trying the page again will often be successful.

Note: If the 500 Internal Server Error message appears during the checkout process at an online merchant, be aware that duplicate attempts to checkout may end up creating multiple orders - and multiple charges! Most merchants have automatic protections from these kinds of actions but it's still something to keep in mind.

Come back later. The 500 Internal Server Error message is one of the most common HTTP error message seen when checking out during an online purchase so sales are often disrupted. This is usually a great incentive to resolve the issue very quickly.

Contact the webmaster. Chances are good that the website administrators already know about the 500 error but if you suspect they don't, you can always try to contact the website directly.

Also Be carful about  how pass arguments to callback function .
You returned t() function in where not form exist .
hook_menu documentation
Pass arguments using hook_menu


Is it possible to hide fields on node edit form? Is it possible to hide fields on node edit form? I've tried Formatter Field but it doesn't work for me. I know it's possible in content type field display management but I need this functionality on node edit form.

You can use the Field permissions module and disable the edit permission for that field, or you can use hook_form_alter and the #access property, here's an example:
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == "contenttype_node_form") {
    $form['field_foo']['#access'] = FALSE;
  }
}

For a node edit form you must also check if the node exists.

You can use hide() function in template.php or node--CONTENTTYPE--edit.tpl.php files.


How do I add a block of JavaScript to the home page only? I have a block of JavaScript I need to add to my homepage (and only my homepage) to enable the logging of clicks via a heat mapping service I signed up for.

They specified the code needed to be placed just before the </body> tag, but I imagine it's safe to put it anywhere within the <body> tag.

I'd like the snippet not to appear on any other pages. How can I accomplish this?

I am running Drupal 6.

If by home page you mean the front page, then you can implement hook_preprocess_page() in a custom module.

function mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
    $variables['scripts'] = drupal_get_js();
  }
}

The same code works on Drupal 7, as $variables['is_front'] is set in _template_preprocess_default_variables() (called from template_preprocess()), using the following code.

  // drupal_is_front_page() might throw an exception.
  try {
    $variables['is_front'] = drupal_is_front_page();
  }
  catch (Exception $e) {
    // If the database is not yet available, set default values for these
    // variables.
    $variables['is_front'] = FALSE;
    $variables['db_is_active'] = FALSE;
  }

The reason of calling drupal_add_js() first, and then drupal_get_js() is that, in the case another module that is executed after would run the following code, the JavaScript file would still be added.

function quite_a_different_module_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('module', 'quite_a_different_mymodule') . '/quite_a_different_module.js');
  $vars['scripts'] = drupal_get_js();
}

Using drupal_add_js(), the file will be added to the output returned from drupal_get_js().

In Drupal 7 if you want to include the js in the  tag with the

last solution, the file you have to modify,
after you copied it inside your theme from the system folder,
is html.tpl.php.

Not strictly the Drupal way but works


Change default messages from Poll? We're running the core Poll module on our site, and we'd like to change the default messages that it generates. I'm meaning stuff like Your vote could not be recorded because you did not select any of the choices.

I looked at the poll content type, but there weren't any settings for it there. It's apparently not listed under modules, because it's core, I suppose.

How can I change these messages from their defaults?

You can use the String Overrides module.  More options are described in the handbook page Change default strings (text).

Apparently these messages are hard-coded into the poll module, so to change them, one would need to hack core.

poll.module:738:    form_set_error( 'choice', t('Your vote could not be recorded because you did not select any of the choices.'));


some images not displaying after migrating to local host I copied a website from the server to local environment and after seeing that everything is displayed I noticed that the images in all blog posts are not being displayed. I googled this problem and found that a lot of people had it before me and tried applying their ways to solve the problem but none of them were successful for me. I think I am missing something. Please correct me if there is something I might have missed.
Here's a list of things I have done

Compared the image paths and both are the same src="/sites/default/files/image.jpg"
Checked the .htaccess file in sites/default/files and no differences there too
Cleaned the cache

It is not a multisite and it is drupal ver 7.31

The reason you are having the problem is because you have your website on localhost/folders. And you Drupal installation expects your website to be in locahost. So there is to easy ways to solve this problem. Either you move everything up directory and all your files are in the localhost.

cd /Applications/MAMP/htdocs/testwebsite # Move to the website folder directory.
sudo mv * .[^.]* .. # Move everything up one directory.
cd .. # Move to localhost directory.
sudo rm -rf testwebsite     # Remove testwebsite directory.

Or you can created a temporary soft link on your localhost so your Drupal installation can find the sites folder on the localhost.

cd /Applications/MAMP/htdocs/ # Move to the webserver directory.
sudo ln -s testwebsite/sites sites/ # This is going to created the soft link .

You can create a virtual host in apache in the same way it was done on your server.


Formatting numbers in D7 I have a serialized object in a field. I now need to output a float-value. Since the site has 2 languages (german/english) I now need to format the float-number based on the current language.

$value = 123456789.01;
// Language = english
print the_format_function($value); # => 123456789.01

// Lanuage = german
print the_format_function($value); # => 123.345.789,01

I'm lookin for the_format_funtion();.

There is a format_number API module, which may eventually handle this for you. And possibly will make it into D8.

For the moment I think the function you are looking for is number_format()

There is a number_format function in native php, so you can do in your drupal template:

print number_format($value, 2, ',', '.'); # => 123.345.789,01

see http://php.net/manual/es/function.number-format.php


Creating a view which lists all taxnomy terms and the number they appear in a content type? So i have a taxonomy called Product Warnings, and it has around 10 terms. This taxonomy is referenced in several content types (Small products, Large products, etc), and can be selected multiple times (so a user can select in the content type 1 or up to all 10 terms from the Taxonomy).

I want to create a view which lists all terms from the given taxonomy (that's the easy part), and also count the number of times each terms is referenced in a specific content type (i.e. Small products)

So it would look like:

Eye damage: 44
Skin irritation: 13
Hair lose: 1
.
.
.

Now, this is fairly easy to do with a db_query and custom code, but the trick is to do it in a view (if it's possible)

Found the answer i was looking for, and that is to turn on Field Aggregation from the 3rd panel in the view.

I think you need to enable the aggregation in the view. the video here explains the same issue but in Drupal 7, but it's okay, it is the same for Drupal 8


Is it OK to programatically access fields defined through the UI? This is a question about "best practise". I've taken over a project which I'm working on right now, and the custom modules this project comes with all access fields defined through the UI. In other words, the field names are "hard coded" in code - even though the fields are not defined in code. Is this alright?

I'm thinking that the code depends on data (in fields) which it has no guarantee will be there. Anyone could delete the fields at any time.

If you need to access fields from code, how do you make sure that the fields exist? Do you make sure that the modules define the field (programatically)?

I usually use the entity_metadata_wrapper() function to create a wrapper, and deal with fields through that. But if the field doesn't exist, you can get some not-very-helpful wrapper errors.

To see if a field exists, you don't need a wrapper. You can use:

if ($node->my_field) {
...
}

You can create content types in code, but nothing (except common sense) is stopping a rogue user from deleting fields after they are created. So if you are really worried about fields disappearing, you should check that they exist before using them, as above.


Conditional on Header on a View Page? How can I put a condition on the Header in a View to not display the Header if the View has content?

There's an option to display a Header/Footer absent any content, but I'm looking for the opposite effect.

You can user template_preprocess_views_view function to do it

function mymodule_preprocess_views_view(&$variables) {
  if ($variables['view']->name == 'my_view') {
    if ($variables['view']->current_display == 'my_display' && !empty($variables['rows'])) {
      $variables['header'] = '';
      $variables['footer'] = '';
    }
  }
}

I like Drupal(8), but it encourages some bad practices. Giving more than one way of doing something is good, but some of those should not be there. Namely, Header and Footer in the Views. It may seem like an easy solution. But there's a catch! Where is this information stored? In the database. Can you easily import/export/reuse these "settings"? Nope. So hope that'll save some one hours of confusion and wasted time, as personally my first Drupal-based site used a lot of those as I thought, well since they're there it must be good idea to use them.

Also avoid using preprocess functions, unless you absolutely must. Also source of wasted time later on.

So where can you put the header/footer? In your overwritten View twig file. For example: views-view.html.twig will cover all your views but you can put it in a specific one if you're overwriting it differently depending on a view.

Variable you can use there to give total results: {{ view.total_rows }}


How to send variable value in POST Method in Drupal How to send variable value to another page by using POST Method in Drupal?

It would just be a standard form with post as the method.

<form method="post" action="/other-page">
  <input type="text" name="yourfield" value="Value">
  <input type="submit" value="Submit">
</form>


Site architecture - consistent paths, breadcrumb and menu We've been trying to implement a site architecture that has a consistent menu, breadcrumb and path structure for all pages in the site.

This is easy for basic pages since the path can be set using the page's menu position (using pathauto), as can the breadcrumb.

eg: site.com/a-page/b-page

However, we also have 'articles' which appear in lists on certain pages, using certain tags.

The issue comes in preserving the consistent menu location (but no menu item), URL and breadcrumb for these articles whilst keeping the system easy to maintain.

eg: site.com/a-page/b-page/article-1
eg: site.com/a-page/b-page/article-2

(Most Drupal sites seem to just give up and use site.com/article-title ?)

Not all the articles are just 'news' so we don't want to just force the path to one format option using pathauto.

One solution we've identified for these articles is:

Add a field to the taxonomy for 'path to parent' which would contain the path to whatever page the articles are listed on (eg: a-page/b-page/) and then pathauto could then use this to build a relevant path to the content. Then create a Context for each term which sets the Breadcrumb and Menu trail to the correct location.

However, this does not seem very easy to maintain?

Does anyone know of a better solution?

I think instead of using Article content type, you should use Book content type.
so you could create a book page named a-page, then a page named b-page and provide it a-page as parent in options below.
Now start adding article-1 and article-2 as child of b-page.

So when you view these pages article-1 or 2 the breadcrumb and will provide the url as site.com/a-page/b-page/article-1

Correct me if i misunderstood the question and do tick right if the answer is right.

I'm looking at Drupal for the first time and I found the lack of hierarchy support  troubling and I think constantly updating taxonomies would be too much overhead for any large site, especially with a distributed authoring base (e.g. large corporation or government agency).

I think I have found a solution using module Node Hierarchy (primarily) and some other modules.

Essentially you specify which content types are allowed to be children and/or parents, and then when editing a node you have the option to 'create child'.  Once child nodes are created, the parent node will have an option to view child nodes, and ordering can be controlled from this screen.

Use module Pathauto to automatically render URL alias based on parent-child-[child] relationships.

Finally use module Menu Block to add menus based on parent-child hierarchies.

A more detailed description/instruction is here:

https://www.youtube.com/watch?v=oz3xkF819c0

EDIT: Updated my answer to better conform to guidelines.


How to implement a cancel button with required elements I have a form in which I have added a cancel button which looks like this:

$form['cancel_button'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
  '#name' => 'cancel',
  '#access' => TRUE,
  '#submit' => array('mymodule_cancel'),
  '#limit_validation_errors' => array(),
);

This form has required elements in it as well and what is causing the problem. I thought that by having the #limit_validation_errors statement would prevent the required elements check, but that is not happening. How do I prevent the required elements from being checked?

EDIT: I found this answer on a different question Isn't it possible to have multiple buttons  along with a submit button?

This would explain the behaviour I am seeing but it seems to contradict the Drupal documentation about limiting error checking. This would really screw up people who want to save a draft of a form that has required fields. I am pretty sure I have seen this done before, so there must be away around this.

You can make something like this in your function validate :

function FORM_validate(&$form, &$form_state) {
if ($form_state['values']['op'] == 'cancel')
{
 ///  Do something
/// drupal_goto() for example
}
}


How to use Drupal in the cloud with on demand instances Services such as Rightscale do lots of things to help mange unpredictable traffic and bring more servers online when traffic spikes.

Is it possible to use Drupal with services such as this?

While Drupal can be set up for a number of configurations, is it possible to set it up so the configuration is flexible.

What do you need to do to make sure it works?

Assuming that you can bring on demand instances online, what do you need to do to make sure that Drupal will work in this situation. What do you have to do?

What is the optimal setup?

Once you have done what you have to do, what should you do to ensure that you can scale to more servers seamlessly. What is the best configuration in terms of number of servers. How many caching servers should you bring on line for each web server. Should you scale each tier independently?

edit

Edit to clarify that this is to do with the implications of on demand scaling for a Drupal site.

Rackspace put together a pretty decent start to this subject here which uses a couple of specific technologies which you might not want to use, but the principles are the same.

You might also need to look at Mysql clustering, but only really if you're hitting serious traffic levels

if the webservice supports php5 and mysql then there should be no problems with running drupal in the cloud. that said you may want to consider looking at the pressflow fork of drupal if you are looking for serious scaling


Form element with type = value odd behaviour I have 2 forms on the site, each of them has an array, that I want to store inside the form to use in form_submit function:

$form['store'] = array(
  '#type' => 'value',
  '#value' => $fields
);

But in one form_submit function this works:

$fields = $form_state['values']['store'];
unset($form_state['values']['store']);

In another one it doesn't work, giving an error:

  Notice: Undefined index: store in scores_search_form_submit

While this code works:

$fields = $form_state["complete form"]["store"]["#value"];
unset($form_state["complete form"]["store"]);

Why does this happen?

You can use form properties:

$form['#mystore'] = $fields;

The form properties are not sent to the client, but are available in the submit hander. For example, core use $form['#node'], $form['#user'], etc.

Updated:

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html#val

  Note that as of Drupal 6, you can also simply store arbitrary
  variables in $form['#foo'] instead, as long as '#foo' does not
  conflict with any other internal property of the Form API.

Updated 2:

Your problem may be related to this issue: http://drupal.org/node/1381830


How to change design in comments list I am listing all the comments in a page.

For example, suppose the comments are listed using a design similar to the following one:

  Comment Title 1

  Comment Description 1

  Comment Title 2

  Comment Description 2

  Comment Title 3

  Comment Description 3

If the third comment is the last comment, I should not print the line for that comment.

How can this be done?

EDIT: Updated to use a preprocess function.  This still might not be pretty, but works fine.  In your template.php file in your theme, add this function (replacing YOURTHEME with the name of your current theme):

function YOURTHEME_preprocess_comment(&$variables) {
  $display_order = _comment_get_display_setting('sort', $variables['node']);
  if ($display_order == 1) {
    $variables['end_comment'] = db_result(db_query('SELECT MIN(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
  else if ($display_order == 2) {
    $variables['end_comment'] = db_result(db_query('SELECT MAX(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
}

Now copy comment.tpl.php from modules/comment and place it in your theme folder.  Add this code

print $end_comment == $comment->cid ? ' last' : '';

to the class area of the div html.  It should look something like:

<div class="comment<?php print ($comment->new) ? ' comment-new' : ''; print ' '. $status; print $end_comment == $comment->cid ? ' last' : ''; ?> clear-block">

You now have a class of last on the bottom comment, no matter which way they are sorted.  Now simply add some simple CSS to your stylesheet:

div.comment.last {
  border-bottom: none;
}

You can also use jQuery or CSS to remove the bottom border from the last comment, but they are less reliable depending on a user's browser, browser settings, etc.

jQuery:

// Remove border from last comment
$('#comments div.comment:last').css('borderBottom', 'none');

CSS (Works in IE9, but unfortunately will not work with IE8 and below):

div.comment:last-child {
  border-bottom: none;
}

If you use a D6:
In a comment.tpl.php delete all previous code and paste this:

<?php print $title ?>

<?php print $content ?>

and in css:

.commentz { border-bottom:1px solid #000; }


How to use CSS preprocessor LESS.js with Drupal 7? I would like to use LESS, the CSS preprocessor, with Drupal 7 projects.

What are the required steps to use LESS in Drupal?

There is the LESS CSS Preprocessor module for drupal.

Introducing LESS support in Drupal 7 would be a great idea when combine with Bootstrap and Font Awesome. A helper module named "TWBS LESS". The goal of TWBS LESS is to provide a handy support for LESS and act as the helper module for on going Drupal-Bootstrap-Remix development. http://edin.no-ip.com/blog/hswong3i/announcing-twbs-less-simple-less-support-drupal-7


Handling id from autocomplete field I have an autocomplete field that selects id,text data from db table. I want to show the text in the field but need to put the selected id inside a hidden field so that, when the user submits the form, it is passed as form_values[] to _submit hook.
Which is the correct way to do it in D7?

I've run into the same topics and found a solution, check it here: Autocomplete field - fill the selected id into another form element (eg. hidden field)


How to add a button that jumps to an external link in the content type? I would like to add a purchase button in the content type, the button is an internal link, for example:www.example.com/go/nodeid. And then add an external purchase link to the text field, for example:https://item.jd.com/2385876.html. Click the buy button (internal link) JS jump to the external links, because I do not want to search engine crawling the external link address.
For example,
 open the page（http://www.chong4.com.cn/read.php?18818）, showing the link（http://www.chong4.com.cn/cydb/go.php?18818_127334_22s）, click will jump to（https://detail.tmall.com/item.htm?id=536478627694&ali_trackid=2:mm_13376157_4604749_42838263,22s18818:1479362916_3k2_69258376）

nofollow: Links to an unendorsed document, like a paid link. ("nofollow" is used by Google, to specify that the Google search
  spider should not follow that link)

  source: HTML  rel Attribute

All you have to do is write your link like this:

Buy Now

For add links in content type you can use link module. That provide you link field.Add link field in your content type.


How do I add a template suggestion for a Views block? I am very much so new to Drupal and have moved to this platform after working with Magento for 5 years.
I am trying to create a template for a view. I have created the twig template under /templates/views/ called views-view--partners--partners--sales.html.twig but do not know how to hook the theme into using this twig template.

You need to name your template based on the rules for Views templates.
For example, "views-view--partners--partners--sales.html.twig" would mean:

viewid: partners
view-display-id: partners
fieldid: sales

If this is correct, then all you need to do is clear the cache and reload; the template should be picked up automatically.

Inside sites/default/services.yml add config like this:
parameters:
  twig.config:
    debug: true

(and clear the cache) and it will turn on twig debug mode, which will give you information (inside html comments in page source) on what templates are used and possible template name suggestions to override those templates.


form submit handler is not called I tried to mimic the multiple user deletion feature of user.module but for some reason the confirm form submit handler never get called. I don't know where the problem lies in. Following is a working sample of module except for the function delete_multiple_server_confirm_form_submit which never gets executed.

function mymodule_menu() {

  $items['testservers'] = array(
    'title' => 'Manage Servers',
    'page callback' => 'display_servers_callback',
    'page arguments' => array('delete'),
    'access callback' => true,
  );

  return $items;
}

function display_servers_callback($args = '') {

  $op = isset($_POST['op']) ? $_POST['op'] : $args;
  $op = strtolower($op);
  $build_form = array();

  if (!empty($_POST['table']) && isset($_POST['operation']) && ($_POST['operation'] == 'delete')) {
    $options = $_POST['table'];
    $build_form['delete_multiple_server_confirm_form'] = drupal_get_form('delete_multiple_server_confirm_form', $options);
  }
  else {

    $build_form['display_servers_form'] = drupal_get_form('display_servers_form');
  }

  return $build_form;
}

function delete_multiple_server_confirm_form($form, &$form_state, $servers) {

  $path = current_path();

  return confirm_form($form, t('Are you sure you want to delete %title?'), $path, t('This action cannot be undone.'), t('Delete'), t('Cancel')
  );
}

function display_servers_form($form, $form_state) {

  $header = array(
    'server_name' => array('data' => t('Server Name')),
    'location' => array('data' => t('Location')),
    'protocols' => array('data' => t('Protocols')),
    'status' => array('data' => t('server status ')),
  );

  $servers = array(
    array('server_name' => 'us1', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us2', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
    array('server_name' => 'us3', 'location' => 'us', 'protocols' => 'test', 'status' => 'ok'),
  );

  $options = array();

  for ($index = 0; $index < count($servers); $index++) {

    $options[$index] = array(
      'server_name' => $servers[$index]['server_name'],
      'location' => $servers[$index]['location'],
      'protocols' => $servers[$index]['protocols'],
      'status' => $servers[$index]['status'],
    );
  }

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No servers found'),
  );

  $options = array();
  $operations = array('delete' => array(
      'label' => t('delete servers'),
      'callback' => 'delete_multiples',
    ),
    'suspend' => array(
      'label' => t('suspend servers'),
    ),
  );

  foreach ($operations as $operation => $array) {
    $options[$operation] = $array['label'];
  }

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'delete',
  );

  $form['options']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
  );

  return $form;
}

function delete_multiple_server_confirm_form_submit($form, &$form_state, $servers) {

  drupal_set_message('working');
}

After careful rereading of the user module, i realize that 2 more hidden form values need to be added so  the same delete_multiple_server_confirm_form will get called again after confirming action,otherwise the display_server_form will be rendered.

$form['table'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
$form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

 foreach($servers as $id) {

    $form['table'][$id] = array(
         '#type' => 'hidden',
         '#value' => $id,
         );
   }

If you are rendering your form using form--anyformname.tpl.php template file then make sure in that template file you are rendering these three thing at the end:

    <div>
    <?php print render($form['form_id']); ?>
    <?php print render($form['form_build_id']);?>
    <?php print render($form['form_token']); ?>
    </div>


CSS is broken only certain admin pages Drupal 8.2.7:
Similar to this question: Why does my Site have a broken theme/style?

In my case only certain admin pages css are broken and this seems to only affect admin, not unauthenticated users. For example /node/add/article. In the head tag, I see the correct aggregated css listed a few times:
/sites/default/files/css/css_Va4zLdYXDM0x79wYfYIi_RSorpNS_xtrTcNUqq0psQA.css?onn5ym

But some stylesheets are not aggregated:
/?onn5ym

The common consensus is that the files where css are stored are not writable by Drupal, but I'm not sure this is the case because some stylesheets get aggregated. Or they are coming from another directory I do not know about? I've also tried clearing cache, no luck. Any other suggestions?

Turns out this was a permissions thing after all. The entire web/modules directory needs to be read/writeable by Drupal.


how to alter main menu to add custom class How do I add custom class to main menu. The main menu links are like Fashion, Art, Life and nodes being viewed category can be any one. I want to make the main menu item active as per node being viewed category. e.g if example.com/node/44 -> category = fashion then the Fashion in main menu should be selected. I tried MYTHEME_menu_link and MYTHEME_menu_link_alter but they did not work for me.

Thanks for your help.

I can't tell you how this works programatically, but with menu-position module you can achieve exactly what you're looking for. You'll just add a position-rule for your node-types (or taxonomy item used) to highlight a parent item accordingly.


ABT term reference field hidden in Node View I am using "Access by Term" configuration to control VIEW and UPDATE access for a content type with a Term Reference field in the content type. See screenshot.

But setting this configuration hides the term ref field in Node View.

How do I fix this?

screenshot of the term ref ABT config fieldset:

Make sure to assign "Allow users to view ABT terms on node page." permission to desired roles.

ABT is a bit treaky to configure, user and contentype must have in common same field TR and same TID on both, i think your problem is that your user do not have same TID (exacltly the same taxonomy and term, ABT looks for TID) and thats why your user do not have permission to see it or update it. Make sure you have same field settings on both sides, user and contentype. I recommend you to install devel and devel node access and there you can see exacltly who has or not permmisions on nodes, fields, etc.


Every user is logged in as admin user I have a weird problem with my new Drupal 7 site. This is also my first Drupal site.

I have now two users: admin1 (has admin rights) & user1
at first, when I logged with admin1, everything was fine
when I logged in as user1, on the hovering admin panel it says that the logged in user is admin1, and this user has admin rights although they don't show on the DB. If content is added by user1, the creator is admin1
I added user2 with no admin rights. Everything went fine until I logged out user2: now the admin1 do not seem to have admin rights anymore but the user2 has them
I tried to disable nginx caching and it seems that it's off, but the problem still remains
Earlier, my site was on LAMP-stack without problems. At least not similar to this. Apache needs too much memory so I switched to LEMP-stack, and this problem arised. So, I assume the problem is somewhere on my nginx-configuration.
All this time, on the database, only admin1 actually have the admin rights

I am using the 7.34 core but the same problem existed with 7.33 as well. The site is hosted on DigitalOcean on a server using Ubuntu 14.04 x64. The webserver is nginx 1.4.6-1ubuntu3.1

@kalabro Actually, it was Drupal problem, but in my own code, not in the core or some module. As a Drupal newbie, I had used "global $user" at a template file to show the current logged in user's username on the menubar... When I removed this, problem was solved.

As a workaround, you could use the Auto Assign Role module.


What is the difference between using theme_table() and theme('table', array())? I am using following code for theming..

theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

is the above format right?
Can 'attributes' be written above inside array?
Can I use theme_table() instead of theme()?

theme_table(array('header' => $header, 'rows' => $rows, 'attributes' => array('class' => 'view-all-frame')));

If they are same then does it affect the execution or anything related to it?

Similarly for theme('item_list', array()) and theme_item_list();

It's not the same.

theme() function is some kind of wrapper for specified theme functions.

It's recommended to use theme() function instead of direct calls, so theme('item_list', array()) is the right way.

I think the function of theme_table and theme('table',array()) is the same. But the way you call the theme_table should be simple like that:

theme_table($header,$rows,array('class' => 'view-all-frame'));


Change ckeditor table dialogue defaults Quite simply the ckeditor table dialogue defaults to a table width of 500, yes the client should be told to delete that value, but I would like to alter the default table width value programmatically to 100%.

I have found other posts like this but in Drupal 8 land where do I do this?

You can achieve this in several ways with a script we can call, for example, ckeditor_settings_modifier.js containing:

CKEDITOR.on('dialogDefinition', function(ev) {
  var dialogName = ev.data.name;
  var dialogDefinition = ev.data.definition;

  if(dialogName == 'table') {
    var info = dialogDefinition.getContents('info');
    info.get('txtWidth')['default'] = '100%';
  }
});

This script should be added in one of these places through libraries:

only in the theme of your website (if you use it also for editing)
in your administration theme in order it works in normal node edit mode, and in your website theme in order it works in quick edit mode
in a custom module in which you can use for example some conditional rules that control the loading of the script.

In any choosen settings it is important to declare the dependency on the core/ckeditor.

This is the case of a module (my_module containing a js folder with ckeditor_settings_modifier.js), in my_module.libraries.yml:

ckeditor_settings_modifier:
  version: 1.x
  js:
    js/ckeditor_settings_modifier.js: {}
  dependencies:
    - core/ckeditor

in my_module.module:

/**
 * Implements hook_preprocess_page().
 */
function my_module_preprocess_page(&$variables) {
  // add ckeditor_modifier in case the user has the role of administrator
  $roles = Drupal::currentUser()->getRoles();
  if(in_array('administrator', $roles)) {
    $variables['#attached']['library'][] = 'my_module/ckeditor_settings_modifier';
  }
}

It works on Drupal 8.4.4 and CKEditor 4.8

You really need to modify this width="" property value?
In HTML5 this property is deprecated, anyway you can use it, and override it behavior via CSS (any value declared for the table through CSS will override the property value without need of use !important or something like that).


Set path for favicon.ico and apple-touch-icon.png I would like my favicon.ico to be accessible by http://example.com/favicon.ico and http://example.com/apple-touch-icon.png, but I can't manage that.
I tried few things, but nothing helped. My favicon.ico/apple-touch-icon.png is located in the theme root folder.

How can I achieve this?

use a symlink, I typically keep my main favicon in my root theme folder, and then in the terminal navigate to the site root and symlink to that icon

ln -s PATH/TO/THEME/favicon.ico

it makes the most sense to me to keep my theme assets in my theme directory, but then I also like to have the same favicon accessible from the doc-root as well

Just place your image in root folder and add the path as in screenshot :


How to display an image field next to the title on the profile pages? My users have an image field, called 'Avatar', that's displayed as an icon. I can easily add it to the users' profile page in the content section, but now I'd like to show it next to the title (the default one prints the username).

As I didn't try to do this before, I surfed around the internet for a while. It seems that lots of similar requests were solved by a template file. Therefore, my plan was to add a user-profile.tpl.php, copy all the code from page.tpl.php to it and add

<?php
print render($user_profile['field_avatar']);
?>

before the title.

I'm not sure whether this might work. Is this a good approach?

The use of the template is solid guess. However, you're using the wrong template. The template you suggesting isn't based on the page.tpl.php page. The output of the user-profile.tpl.php page, will end up in the $content section of your page template.
You should try to use a different approach.

How about a preprocess function? It will intercept the rendering of the variables and by so, you can alter them. If you want to change the title of your user-profile page, I'ld go with something like this:

/**
 * Implements hook_process_page().
 */
function mymodule_process_page(&$vars, $hook) {
  // Load the global user object
  global $user;

  // Check if it's the userpage and the current user, depending on URL
  if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] .= ' ' . $user->avatar[LANGUAGE_NONE][0]['value'];
  }
}

Above preprocess function should be placed in your preprocess folder of your theme or the template.php.
It will extend the existing title with your extra fieldvalue.

There is only one drawback on this implementation. If you have a page with a path like /user/overview, the title will change too. Every URL with user as first argument and a UID as second, will be altered...

Goodluck!

EDIT:
Try this please and let me know how it went:

/**
  * Implements hook_process_page().
  */
function mymodule_process_page(&$vars, $hook) {
    // Load the global user object
    global $user;

    $image = array(
      '#theme'  => 'image',
      '#path'   => file_create_url($user->field_avatar[LANGUAGE_NONE][0]['uri']),
      '#width'  => 20,
      '#height' => 20,
    );

    if ((arg(0) === 'user') && (arg(1) === $user->uid)) {
      $vars['title'] = render($image) . $vars['title'];
    }
}

I'm pretty sure the file to copy is modules/user/user-profile.tpl.php and put it in your theme folder https://api.drupal.org/api/drupal/modules%21user%21user-profile.tpl.php/7 and make the changes in that.


Send an email from Drupal interface? How can I send an email from the D7 UI to specified email addresses?

I want to type in some text, type in some recipient addresses, and click send to send it from the site's address.

An easy way could be using Rules and a custom content type.

The content type should have a title which can be used as the email title, a body for email body, and a field to hold email address(es) (or perhaps a reference field to site users or roles).

Then configure a new rule. Select new content event, add a filter to restrict to defined content type, then as an action select send email. Map the proper inputs and you are done.

Drupal isn't exactly meant as an email client, instead try doing it in a Drupal way.

For example:

Enter a username for a recipient, add body, then send. Give Views Send a shot.
Go to a user page, add body, then send. As in the bundled contact module.


Field depandancy module can not work for textfield in field collection I am using field dependency module for use only 1 field

I have 2 fields text and image user can use only 1 field text or image if user can select text field other will be hidden or invisible
same case with image to text field

here is conditions:

case 1:

Dependent:Image (field_image)
Dependees:Text (field_text)
Description:Image is invisible when Text is filled.

case 2:

Dependent:Text (field_text)
Dependees:Image (field_image)
Description:Text is invisible when Image is filled.

case 1 is working perfectly but case 2 is not working.

You can use Conditional Fields module which define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields.

Thank you.


Path alias creates redirect loop or redirects to the front page When I call our sit "www.example.com/contact-us" I'm getting the following error:

  Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

If I call the site with "www.example.com/node/5" the contact page is displayed just fine.

When I check the path alias on /admin/config/search/path/edit/6, system path and alias are set correctly.

Another problem exists for another alias, when I call "www.example.com/staff" I'm getting redirected to the landing page "www.example.com". Once again the alias is set correctly.

We're using Drupal 7, and the i18n_redirect and redirect modules.

Edit your page and go to URL redirects. Find the redirect path with the most number of count and delete it. Click save then view the page.

Let me know if that fixed your problem

The only way after trying many patched was to open the redirect.module file and omit line #989

drupal_set_message('Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!');


simplenews. confirmation of subscription for registered user purpose: confirmation of subscription for registered user

installed on the website simplenews module (https://www.drupal.org/project/simplenews).
now on the main page there is a form to subscribe to the newsletter.

if the user is not authorized, he introduces email and sends a subscription request,
he comes to notice by email that he signed up for the newsletter and confirm the proposal (!) the desire to receive the newsletter.

if the user is authorized, he sees only the button (email enter) and if you send a subscription request, it immediately becomes signed.

can to make it so that an authorized user before activating the subscription, as well as anonymous, received a notice to activate your subscription?

well, since no one here, I will use:

simplenews_subscribe_user($email, $tid, TRUE, 'website');


The block isn't shown on the front page I have a view block that shows a sub-set of nodes. In the configuration page, the autopreview section shows content, so I know the filters for the view are set up correctly. I configured the block to show on only the listed pages and entered <front> for the page.  Unfortunately, the front page shows only the following content and a static block.

  No front page content has been created yet.
  •Add new content

The weird part is that this static block is configured the same way the view is configured  to show only on the front page.

Why doesn't the view block appear on the front page?

There is something else you should check. If this is a new site, and you have newly named regions, make sure that the regions have underscores (instead of dashes.) If you need to convert any dashes to underscores, you'll have to reassign and re-enable the blocks on the Structure > Block Layout page.

Try setting your block to only display on on /node
Thats what I had to do on my Drupal 8 site for things to show up on the front page.    Also if you want the:

No front page content has been created yet.

 •Add new content

To disappear, you'll need to edit the 'Frontpage' view and get rid of those values from the view.


How to use entity_metadata_wrapper in hook_boot I am trying to create an entity with entity_metadata_wrapper from within hook_boot.  I know everyone will say "use hook_init" but for performance reasons, I'm going w/ hook_boot :) .

I have a couple modules loaded like so:

require_once DRUPAL_ROOT . '/includes/common.inc';
drupal_load('module', 'entity');
drupal_load('module', 'field');

This is what I have:

$entity = entity_create('myentity', array('type' => 'click'));
$ew = entity_metadata_wrapper('myentity',$entity);
$ew->field_myentity_url_reference->set($row->rid);
$ew->save();

The above works fine if run normally (like from form_alter or something), but not from hook_boot.

I am getting the following errors:

Warning: class_implements(): object or string expected in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
Warning: in_array() expects parameter 2 to be array, boolean given in entity_create() (line 367 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/entity.module).
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityMetadataWrapper->set() (line 122 of /data/disk/host/distro/005/drupal-7.18.1-dev/sites/mysite.com/modules/entity/includes/entity.wrapper.inc).

Anyone know what else I need to drupal_load to get this to work?

EDIT - Figure out how to do this:

I used the background process module: http://drupal.org/project/background_process.  I added the code below to hook_boot:

//load the required modules needed to do background_process
require_once DRUPAL_ROOT . '/includes/common.inc';
require_once DRUPAL_ROOT . '/includes/path.inc';
drupal_load('module', 'background_process');
drupal_load('module', 'progress');

background_process_start('shurly_create_click_log', $row);//  drupal_load('module', 'entity');

Then I put the entity code in a new function:

function shurly_create_click_log ($row){
    $entity = entity_create('linkpin', array('type' => 'click'));
    $ew = entity_metadata_wrapper('linkpin',$entity);
    $ew->field_linkpin_url_reference->set($row->rid);
    $ew->save();
}

Basically, the shurly_create_click_log function gets ran at full bootstrap in the background, so it doesn't slow down my pageload/redirect from hook_boot.

Here's a solution.

Add this to the top of your hook_boot() function:

function hook_boot() {
  global $user, $base_path;
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
...
}

drupal_bootstrap keeps track of what level it has been called so this trick effectively pushes hook_boot to being later in the boot process.


"Authored by" field to be automatically filled On every creation of a node or edit of a node I need the "Authored by" field to be automatically populated with the username of anyone saving changes.

any ideas how I can do that?

Thanks.

Personally I think that a module like Rules (powerful and awesome as it is) is overkill for something relatively simple as this.

Looking at node_form(), I see that the author is set by populating the author field with the username. I would create a custom module which implements hook_form_BASE_FORM_ID_alter, and set the default value of the author name field to the name of the current user. That would look something like this (disclaimer: untested code!).

<?php

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  $form['author']['name']['#default_value'] = !empty($user->name) ? $user->name : '';
}

An advantage of this solution is that the field is populated in advance with a default value, allowing user with sufficient permissions (eg. administrators) to override the author as they always can. It would be harder to do that in a rules-based approach which only kicks in after the form has been submitted.

update:

The topic starter mentions in another answer that he ended up with the following code:

function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if ($form_id == 'content_type_node_form') {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

Some feedback on this code:

Of course, the if-statement makes sense if you only need this behavior in certain cases. You could even place the global $user; inside the if.
I would recommend that you keep the !empty($user->name) ? $user->name : '' part, instead of simply using $user->name. It may be an edge case, but as you can see in drupal_anonymous_user, the global $user object does not necessarily contain a 'name' property. If, at some point in the future, this form would become available for anonymous users, they will end up with php notices on their screen.

This should just happen when created, if Author and Date information are ticked in admin/structure/types/manage/[your_content_type], under display settings.

If you want something else, you can use the token module and use a token as default value ; again in the content type settings.

If you want it updated with every save, you have to use hook_node_update() in a custom module, and set $node->uid to current user's ID (global $user; $user->uid).


Programmatically delete one entry from one field on one entity What's the proper way to programmatically delete one specific field entry for a multi-entry field from one specific entity? (that's specific fields and specific entities, not field types or instances and entity types)

Here's some possibilities I've looked into which don't work:

Loading the entity with entity_load(), setting the field entry to =null or =array(), then saving with field_attach_update(). It's the closest I've found but it leaves a zombie null field entry in the database which shows up as a blank row on forms until the form is saved and hook_field_is_empty() can kick in (hook_field_is_empty() is configured such that =null or =array() will flag as empty).
Loading the entity with entity_load(), unsetting the field entry by key, then saving with field_attach_update(). This seems to do nothing - it seems that Drupal interprets the entry not being there as a sign to not modify it. (strangely I also sometimes get maximum query time expiration timeouts when trying this approach)
field_attach_delete() - this is much too blunt: it kills all fields for the entity
field_purge_data() - better, but still too blunt: it kills all entries of the field, not specific entries

So to clarify, I've got code that finds (and loads) an entity which has a field that has multiple entries, and finds a specific entry on that field that needs to be removed. I want to remove that entry completely, without touching any other entries or any other fields on the entity.

If you're able to rely on the entity API module you should be able to use code similar to the following:

// Load some entity.
$entity = entity_load_single($entity_type, $id);

// Remove the field value.
unset($entity->field_FIELD_NAME[LANGUAGE_NONE][$index]);

// Reset the array to zero-based sequential keys.
$entity->field_FIELD_NAME[LANGUAGE_NONE] = array_values($entity->field_FIELD_NAME[LANGUAGE_NONE]);

// Save the entity.
entity_save($entity_type, $entity);

the current preferred method would employ the entity_metadata_wrapper

$node_wrapped = entity_metadata_wrapper('node', node_load($nid));

unset($node_wrapped->$field_name[$index];

this is the best tutorial on the EMW that i've seen http://deeson-online.co.uk/labs/programatically-access-field-data-using-entitymetadatawrapper-drupal


How to show fivestar votes in views as number instead of percentage? I have a view which show a content with a Fivestar field (votes).
The problem is that the field is shown as the percentage of votes, not like the stars, or the number (in fact I need to show the number instead of percentage).

I mean, my Fivestar field has 10 stars. Well then if, for example, a node has 7 stars, rather than see the 7 stars or the number of stars (7) is shown the percentage, 70.

What I have to do to show the number (in my example "7")?

I found a solution for my question: Hide your vote field in views ("Exclude from display"); then, add a Global field, the "global math expression", and in this field add a replacement token of your exclude field, in my case [value]. Finally add the mathematical expression to divide by 10 the number: [value]/10.
Apply and save the view.

Here is a 'fix' to the issue:  "How to show number of stars instead of percentage."  I realized I could just as easily change the label of the formatter in fivestar.theme.inc, i.e. "4" instead of "4/5"

Step 1:   In Views, edit your field.  Set formatter to "Rating"
Step 2:  Go to fivestar.theme.inc and edit line 137

Instead of $output = $rating . '/' . $stars;

I used

$output = $rating;

My full issue can be seen here: https://www.drupal.org/node/421800#comment-11792403


Update a single field when saving an entity Question: How do I update a single field of an entity? For example, lets say I have a user and want to update field_my_field. How do I just update that without using user_save?

My Specific Problem:
I have a a bunch of user fields defined, and am trying to optimize the performance of my site. I am using views_bulk_operations, and my code is timing out (maximum execution time) because I am repeatedly calling user_save, and it's an expensive operation.

I am only updating a single field, and would like to optimize this code. Rather than calling user_save, which is taking 500ms to run, I'd like to update the field directly.

I attempted to use field_attach_update(), and that works a little better, but that's also updating all the fields. Is there any specific way just to update or save a specific field for an entity?

I'm not interested in batch operations, or anything at the moment -- I know how to do that, and can convert this into a batch so I don't run into execution timeouts. I just want to know how to save a single field for an entity.

Give a try with field_sql_storage_field_storage_write.

See this blog post with an example:

//Get the id of your field
$name = 'name_of_your_field';
$info = field_info_field($field_name);
$fields = array(info['id']);

//Execute the storage function
field_sql_storage_field_storage_write('model', $entity, 'update', $fields);

You have to first load the logged in user and then use entity module function entity_metadata_wrapper to update the user field, but be pretty sure to enable the entity module.

            $account = user_load_by_name($uname);
    $user = user_load($account->uid);
    $obj = entity_metadata_wrapper('user', $user);
    $obj->{field_machine_name}['und']['0']['value'] ="your value" ;
    $obj->save();


How to create a module in HTML directly? For instance, I would like to create a module like

    First Name: <input type="text" ng-model="firstName">

    Last Name: <input type="text" ng-model="lastName">

    Full Name: {{firstName + " " + lastName}}

But what I found is that I have to create the module in PHP (For example, mymodule.module), import JavaScript file using drupal_add_js, create functions to establish a form in phpm etc.

So is there any way or an example to create a module directly with HTML?

No there is no way to create a Drupal module without creating the associated .module (a PHP file) and .info files. If you want your JS file to be inserted on all pages, you can have an empty .module file and add a scripts[] = myscript.js enty in the .info file. Keep in mind that Drupal is a CMS, designed to let site administrator manage content. what you are trying to do looks like embedding a JavaScript application on pages of a site whose content is managed with Drupal. While Drupal is extensible, it is very opinionated on how to build custom page.

Since you module actually mixes JavaScript and HTML, the clean way would be to have the required PHP boilerplate code to produce the HTML markup (ie. register a theme template hook and provides its default implementation) while ensuring the JavaScript file is included on the page whenever you template is rendered. Then have the required PHP code to produce a page containing your markup.

MODULE.module

/*
 * Implements hook_menu().
 */
function MODULE_menu() {
  return array(
    'my-app' => array(
      'page_callback' => 'MODULE_page',
    )
  );
}

/*
 * Page callback for MODULE app page.
 */
function MODULE_page() {
   // A simple page containing a single element rendered from out own template.
  return array(
    '#theme' => 'MODULE_app',
    '#ngApp' => 'myApp',
    '#ngController' => 'myCtrl'
  );
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    'MODULE_app' => array(
      'template' => 'MODULE_app',
      'variables' => array(
        'ngApp' => 'myApp',
        'ngController' => 'myCtrl',
      )
    ),
  );
}

/*
 * Implements  hook_preprocess_HOOK().
 */
function MODULE_preprocess_MODULE_app(&$varialbles) {
  // Add required libraries, with
  drupal_add_js(...);
  // Add the custom JavaScript to the page.
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/MODULE-app.js');
  // Add settings for the rendered element to the page.
  drupal_add_js(array('MODULE' => array($variables['id'] => array(
    'ng-app' => $variables['ngApp'],
    'ng-controller' => $variables['ngController'],
  ))), 'setting');
}

MODULE-app.tpl.php

<?php
/**
 * Add documentation here explaining what this template is and what
 * is expected from any overriding implementation (like having a root element
 * with the ng-app and ng-controller attributes, and what's available in the scope).
 */
?>
<div ng-app="<?php print $ngApp; ?>" ng-controller="<?php print $ngController; ?>">
    First Name: <input type="text" ng-model="firstName">

    Last Name: <input type="text" ng-model="lastName">

    Full Name: {{firstName + " " + lastName}}

MODULE-app.js

Drupal.behaviors.MODULEApp = {
  attach: function(context, settings) {
    // Bootstrap the Angular app for any instance or our element.
    settings.MODULE.forEach(function(variables) {
      var app = angular.module(variables['ng-app'], []);
          app.controller(variables['ng-controller'], function($scope) {
            $scope.firstName = "John";
            $scope.lastName = "Doe";
          });
    });
  }
}

Are you sure that you really need module actually? If you only need to insert some (embed) code at some place on page then simple static block can do the job. From admin menu go to Structure -> Blocks and click "add block" link. Enter markup you need in block body save block, and from same Blocks page add it to some region so block body will be displayed on page.


How can I make a usable backup of the site on CD? The client would like to archive off a copy of their drupal 7 site every 6 months or so. By archiving, they are referring to copying the site (in a usable format) onto a cd.

What are some of the options for doing this?

The Backup and Upgrade module can be used to schedule automated database backups. One of those backups, combined with the codebase, gives you a full backup of the site. If this is to be burned to a disc every 6 months, I wouldn't bother automating anything - the time investment won't be worth the future time savings.

@kine456 : Some years ago, after a client request, I used Server2Go (http://www.server2go-web.de/) and it works pretty well with a small Wordpress site. Stunnix may works as well (http://stunnix.com/prod/aws/).
But it is not, in both case, the way to a store a backup.


What is causing /user/*/taxonomy/term/* to redirect to /taxonomy/term/*? I got a view with contextual filters set up as the following:

Global: Null (Fixed value "user")
Content: Author uid (User ID from URL)
Global: Null (Fixed value "taxonomy")
Global: Null (Fixed value "term")
Content: Has taxonomy term ID (Taxonomy term ID from URL)

When I go to mysite.com/user/*/taxonomy/term/* I'm being redirected to mysite.com/taxonomy/term/*.

How can I prevent this?

I also got Pathauto to change the URLs to [user:name] for user/* and tags/[term:name]for taxonomy/term/*.

Edit: If I disable the URL alias for the taxonomy terms it still redirects to mysite.com/taxonomy/term/*.

The source of the redirect could be essentially any module you have, and several modules allow for configuration that will cause redirects as well. You will need find the source of the redirect on for your particular situation.
Suggestions:

Deactivate modules in a 50 / 50 manner. This allows you to quickly narrow down which module is providing the redirect, and hopefully that will help you to work it out. Using drush to disable/enable modules will make this much faster.

Install Devel. It has a settings called "Display redirection page", and implements devel_drupal_goto_alter halting the redirection.
The primary purpose of this is to gather up debug information that would otherwise go lost due to the redirect. In this particular case, I suggest you add a dpm(debug_backtrace()); into the hook so you can trace the call to the source of the redirect.

Everything else failing, fire up a full debugger, and trace the call, ideally with help from the information provided by the debug_backtrace() above.

You could use hook_exit($destination) to change the redirect.

Create a new module. I use the Netbeans drupal-7 plugin to create .install, .info and .module files.
Fill out the .info template.
Implement hook_exit($destination). Call another drupal_goto(). Be careful that it can't create a redirect loop.

Hook Exit passes the destination address, and if you put a debugger on it you may be able to trace the call-stack to find another drupal_goto() that is causing the redirect.


Is weather.com still running Drupal? There have been news items in 2013 about weather.com moving to Drupal. I have been reading How to tell if a site is using Drupal 7 and I have been unable to find out if the site is still running on Drupal.

How can I find out if weather.com is still running Drupal?

I use buildwith chrome plugin and Appspector, it does not looks like they use drupal CMS.

Is not Drupal. IMHO is a custom php framework based on YUI library.


How to get BundleKey in EntityManager after getting storage of entity? I want to get bundleKey of any entity type after is loading from

$node = \Drupal::entityManager()->getStorage('node');

After getStorage I am getting bundleKey Value as "type", but how to render that, as it is saying that is a protected value.
Tried to fetch like:

-> $node->get('bundleKey')->Value();
-> $node->getField('bundleKey')->getValue();
-> $node->bundleKey;

All above methods i tried to fetch Values but still no luck.

Anyone Knows how to fetch bundleKey.

You can get bundleKey of your entity type by this way:

$type = 'commerce_product';
$bundle_key = \Drupal::entityTypeManager()->getDefinition($type)->getKey('bundle');

Found Solution:

Rather that loading complete storage, we can use entityDefinitionUpdateManager and get keys where you will get all id, bundle, label, etc

$manager = \Drupal::entityTypeManager();
$entity_type = $manager->getEntityType('commerce_product');
$entity_keys = $entity_type->getKeys();
$bundle = $entity_keys['bundle'];


Change views pager programmatically I'm adding nodes to a view programmatically and i'm altering the pager 'x out of y' by setting the folowing in hook_views_pre_render:

$view->query->pager->total_items = $count;
$view->query->pager->current_page = isset($params['page']) ? $params['page'] : 0;
$view->query->pager->options['total_pages'] = ceil( $count / $lim );
$view->total_rows = (string) $count;
$view->items_per_page = (string) $view->query->pager->options['items_per_page'];
$view->current_page =isset($params['page']) ? $params['page'] : 0;

Let's say there are 10 pages but even with this code nothing seems to happen, nothing get's altered. When on the second page, it doesn't display the next button. How can this achieved with code? What object, array should i alter to have this result?
Any help would be appreciated.

Thanks

Try some thing like this and see if it helps

function views_pag_views_pre_build(&$view) {
    if ($view->name == "pagination") {
            $view->init_pager();
            $view->set_items_per_page('10');

    }
}

I used the following code:

function yourmodule_views_pre_render(&$view) {
    $myview = views_get_view('view_id', TRUE);
    $myview->display['default']->display_options['pager']['options']['items_per_page'] = '5';
    views_save_view($myview);
}

Your view id is the machine name of your view.

The snippet was borrowed from Programmatically Change Pager "Items to Display" value?

In order to clear the pager, the solution in the above thread also leaves the following snippet on the end.

$cache = $myview . ':block:results:';
cache_clear_all($cache, 'cache_views_data', TRUE);


Webform + reCaptcha - still lot of SPAM Few months ago I installed reCaptcha module to use with webform. It worked perfectly: I can't submit form if I didn't provide correct captcha code. It worked even if I disable JavaScript. Problem is that I still get a lot of SPAM submissions from this webform. How this can be possible?
Drupal version: 6.27.
Webform version: 3.18.

There is really no silver bullet that can be used to completely stop spam. Spam can only be minimized.

Spam entered by human beings will still always get through -- and there are more and more human being spam farms out there.

The best solution that I have found is to work with Mollom rather than ReCaptcha.

Just as @Bisonbleu mentioned in the comment. Another module you can make use of is the honeypot module

  Honeypot uses both the honeypot and timestamp methods of deterring
  spam bots from completing forms on your Drupal site (read more here).
  These methods are effective against many spam bots, and are not as
  intrusive as CAPTCHAs or other methods which punish the user.

I recently changed to Confident CAPTCHA. It was a straight forward drupal implementation and my users like it.


Why render funcion hide img tags? I have a simple text that contains  tags but when I try to render the field, the img tags disappear!

<?php print render($content['field_with_img_tags']); ?>

Why?

What type of field are you using ? If it is a body_format using a format (i.e.: Filtered HTML, Full HTML) verify the filter settings. Probably Limit allowed HTML tags is enabled and the  tag is not part of the allowed tags.

To verify / change settings, it is under admin/config/content/formats and click on configure link of your used format.

try

print drupal_render($content['field_with_img_tags']);


Programmatically save coordinates I have read in a lot of sources that I should use the geofield_compute_values() when trying to programmatically save coordinates in Drupal, but it does not work for me. That function doesn't exist in Drupal 8.5.2.

I've installed the Geofield module using Composer and I can use it as usual in the admin area. There are no problems with saving.

This is the code I tried, which returns an error about a not existing function (geofield_compute_values()).

$geofield_data = geofield_compute_values(['lat' => $lat, 'lon' => $lon    ], GEOFIELD_INPUT_LAT_LON);
$cbisProduct->set('field_koordinater', $geofield_data);

I have also tried this out with no successful result and no errors.

$geofield = [
  'geom' => "POINT (" . $lon . " " . $lat . ")",
  'geo_type' => 'point',
  'lat' => $lat,
  'lon' => $lon,
  'left' => $lon,
  'top' => $lat,
  'right' => $lon,
  'bottom' => $lat,
];
$cbisProduct->set('field_koordinater', $geofield);

I also tried the solution given in How to save LNG and LAT progamatically in a geofield, but it didn't work either.

How can I programmatically save coordinates?

Try this:

$entity->set('field_geofield_name', [sprintf("'POINT (%s %s)'", $longitude, $latitude)]);

Cheers!


What is the twig template name for a node edit form? In Drupal 8, what is the twig template name for a node edit form for a custom content type called for example "device".

For a default node we use node-edit-form.html.twig
So what is the edit template name for a custom content type ?

I would appreciate your help.
Thank you !

You could have a look at this comment. It suggests adding a theme suggestion like this:

  This feels hacky, but it's the best I can come up with. First add this
  code to your admin .theme file (likely a sub-theme of Seven):

function NAMEOFTHEME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
   if ($hook == 'node_edit_form') {
     if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
     }
     else {
       $current_path = \Drupal::service('path.current')->getPath();
       $path_args = explode('/', $current_path);
       $content_type = $path_args[3];
     }
     $suggestions[] = 'node_edit_form__' . $content_type;
   }
 }

  Next, create twig templates in your theme's template directory in the form
  of node-edit-form--NODE-TYPE-SEPARATED-WITH-DASHES.html.twig.

If you want to theme a specific form, for example the edit form of a node type, then all you have to do is

/**
 * Implements hook_theme().
 */
function THEMENAME_theme($existing, $type, $theme, $path) {
  return [
    // form id (weather it's an edit node for or a new node form)
    'node_NODE_CONTENT_TYPE_edit_form' => [
      'render element' => 'form',
    ],
  ];
}

Then create a twig file node-NODE-CONTENT-TYPE-edit-form.html.twig

and theme it like so:

{{ form.field_MACHINE_NAME_OF_FIELD }}
{{ form.field_MACHINE_NAME_OF_FIELD2 }}
...
{# this prints out the submit button #}
{{ form.actions }}
{# you need to have this for the form to work properly #}
{{ form|without('name', 'field_MACHINE_NAME_OF_FIELD2', 'field_MACHINE_NAME_OF_FIELD3') }}


How to set the default value of an exposed filter rather than -Any-? I have a view with exposed filters in Drupal 7 and I need to set the default value of a filter to current year. I also need to unset/remove the - Any - option from the select list.

You can use hook_form_alter() to alter the any drupal form.
example :

function yourmodule_name_form_alter(&$form,&$form_state,$form_id){
  if($form_id == 'views_exposed_form'){
  $form['field_width_value']['#default_value'] = 'whatever you want';
  unset($form['field_width_value']['#options']['All']);

 }
}

This is my solution. Working for Drupal7

function **THEME_NAME**_form_alter(&$form,&$form_state,$form_id){
    if($form_id == 'views_exposed_form'){
      $form['**FIELD_ID**']['#options']['All'] = '**YOUR TEXT**';
    }
}


Adding options to View filter settings I want to add new option "Own Company" into "Options" select in View filter settings form:

This is filter of entityreference field.
Also I want to have opportunity alter views query with this value.

I tried with form_alter but I can't save chosen value.

Also I wanted to write own views child class that will handle entityreference filter settings. But I can't find dafault handler in hook_views_data_alter.

Also saw that views filter select in entityreference module is made with ctools plugins system. Filter settings form might be plugable but I can't manage to do it.

Has anybody altered views filter settings form?

1) Add new custom views filter handler that extends views_handler_filter_in_operator

class MY_MODULE_own_company_filter_handler extends views_handler_filter_in_operator {

  public function get_value_options() {
    $options = parent::get_value_options();
    $options['own'] = 'Own Company';
    $this->value_options = $options;

    return $this->value_options;
  }

  /**
   * Replaces "Own Company" value with real value.
   * Do query alter here or in query() function.
   */
  function pre_query() {
    parent::pre_query();

    // Check if "Own Company" was chosen.
    if (!empty($this->value['own'])) {

      // Unset "Own Company" 'own' value.
      unset($this->value['own']);

      // Get current "Own Company" value the way you like.
      $company_id = 100500; // Example value.

      // Set current "Own Company" value.
      $this->value[$company_id] = $company_id;
    }
  }

}

2) Implement hook_views_data_alter() and add custom handler to all entityreference field filters

/**
 * Implements hook_views_data_alter().
 */
function MY_MODULE_views_data_alter(&$data) {
  // Loop all field filters.
  foreach ($data as $data_key => $data_field) {
    if (strpos($data_key, 'field_data_') !== FALSE) {

      // Get field name
      $field_name = str_replace('field_data_', '', $data_key);

      // Check if field filter is entity reference
      if (isset($data_field[$field_name . '_target_id']['filter']['handler'])) {
        if ($data_field[$field_name . '_target_id']['filter']['handler'] == 'views_handler_filter_in_operator') {

          // Name of custom handler class
          $custom = 'MY_MODULE_own_company_filter_handler';
          // Add custom handler
          $data[$data_key][$field_name . '_target_id']['filter']['handler'] = $custom;

        }
      }
    }
  }
}

What you might need is to create a "relationship" (http://gotdrupal.com/videos/drupal-views-relationships) with your user's profile and filter the user's "company" and have that match one of your company's taxonomy terms to get the same company results.

You might have to create a view's php field to get the result you want. (How to use Views PHP to rewrite results of a field?)


Site redirects to old URLs after moving to a new server I am in the process of moving a Drupal site to a new server.
I copied the database and moved all the files.
The old URL for the site is http://www.sniffingmusicians.echidna-band.com/ and the new is http://www.sniffingmusicians.com/, which point to a different server.
Even though the frontpage of new is there, when I log in, I am redirected to the old domain.
Additionally, all the content is using the old URL. I changed the value of $base_url in settings.php, but there is no real impact.
Where else can I reconfigure my site's URL?

Maybe you can use this module:

Path Redirect (Drupal 6)

Redirect (Drupal 7)

If you are using domain access, be sure to check the table PREFIX_languages. I had the exact same problem and wasted 2 days before I found the problem. The old domain was hard coded in the PREFIX_languages table and once I changed it everything worked perfectly.


How can i change registration email send to admin I was wondering how to change the standard text in the email send to the administrator when a new user has registered.

Is there a way to change the text? Maybe the same way as you can change the emails send to the user when registered?

thanks

Unlike normal users there's is no UI to change the text of the message sent to administrator on account creation.

You could implement hook_mail_alter(), to achieve this via a custom module:

function MODULE_mail_alter(&$message) {
  if ($message['id'] == 'user_register_pending_approval_admin') {
    //$message['body'] is the array you want to change.
    $message['body'][] = 'Your custom message for admin goes here.....';
  }
}

One way is to use the rules module

You create an action (send an email) on a user creation event


How to resave all my nodes In D7, it was easy with the VBO module..
But how to do it with D8? (Preferably using a view to select the nodes to resave)

In many places I saw that a small part of the VBO module is now included in the D8 core but I can't figure out how to use it (assuming a simple save should be feasible)

What you are asking for is included in core Views, unless I am mistaken.
In a new Content view you will be able to add a "Content: Node operations bulk form" field and that offers you an option for "Save content".

You could even use the default "Content" view...

that already offers that option out of the box:

In Drupal 8, there is a module Scheduler which gives content editors the ability to schedule nodes to be published and unpublished at specified dates and times in the future.

It's currently in alpha version for drupal 8.


Alter field content inside modules hook_node_view I'd like to alter, but not save, a fields output.  I've got a MODULE_node_view already setup.  Is there a way to do this?  I don't want to save the output permanently.

In HOOK_node_view() you can alter your fields like this:

function MODULE_node_view($node, $view_mode, $langcode) {
  //be sure to be in full page mode, but you can also user 'teaser'
  if ($view_mode == 'full' && node_is_page($node)) {
    //kpr($node); => use devel module and kpr() to inspect your node.
    //Change the title of the node
    $node->title = 'New title';

    //Change the "text" field
    $lang = field_language('node', $node, 'field_text');
    $node->field_text[$lang][0]['value'] = 'New field text value';

    //Change the "body" field which has a slightly different syntax
    $lang = field_language('node', $node, 'body');
    $node->body[$lang][0]['value'] = 'New body value';
  }
}

Note the usage of field_language() to retrieve the correct value for each field.

You can print the $node array and then access your field through index.

print_r($node);


how to include one drush make.yml file in another? With the INI-style drush .make files I could say includes[common] = "common.make" in say, drupal_master.make but I can't see a way of breaking my make.yml files into smaller reusable chunks.
I've tried

imports:
  - common.make.yml

(like Symfony uses elsewhere) as well as other guesses and I can't see any examples or documentation on "including" YAML drush make sub-files.

Can it be done?

Edit: I do see that you were using the wrong keyword, it should be includes and not imports.

It looks like you have the correct syntax above I believe. We use something like the code below in our make process, there are three different core makes that we call that one in, local, development, and build (we wanted to get updated versions in local and more stable ones in dev and build, just so we can update when appropriate.). It works pretty well but see the code below for an example. Thanks!

api: 2
core: X.x

defaults:
  projects:
    subdir: "contrib"

includes:
  - drupal.make.yml
  - libraries.make.yml
  - modules.make.yml
  - themes.make.yml
  - custom.make.yml

Here is the link for the Drush documentation for the make files, I didn't notice that they had swapped over to YML in the make docs or I would have started with this probably: Drush Docs - Make.

Drush do a large use of YAML files, I suggest you organize as a codebase and use a command line tool to parse a group of files into one for every task! You can include the common parts and share schemas use a '$include' tag provided by utility like this https://github.com/javanile/yamlinc

Comparisone 'includes:' vs '$include:'

'includes:' only support specific section no nested include support, only one level of inclusion
'$include:' generic place everywhere you need it, nested inclusions supported