Where does the $node get its field values after a node edit page has been submitted? I'm attempting to debug a problem where a date field is not being saved.

The field renders fine with the rest of the node form, but upon submit one particular field has no value.

The $form_state contains the expected value all the way down until the form does a redirect to the node view, however, in hook_node_presave, all the data that should be on the node, is missing.

I'm getting lost in the form api trying to trace down where exactly the form_state gets added onto the node.

I am using Drupal 7, and the Date module version 7.x-2.5.

It looks like the actual work to attach the fields to entity objects is done in the _field_invoke() function, right at the bottom with these lines:

if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
  $entity->{$field_name}[$langcode] = $items;
}

That doesn't make a lot of sense out of context so it's worth having a look at the whole code for the function.

The basic workflow is:

The node form submit handler calls field_attach_submit()
field_attach_submit() calls _field_invoke_default()
_field_invoke_default() calls _field_invoke()

The entity object is passed through all of those functions and once they're run all fields are attached to the object.

I know it's not much to go on but hope it helps.


Copy view mode custom settings On /admin/structure/types/manage/article/display I can enable custom display settings for various view modes. But what if I want one custom view mode to be almost identical to another? Is there a way to copy the settings of a certain view mode to another view mode?

There isn't any built in way of doing this. I'm sure you could make a custom module that could do this, but it wont exactly be trivial.

What makes this a bit tricky, is that the information is store many different places. Each field has it's weight stored in the field_config_instance table, which holds general information about the field, like widget settings etc. The weights for all the extra fields for the entity/bundle is saved as a key to the field_bundle_settings variable that can be accessed with variable_get.

If you want to explore this you can take a look at the field_ui_display_overview_form_submit function which is responsible for saving the display info.


Using Theme() to output html/javascript in user edit I have a module that outputs a button to the user edit page. I use the form_user_profile_form_alter to append the button but I want to add html and javascript after it. I saw that the theme() function can do this but my attempt does not add any html. Also I saw that the theme needs two parameters but I do not know what the 1st parameter is supposed to be. I was only following examples.

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

  $form['actions']['myButton'] = array(
    '#type' => 'submit',
    '#value' => 'Click Here'
  );
  $form['actions']['myButton']['#submit'][] = 'myModule_callback';

  return $form;
}

Here is my callback function

function artsci_pubmed_biblio_callback($form,$form_state){
  drupal_set_message('Button Clicked');
  return theme('box', '
Item 1

Item 2

Item 3
');
}

If you just want to add some markup and Javascript, you don't need a submit callback because that's for handling form submissions.

Requirement 1: Add html

Options:

#prefix and/or #suffix form element attributes. (If just simple short html this will do)
#theme to use you custom theme function declared hook_theme and place your markup in your tpl.php file. (If too much markup and want your module/theme to be clean)

Requirement 2: Add javascript

You can use #attached form/form element attribute

In the links, there are example codes that you can follow.


DB log message: login failed for user xxx Does anyone ever get "Login failed by user xxx" messages in their recent log entries?  I have been getting the same message over and over for the past several days, always from the same IP address and user trying to access node/add.  It's kind of freaking me out.  Anything to be done about it?

These are often spammers, but might also be malicious users who are trying to break into your site (for example, to use it to post malware, distribute files, or as an email relay). If your set of users is small and well known then you should only be worried about these messages if they are for actual accounts on your site - that would be an indication of a brute force attack.

If your site is Drupal 7 then you already have some built in protection against brute force.

Some modules that might be useful to improve the overall login security of your site.

http://drupal.org/project/user_restrictions
http://drupal.org/project/password_policy
http://drupal.org/project/mollom - configured to show a captcha on the login page
http://drupal.org/project/tfa
http://drupal.org/project/ga_login
http://groups.drupal.org/node/235938


Drupal in redirected site folder not working My web host directs traffic to the main public_html folder on the site for my main site. `

However, I want my main site to redirect to a subfolder for organizational reasons, so I can easily manage just the main site files within that folder.  Therefore I want to redirect to public_html\mysite.com

I have created a .htaccess in the public_html folder that DOES redirect properly when I just point it to a test index.html file.  However, when I try to point to index.php of for my drupal installation, I get the following :

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, webmaster@mysite.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.

Here is my .htaccess which lives in the public_html

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?<mysite>.com$
RewriteCond %{REQUEST_URI} !^/<mysite>.com/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /<mysite>.com/$1
RewriteCond %{HTTP_HOST} ^(www.)?<mysite>.com$
RewriteRule ^(/)?$ <mysite>.com/production/dev-code/index.php [L]

Do I need to modify the .htaccess in \public_html\mysite.com` somehow for drupal to load?  I don't have access to the server error log.

Just add a rewriteBase to your .htaccess file

RewriteBase /subdirectory

Note that this goes into the .htaccess file in the “subdirectory”, not your website root .htaccess file!


Rewriting taxonomy term in exposed filter I have an exposed taxonomy term filter with values of "true" and "false".  I would like to simply rename the options to "yes" and "no".

I can't simply change the taxonomy tern name since I am importing the values from a XML file.

How would you suggest I do this?
Is there a simple CSS rewrite - changing true to yes, and false to no?
Is there a field theme function I should use?

Thanks for any help.

The easiest way is to use hook_form_alter to alter the names displayed in the options.

An alternative and a bit more tricky way, is to create your own views_filter_handler for them term used in the view, and customize how the exposed filter form should look like. This is a good solution if you are creating many views and want a single place to do the alterations. See How do I add dropdowns in Filter Criteria in Views module? for more info.


Views table columns not sortable Standard drupal field types like Strings, Numbers, Dates and Taxonomies can be defined as Sortable in Views with Format: Table.

But more complex fields like Hierachical Taxonomies and Paragraphs or paragraphs don't have a checkbox to make them Sortable.

Is there any way to make them sortable using Views interface or do I have to make a custom plugin  Tablesort with EntityQuery?

Categories or Paragraphs are just references when you create a node view.
Thus when you use them in the fields (as output) they are not sortable but you can add a relationship to them and then their individual fields (like name, id etc) become sortable

Here is an example with tags (on article content type)

Added term relationship Taxonomy terms on node and then tag id and tag name are sortable (among others)

ΝΟΤΕ: you will most certainly end up with duplicate results in the view. For this you can use aggregation, "Group results together" with group column "entity id".


Add value to field using Entity Metadata Wrapper I'm trying to accomplish the seemingly simple task to add a value to a multi-value file field in Drupal 7. I have been trying for hours, but none of the answers I found would solve my problem.

My field is called field_video_ext. Using the Remote Stream Wrapper module, I would like to add values like this (using some of the module's code):

<?php

// My videos and their respective nodes.
$videos = array(
  array(
    'nid' => '1903',
    'uri' => 'http://example.com/movie.flv',
  ),
  array(
    'nid' => '3172',
    'uri' => 'http://example.com/movie2.flv',
  ),
);

foreach ($videos as $video) {
  // From the Remote Stream Wrapper module.
  try {
    $file = remote_stream_wrapper_file_load_by_uri($video['uri']);
    if (!$file) {
      $file = remote_stream_wrapper_file_create_by_uri($video['uri']);
      file_save($file);
    }
  }
  catch (Exception $e) {
    drupal_set_message($e->getMessage());
  }

  if (empty($file->fid)) {
    drupal_set_message(t('Unable to add file from URL %file.', array('%file' => $video['uri'])));
    exit;
  }
  // Display needs to be set.
  $file->display = 1;

  // Get Entity Metadata Wrapper
  $wrapper = entity_metadata_wrapper('node', $video['nid']);

  // Write information into fields.
  $wrapper->field_video_ext->set(get_object_vars($file));

  // Save wrapper.
  $wrapper->save();

}

?>

Now the problem is that this doesn't work if the field accepts multiple values. It throws the error

  EntityMetadataWrapperException: Invalid data value given for wrapper
  chain

I then tried using $wrapper->field_video_ext[] = get_object_vars($file);, but that doesn't work either. I think it was this error I got:

  Fatal error: Cannot use object of type Project as array

I also tried the following instead of get_object_vars($file):

$file = (array) $file;
$items = array($file);

And then saving that array using set() or the [] way. But to no avail. Can anybody tell me what I am doing wrong?

One issue may be that get_object_vars() returns an array with keys that the file field does not understand.  The EntityMetadataWrapper documentation provides two options for setting file reference values, though it appears to use single value fields in the examples:

Setting the file directly:

$w_containing_node->field_attachment_content->file->set( $file_obj );

Providing an array with just fid:

$w_containing_node->field_attachment_content->set( array('fid' => $fid) )

One of the comments provides the following examples from the entity tests which apply to a multi-value field, though I'm not sure if setting the full file object will work appending a new item:

$wrapper->field_file[0] = array('fid' => $file->fid, 'display' => TRUE);
$wrapper->field_file[1]->file = $file;


Two different design in Drupal website My website has two designs and I not sure which one is better. I am thinking upload both of them.

Here is my question: Is drupal able to let 50% of the user see design A and the rest is able to view design B. After one month later, I am able to see a report which one is better.

The closest thing I know is:
Switchtheme

Adds a block to allow users to switch between enabled themes.
Themes can be given 'user friendly' names and access can be controlled
by user role.
Switchtheme provides optional support for Browscap module to switch
themes based on the browser of a visitor.


Disable example of shipping method Please tell me how to remove the example shipping method. If I disable this module, my other shipping methods also don't work. There is no option to disable or delete this. The only option is 'Configure Component'. I have even tried imposing a condition on Example Shipping Method 'that it must show up only if the order is too big' but still doesn't work. All shipping methods get disabled even if I add a condition on 'Example Shipping Method. '

You can disable Shipping Method Example from the module list itself. I have never enabled that and my shipping method works. I have flat rate enabled for my shipping method. Simply disable the module. Here is the screenshot of my shipping modules tab -


Display plugin entityreference is not available I'm not sure if this is a Views issue or an Entity reference issue, so I'm cross-posting here to see if I can find an answer.

I'm trying to export a view from my testing & development site, to our production site, but I keep running into issues, and I'm not sure where I'm going wrong.

To the best of my knowledge I've got the exact same setup on both sites - modules are all the same, and all have the same versions for both Views and Entityreference.

However, when I try to import the view on our production site I get the following errors:

Relationship handler node.reverse_field_plan_document_attachment_node is not available.
Display plugin entityreference is not available.
Relationship handler node.reverse_field_plan_document_attachment_node is not available.
Unable to import view.

I'm stumped. I have no idea where else to look. I'm assuming it's a simple issue with a setting somewhere, but I can't find it. Everything works perfectly without issue on our testing site, and doing wholesale database swap is not an option.

When I go to create a new view on our production site, I don't even have the option to add an entity reference display:

Initially, I tried to use the features module to move the feature set from the testing site to the production site, but that was an enormous mess. I completely uninstalled the features module, and all the modules I created with it in effort to try to get this stuff working. After uninstalling all that stuff, I'm still left without an option to even create an Entityreference display with Views, and obviously cannot import my view either.

Can you help?

So - after getting another pair of eyes on this the issue is resolved. Somehow, the entityreference module was only partially installed and was missing the views directory (along with a couple other things) but was otherwise fully functional outside of the issue as described above.

Not sure how the module would be working for other purposes, not throw any errors at all without those directories but that was the case.

Thanks to Matt Glaman for the help tracking down the problem.


Value from ajaxified form field not passed to ajax callback This is a continuation of this issue, where I couldn't get the ajax to fire on an entity reference field in a node edit form. With the following code, I'm able to get the ajax to fire.

/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function mymodule_form_blog_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_video_reference']['#ajax'] = array(
    'callback' => 'mymodule_video_ajax_callback',
    'wrapper' => 'my-path-div',
  );

  $form['my_path'] = array(
    '#markup' => t('My path'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#weight' => 6,
  );

  if (!empty($form_state['values']['field_video_reference']['und'][0]['target_id'])) {
    $form['my_path']['#markup'] = 'Token path: http://www.mysite.org/node/' . $form_state['node']->field_video_reference['und'][0]['target_id'];
  }
}

function mymodule_video_ajax_callback($form, $form_state) {
  return $form['my_path'];
}

The problem is that the value from field_video_reference isn't being passed to the if statement in the form builder or my callback, so the value from that field isn't displayed in the my_path field when the value is first selected on the node create form (it works fine if the node has already been saved and there is a value in field_video_reference when I edit the node). I'm following examples from the "Drupal 7 Module Development" book as well as from the Examples module, so I can't see what I'm missing.

Thanks.

$form_state['values']['field_video_reference']['und'][0]['target_id'] looks wrong to me.

I would expect the value to be in $form_state['values']['field_video_reference'].

If you haven't already then install the Devel module and then use can use dpm($form_state); to output the array to the message area and inspect it to find the correct path.

Sometimes for ajax requests Devel Debug Log is also useful as it allows you to send a dump of a variable to a log so you can inspect it even if it is not possible to send content to the message area.


How to turn multi-value image field into a UL I have a multi-value image field.  I want to output the images in a UL/LI.  Should I add a prefix and suffix in preprocess_field?

You could certainly do it with a preprocess function...or you could install the Fences module and do it through the UI:

  Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.


How can I display a block as a node? I've got a modules that supplies a bunch of blocks. I'd like to be able to display them individually as stand-alone pages. I can embed them into nodes, but then I'll need to create each node manually. Ideally I'd just create a menu entry specifying which specific block I'd like to display.

Is there anything out there that can do that? I'm looking for basically the inverse of http://drupal.org/project/nodeblock.

Thanks.

I would do this from my custom module. I would create a men path and a page callback which renders the block.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['my/block/path'] = array(
        'title' => 'Block As A Page',
        'page callback' => 'mymodule_block_as_page',
        'access callback' => TRUE,
    );
    return $items;
}
/**
 * Page callback the path for my/block/path
 */
function mymodule_block_as_page(){
    $block = module_invoke('module_name', 'block_view', 'module_delta');
    return $block['content'];
}

If you go to the path my/block/path, you will see your block as a page/node.


Swap prices in Ubercart based on Attribute price I am implementing a down-payment/multi-pay option on a higher-priced product, and I want to offer it as an attribute. Let's say the product costs $1,000... I want to be able to offer it at full price like a normal product, but also offer the customer the ability to only pay $500 at the time of purchase. If they choose that $500 option/attribute, their card will be charged for five additional monthly payments ($100 each plus a service fee amount, via the UC Recurring Payments and Subscriptions module) so that they pay the full amount plus fees over that time period.

By default, the Ubercart product attributes simply add their dollar amount to the dollar amount of the product. How can I use the attribute dollar amount instead of the product's dollar amount when that attribute is selected? One workaround would be to add a "no, I want to pay the entire amount now" attribute and price it with the normal product price, but that would not be ideal.

Thanks!

Looks like the Ubercart Ajax Attribute Calculations module will do the trick, at least somewhat... it will change out my product's "$0" base price for the attribute price, but it still does not technically "swap" the prices.


Creating an “unzip” custom module I am creating a website that will allow users to upload projects. Project submissions will consist of .zip file. Once the user uploads their project, I need to unzip the .zip file and find the .html file . Also, it needs to be possible to upload these projects through the web interface "Add New Content" and through Node.create by way of the services module.
note I'm using the PclZip library.
This is part of the code I use when the uploaded file but it does not extract the file

function custom_unzip_node_submit($node, $form, &$form_state) {
    if ($node->type == 'flipper') {
    $p_zipname = base_path() .'sites/default/files'.$form_state["complete form"]["#node"]->field_file["und"][0]["filename"];
    $to_extract = base_path() . 'test/';

    $zip = new PclZip($p_zipname);
    $ar = $zip->extract(PCLZIP_OPT_PATH, $to_extract);

    }
}

Keep in mind Drupal 7 has a built in library for working with archive files.

Archiver Zip

See also system.archiver.inc

Perhaps you'll have more success using that.

Lastly, make sure the path to the uploaded file is correct for extraction.


User contributed image gallery, per node Working on a new Drupal 7 based site.  Put together a few sites back in the 5 days, but lots has changed.

I'm looking to allow users to upload images to a particular content type, and to show those images as a gallery.  Restated - I'd like user X to be able to create a node, and then users X, Y, Z, P, D, and Q to each be able to upload images to that node.  (Looking to the future, I want people to vote on images, but let's keep it simple, for the moment.)

My sense at this point is that I have to create an entity type for image, use entity reference to point from the images to their parent node, and use views and probably eva to show the galleries on the parent node.

Question 1: Am on the right track here?

Question 2: How should I handle the 'allow anyone to upload images' piece?  I'd like there to be a rather simple opportunity, when a user is viewing a parent node, to upload an image or provide an image url, and for the image node to be created and appropriately associated.

Thanks for any help.

You could just use the modules:
http://drupal.org/project/references
and
http://drupal.org/project/nodereference_url

This would work if users create new images as nodes. With the help of the second module you achieve that the relation between image node and parent node is automatically created and it also allows to set a link directly on the parent node (a la: create image for this content).

I don't think that you would need EVA in this case. The view to show all images per parent content is straightforward with one argument based on the relation.

What I describe above is pretty much the way you would have done it in Drupal 6 as well. You might get additional features (and maybe complexity) using the module entity reference and EVA.

Hth.


View title change based on context I have a view that lists nodes of a certain type "TypeA" using their titles (and a link to click on).
The view filters out the current TypeA node from that list using a contextual filter set to Content:ID with a default value passed in through the request URL, and the "Exclude" checkbox ticked.
Consequently, when the currently displayed node is not of TypeA, all nodes of TypeA are listed.

I want the block in which the view is displayed to change title depending on whether I view a node of TypeA or not, as follows:

Node is of TypeA, the title is set to "Other TypeAs"
Otherwise, the title is set to "All TypeAs"

I don't know how to further test the query result for the condition, or change the contextual filter (since I always have a Content:ID passed in) to make that happen.

One possible workaround could be to trigger on the URL path because all nodes of TypeA have a custom URL path (via the Pathauto module) configured.

I am using Drupal 8.4.6, soon to migrate to 8.5.

You can implement a hook in your module. Ex:

/**
 * Update title of block based on the node type currently being viewed.
 *
 * Implements hook_block_view_alter().
 */
function my_module_block_view_alter(&$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  // Only act on the block you want.
  if ($build['#id'] == 'your_block_id') {
    // Attempt to get the current node object from the route.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      if ($node->getType() == 'type_a') {
        $build['#configuration']['label'] = t('Other Type As');
      }
      else {
        $build['#configuration']['label'] = t('All Type As');
      }
    }
  }
}

See api documentation for hook_block_view_alter for more info.


Line Item displays sku in title How do you hide the SKU in the line item display.

It seems to be part of the "Line item label" field on
admin/commerce/config/line-items/product/fields

Theres also no option in the view to change it.

After further inspection, I found in the view that "Rewrite the output of this field" was on to include the sku.


Showing a node edit page with drupal_get_form() and hook_menu() I am using drupal 7 and am stuck at a very basic problem. I would like to simply show the edit page to a known node id. I know there are similar posts but they either didn't work or I didn't understand theme.
My module looks like this:

<?php
/*
 * Show the edid page to a specific nid.
 */

function control_center_menu() {
  $items = array();
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);
  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

However, at test/test I get a bunch of errors:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'node_form' not found or invalid function name in drupal_retrieve_form() (line 795 of /home/christian/workspace/gigs/includes/form.inc).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 629 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Undefined index: #node in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).
Notice: Trying to get property of non-object in menu_form_node_form_alter() (line 630 of /home/christian/workspace/gigs/modules/menu/menu.module).

And instead of the hole form I only get the Menu setting check box and the URL path settings.

What am I doing wrong? I tried hard to find a noob friendly copy past example but didn't find any... Thanks a lot in advance!

hook_menu() is only evaluated when the caches are rebuilt, so the call to module_load_include() won't be called when the path is actually visited.

That hook is only meant for declaring menu items, if there's any logic that needs to be added for a path it should happen in the access callback/page callback like so:

function control_center_menu() {
  $items = array();

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'control_center_test_callback',
    'page arguments' => array('page_node_form', $node),
    'access callback' => TRUE,
  );
  return $items;
}

function control_center_test_callback() {
  module_load_include('inc', 'node', 'node.pages');
  $nid = '4';
  $node = node_load($nid);

  return drupal_get_form('page_node_form', $node);
}

Since you're forwarding to a static node edit page though, it might be easier just to set the page callback to drupal_goto() and hardcode the URL:

function control_center_menu() {
  $items = array();

  $items['test/test'] = array(
    'title' => 'Edit this node',
    'description' => 'Edit this node.',
    'page callback' => 'drupal_goto',
    'page arguments' => array('node/4/edit'),
    'access callback' => TRUE,
  );
  return $items;
}


Test doesn't show up I have created a test orb.test for my module and placed it within the module directory. Installed the Simple Test module. When I visit the /admin/config/development/testing my test orb.test its not listed. Here is the code for my test

class OrbTestCase extends DrupalWebTestCase {
  protected $privileged_user;

public static function getInfo() {
  return array(
    'name' => 'Orb Test Case',
    'description' => 'Ensure that Online Booking functions properly',
    'group' => 'Examples',
  );
}

public function setUp() {
    parent::setUp('orb');
    $this->privileged_user = $this->drupalCreateUser(array('allow online  reservations'));
    $this->drupalLogin($this->privileged_user);
}

public function testorbroomavailability() {
  $this->drupalGet('orb');
  $this->assertText('Room Status');
}
}

Have I missed something here?

EDIT 5th August 2014:
My tests written and placed in of my modules do not show up in the list of tests (admin/config/development/testing)

Your test class look OK.

There is no need to install or enable the Simple test module if you're using Drupal 7.  Instead, you should enable the core Testing module.  (Don't know if installing Simple test will make a difference, but it were not present when I went through the routine described below.)

Provided it exists inside your module's directory, you're using Drupal 7, have enabled the core Testing module, cleared the cache, and made sure to declare your test file with the correct name in your module's .info-file, nothing should stop it from appearing in the list included in the "Examples" group when you visit /admin/config/development/testing.

Here is how it looks on my site (after I've gone through the steps outlined above):


Image height/width not saved using CKEditor and Full HTML input format I just upgraded a Drupal site from 5.22 to 6.22.  Everything is working except for one small problem.  I replaced FCKEditor with CKEditor using CKFinder to manage file uploads.

The problem is that when I insert an image into the CKEditor and adjust the width/height, it is not saved.

I am using Full HTML for the input format, so I don't understand why it's not working.

Looks like this might be a known issue. See this thread for info: http://drupal.org/node/731068


How do I programmatically disable/enable a block? I have the following code but its not disbling the block. It remains active and visible on the sidebar where i have placed it.

$theme="themename";
$block="client-block-1938";
$module="modulename";
$region="right_top_box";
db_merge('block')
        ->key(array('theme' => $theme, 'delta' => $block, 'module' => $module))
        ->fields(
                       array(
                              'region' => $region,
                              'status' => 0,
                              'visibility' => 0,
                           )
             )
->execute();
cache_clear_all();

Use db_update.

db_update('block')
   ->fields(array(
     'status' => 0,
     'weight' => -10,
     'region' => 'disabled',
   ))
   ->condition('module', 'modulename')
   ->condition('delta', 'modulename_delta')
   ->execute();


Should I source control contribed modules in my project? I've been told that while developing I should source control everything under sites/ into my code repository (e.g SVN).

Assuming I'll never touch any of the contrib modules I use (ctools, views etc) but will only create my own theme, should I still do that?

Or should I just source control everything under sites/all/themes/?

thanks

In my team, we have moved to only sourcing what is specific to our current project. If we are using Views for example, we add the appropriate entry to our drush make-file, and version that, but not the module itself.

This leaves us with a very small repository, consisting of any custom modules specific to the current site, the current theme, and features exports.

Unless you absolutely can't use drush and drush make, I don't see why one should version control code that is well versioned somewhere else. And if you intend to hack on one of modules, then you should add that as a submodule, again, not versioning the code in your own repo. (I believe this is called a vendor branch in SVN).

Edit: For more details and a more advanced setup, you can take a look at this repository: git@github.com:letharion/Drupal-build-scripts.git The scripts are written in bash to support my teams workflow which includes a building a base-install profile (NodeStream), then our site-specific profile on top of that, a make file for each profile, hooks for applying patches or making other changes on individual build steps etc. I hope I will find the time to re-write it as a drush extension in the near future.


Drupal 7 views, filter by owner I need to show the list of the content created by the currently logged-in user.
How do I do this with the Views module?

Create View on Content, and click "save and edit".
Add necessary fields. Title, body, post date, etc.
Expand the "Advanced" pane.
Add new Contextual filter.
Check "Content: Author uid"
When the filter value is NOT in the URL -> Provide default value  ->  User ID from logged in user (if you are putting this View in profile pages, better choose "User ID from URL")
Apply and save.
:)

Update:

Here is a short list for Views 2:

Create a View on node as primary table.
Add necessary fields as you want.
Click Add new argument(Little plus sign under arguments pane).
Check "User: UID" and click add.
When the argument is not given, choose to use a default argument, and set it to logged in user.

Update 2:

If you want to restrict access to own content, see https://drupal.stackexchange.com/a/41899/1899


How to noindex comment/reply in Drupal 7 I use Drupal 7, and I am trying to use the "noindex" meta tag to prevent http://example.com/comment/reply/43/738 from being indexed by search engines.

The comment/reply page is being indexed, even though I've used the following role in robots.txt:

Disallow: /comment/reply/

In which template file will I need to incorporate "noindex" meta tag for /comment/reply/ pages?

You can use any of this code in robots.txt:

User-agent: *
Disallow: /*comment

This will neglect every URL that contains comment.

You can also use the following, to neglect every URL containing /comment.

User-agent: *
Disallow: /comment/reply

User-agent: *
Disallow: /comment

After you do this, check whether it is working or not by using the Google Robots.txt checker.


contact page with some texts, a form & google map I would like to have contact page which displays information about address, phone, email and some texts. + a contact form + a Google map showing location.
Please let me know how the above is achieved. Thanks

The best way is to use webforms to create your contact form. Make sure to use the option of creating the webform in a block. Create two more blocks. One containing the address and contact and the other containing your map.

And using like panels or a page. arrange your blocks on that page.


How to show a list of article titles I am a bit confused. I understand what teaser does(shows the title and a preview and maybe some other things of an article). How do I not show a preview of the article.

I just want title and possibly author. My aim is to have a frontpage/homepage that only shows a list of titles.

I don't like the look of the article preview.

Still sorta new to Drupal hoping for an in depth explanation as well.

Your best option is the Views Module:

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

create a new view as a Page with Fields
add whichever fields you want displayed
assign that page address as the front page under /admin/config/system/site-information


Ubercart show Prices without Tax For specific Role I need to show prices without tax for specific user role. Other available roles should see prices with included tax.
How I can achieve this behavior?

ubercart adds taxes in hook_entity_view_alter( uc_taxes_entity_view_alter)

So I implement hook_entity_view_alter in my module

function mymodule_entity_view_alter(&$build, $entity_type) {
  global $user;

  if($user && in_array(constant('SOME_USER_ROLE'), $user->roles)) {
    return;
  }

  // ...
}

Also unimplement uc_taxes implemetation of hook_entity_view_alter using hook_module_implements_alter

function mymodule_module_implements_alter(&$implementations, $hook) {
  if (in_array($hook, array( 'entity_view_alter'))) {
    unset($implementations['uc_taxes']);
  }
}


How to put site in 'Safe-Mode' to troubleshoot Drupal if site encounters problem? If site goes caput. Quite a few modules have been installed. Site was running perfectly fine until you need to upgrade a few dozen modules now. (I have not been updating my drupal site for quite a few months - imagine how many modules needs updating!) Update was ran, site stopped working. I don't know where to start troubleshooting. Site would not even go to admin/structure pages. It just refuses to cooperate.

I feel there should be a way. Like, looking from the database itself what tables should I delete (should I delete module tables? Would this not entertain more problems?), or is there any specific tables I should look at only and safely delete the contents that should force Drupal to run in 'safe-mode'?

I guess there should be a safe-mode option for Drupal in cases like these but if none, what is the best course of action to put it into 'safe-mode'.

Notes:

I have searched in "advise for managing and troubleshooting modules" but this is not enough for me.
"Drupal error. Drupal safe mode possible?" also is closer but I don't know how to use drush or at least as far as I know drush is difficult on windows.

First of all, I reccomend you install drush. It provides a ton of handy command line operations for Drupal that will allow you to do things if your site goes belly-up.

You should troubleshoot by turning off modules with drush
pm-disable. Look in your error logs to see if any modules in
particular are the culprit.
You can also enable and disable modules in the database, instructions
are here. You can also get some major issues if you move a
module to another location and don't rebuild the module registry,
which can be done with drush rr.
Make a backup of your DB (and in general, ensure backups are made on
a regular basis) before doing anything. Do NOT drop any tables or
delete any rows if you don't know what you're doing!

When doing updates, I would advise that you update each module one at a time in a development version of your site, using drush pm-update. Once the module is updated, run drush updatedb and also drush cc all, then check around the site quickly to make sure no major errors have occured.

Generally it's best to do core, then security updates, then version updates. It's also worth checking the version jump (especially with important modules such as Features, or Context) and making sure there are no drastic changes. As an example, Features 2 recently changed the way it stored field settings and it requires some clean up operations that will have to be done manually.

So take great care when updating modules!


No change upon editing node.tpl.php I have a view where I am displaying nodes using row style Node. I want to edit the way the Node row style.

I edited the file /modules/node/node.tpl.php and commented the line

print $picture;

just for testing.

I was expecting that the picture field of each node would vanish. But I saw no change in the view display. Why is this?

The documentation for the plugin says:

  The node row style will display each item of the view through Drupal's standard node_view() function. Views has very little control over this output, except for the options you see.  You can choose from different Build modes. By default there are "Teaser" and "Full node". You can also decide if you want to "Display links" and/or "Display node comments".

  Because the output is run through the standard node template mechanism (typically node.tpl.php or a variant thereof), any decisions about what is output may be done there.

  Views does add an extra 'suggestion' to the list of possible node templates: node-view-VIEWNAME.tpl.php—you may use this to theme a node specifically for the view. This can be handy for creating very small teasers and the like.

The template file could be different from node.tpl.php if there are other template files suggested for the content type, or a node in particular; the Views module itself suggests a template file whose name depends from the view name. Then, between the node.tpl.php defined from the Node module, and the same file defined from the theme, the latter is the used one.

The rendering method use for that plugin is views_plugin_row::render(), which contains the following code.

return theme($this->theme_functions(), $this->view, $this->options, $row, isset($this->field_alias) ? $this->field_alias : '');

With Drupal 7, the method is views_plugin_row_node_view::render(), which contains the following code.

  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }

References

The documentation page for views_plugin_row_node_view (Drupal 6)
The documentation page for views_plugin_row_node_view (Drupal 7)


How do I avoid the "too many connections" error message is shown? How do I avoid the following error message is shown to normal users?

  PDOException: SQLSTATE[HY000] [1040] Too many connections in lock_may_be_available()

There are two issues here:

Users are seeing site error messages that they shouldn't
The error message itself

For 1, go to admin/config/development/logging and set Error messages to display to None.  Don't worry, this won't affect messages like "incorrect login details" or "page not found, we did a search instead" ... things that the user really needs to know.

As for 2, here are a couple of things to try:

Turn off all your custom modules if you have any, re-enable them one by one to see if you can find the cause
Do the same with contributed modules
Read up on the error message, there are too many things that could be causing it that are non-drupal specific to be useful on this site.


How to Unit Test Entity Reference Field Value I have been tasked with writing a Unit Test for a method where I pass in a Node object, modify an Entity Reference field value, and then return a Node object.

Since this is a Unit test, I am unsure as to how to write an assertion.

Note: just included relevant code.

class ClassIAmTesting {
    public function populateSymbols(Node $node) {

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
      return $node;
    }
}

I have created a mock for the Entity Reference Field:

$entityReferenceMock = $this->getMockBuilder(EntityReferenceFieldItemList::class)
      ->disableOriginalConstructor()
      ->setMethods(['appendItem'])
      ->getMock();

I have also created a mock of the Node Object

$nodeMock = $this->getMockBuilder(Node::class)
      ->disableOriginalConstructor()
      ->getMock();

$nodeMock->expects($this->any)
      ->method('__get')
      ->with('field_symbols_in_this_story')
      ->willReturn($entityReferenceMock);

The method returns a Node object but how can I assert that the Entity Reference Field Value has changed?

Edit: The class with more details:

class ClassIAmTesting {
  public function populateSymbols(Node $node) {

    $body = $node->field_body->value;

    $dom = Html::load($body);
    $xpath = new \DOMXPath($dom);

    foreach ($xpath->query('//span[@class="tooltip"]') as $xpathNode) {

      $symbol_id = $xpathNode->getAttribute('data-symbol');

      $node->field_symbols->appendItem(['target_id' => $symbol_id]);
    }

    return $node;
  }
}

This is a good example of a test that would probably be better suited as a kernel test rather than a unit test since it's dealing with the Field API which can get tricky to mock, and is probably better to test with the real thing.

To test this as a kernel test you need to ensure the following:

Either create your field field_symbols directly in the test's setUp method or place the field config and storage YAML files in a module's config/install directory, and enable that module for the test.

You'll need to also enable the node module, and any other module's that your code depends on

Then, in your test you can execute the custom code and ensure the expected values are set:

public function testFieldSymbols() {
  $node = $this->createNode();

   // Do this, or retrieve the service if your class is a service.
   $fixture = new ClassIAmTesting();

   $fixture->populateSymbols($node);

   $this->assertEquals('expected field value', $node->field_symbols->target_id);


Is it possible with Drupal Views to have AND and OR in a filter set? I am attempting to build a view with four filters (A, B, C, D). With Views 3 it is possible to select whether you want these filters to be chained with AND statements or OR statements. Is there a way to configure views so as to chain some of them with AND and others with OR?

For example, ending up with a query that is similar to:

SELECT *
FROM {table}
WHERE A = 0
  AND B = 0
  AND (C = 1 OR D = 1)`

Looks like this is entirely possible with the Views 3.x branch. You can create custom Filter groups directly in the Views UI itself, and set the AND/OR for each group separately.


How to import a template file with HTML markup to use for sending email notifications? I want to send the email notifications to users of the site. I have a basic template file with the HTML markup I want to send in the email.

How do I import that HTML file (which is in the root folder of the project) in my module?

If the module doesn't allow importing it, just copy the markup and put it in your relevant Email template, inside your module.

Otherwise, add such importing option by customizing to module, or try another.


Get the name of file from file field before node is saved There is a file upload field(which uploads zip files) . I want to get the name of file in node_presave , How do I do it?

try some thing like

function module_node_presave($node)
{
   if($node->type=='article'){

       $file = file_load($node->field_zip['und'][0]['fid']);
       dpm($file->filename);
   }
}


How to redirect according to URL parameter after form submission Currently I'm using Drupal as my authentication system, and I would like to redirect user to our main site after login, according to an URL-passed parameter, for example user/login?redir=http://google.com. And yes I've found out there is a destination parameter however it doesn't work it the passed argument begins with http or somehow a non-Drupal path. Any ideas? hook_drupal_goto_alter is a hook I found might be helpful, but not sure how to implement it.

The issue with ?destination= is that it provides no mechanism for setting external => TRUE for the options in drupal_goto(), which Drupal needs to redirect to an off-site location.

I think the easiest way to get what you're looking for is to implement hook_form_alter() for the user login form, save the URL parameter if it's available, and then manually redirect in the submit handler.

Something like this:

function MYMODULE_form_user_login_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['redir'])) {
    $form['redir'] = array(
      '#type' => 'value',
      '#value' => $_GET['redir']
    );

    $form['#submit'][] = 'MYMODULE_user_login_redirect';
  }
}

function MYMODULE_user_login_redirect(&$form, &$form_state) {
  $form_state['redirect'] = array($form_state['values']['redir'], array('external' => TRUE));
}


theme_field() not working in a module Writing in to custom.module:

function custom_field($variables) {
  dpm($variables)
}

Returns nothing is it working in a module? And i have devel installed and turned on

You can only use that method to override a theme function in a theme (template.php).

To override the callback function for a theme using a module, you need to implement hook_theme_registry_alter(), e.g.

function MYMODULE_theme_reigstry_alter(&$registry) {
  $registry['field']['function'] = 'MYMODULE_theme_field_override';
}

You might need to change other things too (file path, preprocess functions, process functions, etc, depends on your use case). The above method will help with all of that too.


HTML in webform labels I need to insert HTML markup (spans, classes, h2 tags). However, webform appears to be filtering out all markup from labels. Has anybody succeeded in inserting html markup in labels, and how did you do that?

You won't be able to use HTML markup within the label inputs within the Webform module itself, as it most likely cleans out all HTML markup before displaying to the user to prevent XSS attacks etc.

Most likely you'll need to write a small custom module which implements hook_form_alter, which will allow you to change the markup used for the labels.

I'm not actually sure if Drupal will allow markup within the #title attribute of your form elements, so you might need to use the #prefix property instead to add your custom HTML replacement labels.

If this is all Greek to you then you'll probably need to checkout these tutorials:

Creating modules - a tutorial: Drupal 7.x

Hook snippets: hook_form_alter


Which module can I use to visualize Drupal log data in the format of a chart? I installed Better Statistics and Syslog Access. I wonder if there is a module that can take this data and visualize it like a graph, pie chart, etc? I found one but it's a service, any suggestions?

Native charting modules

Have a look at the Comparison of Charting modules. Here is a quote from it:

  There are a variety of modules that facilitate the creation of charts. When it comes to charting in Drupal, the saying "There's a module for it" doesn't really apply. In this case, it's more accurate to say, "There are plenty of modules for it" ...

  These modules support for various charting libraries that may be desirable based on a site's desired appearance, feature-set, and licensing needs.

Here is the shortlist of 'native' charting modules, for which at least 1 official release exist (quote from that comparison also):

Forena facilitates the creation of charts  by using the SVG Graph library. Forena does not depend on Views for creating charts, however it can be used as an extra views style plugin.
Google Chart Tools provides a simple API to build interactive SVG charts, using the Google Chart Tools.
Chart currently only supports the deprecated Google Chart Tools: Image Charts, which is deprecated as of April 20, 2015. Though issues #2371567, #2371075 and #2368793 are about addressing that. It is the most commonly used charting module today (over 25K reported installs, which is more then double of all other native charting modules together).
Charts (not to be confused with the charting module with namespace chart !!!) provides an API that can be used as a stand-alone API, and the integration with Views supports building charts with no coding.
Charts and Graphs, which is an API for developers. It can be extended by third-party modules that want to add their own charting implementations. It does nothing by itself. It should only be installed if some other module requires it. Views Charts is one of the modules using it.
Flot provides an API and views integration for using the Flot graphing library.

Note: there are quite a few additional 'native' charting modules, though they do not have an official release (yet), only dev, alfa or beta versions.

Forena showcase

Have a look at my answer to "Views Table with Taxonomy Terms for Columns and Rows", which details how I once created a crosstab report (using the Forena module) that looked like so:

Then look at the video demo "How to create Crosstab Tables and (related) charts" to get an idea what it takes to create a chart from such crosstab tables.

Disclosure: I'm the author of the comparison and co-maintainer of the Charts, Chart and Forena.


Removing the active language I'm having some trouble with removing the active language from the Language Switcher Dropdown module. I'm trying to override theme_languageicons_icon() with the following code, but it doesn't seem to work.

function themename_languageicons_icon(&$variables) {
  global $language;

  foreach ($variables as $varKey => $value) {
    if ($variables['language']->language == $language->language) {
      unset($variables[$varKey]);
      break;
    }
  }

  return theme('links', $variables);
}

Do you have any idea on how to achieve this? I don't want to disable the active language using CSS since I'm having different style properties for the first-child and last-child of the list.

For a similar problem (removing the language switch links for non-translated equivalent pages), I've implemented hook_language_switch_links_alter() in my theme.

Although I haven't tried it out myself, I think the code example will point you in the right direction. Instead of setting an 'active-language' class attribute, you can unset the link.

function mymodule_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  if ($type == LANGUAGE_TYPE_CONTENT && isset($links[$language->language])) {
    foreach ($links[$language->language] as $link) {
      $link['attributes']['class'][] = 'active-language';
    }
  }
}


Is there a generic method to retrieve entity IDs? I have seen this code suggesting how to return a list of entity IDs:

$query = \Drupal::entityQuery('node');
$query->condition('type', $bundle);
$entity_ids = $query->execute();

but this requires the knowledge of when to use "type" or what "type" is. For example, for user entity i would think setting type to $bundle = 'user' would work - but it gives error.

for terms from a vocab i would expect type to be set to the name of the vocab; but that also gives an error.

Is there a generic method to call for entity_type that would hint at what is required to do a query for entity ids?

You're looking for the bundle key, which can be obtained from the entity type:

$entity_type = 'node';

// Load the entity type definition and get its keys.
$keys = \Drupal::entityTypeManager()
  ->getDefinition($entity_type)
  ->getKeys();

$query = \Drupal::entityQuery($entity_type);

// 'bundle' is optional, if not provided it will be the same as the entity type ID,
// but obviously you won't need to use it as a condition.
if (mb_strlen($keys['bundle'])) {
  $query->condition($keys['bundle'], $bundle);
}

$entity_ids = $query->execute();

See EntityType::getKeys() for more information.


Seeking iPhone/iPad JavaScript/jQuery libs, techniques & tutorials Client wants iPad & iPhone support for a webapp that has at least one form where DOM elements are dragged around on a (Raphael) Canvas (JavaScript rendered graphic).

Currently, the touch-unfriendly interface to drag items around uses mouse-hover and other mouse states to handle the drag-items interface. I know I'll need a completely different approach for touch screen devices, and am wondering if any fellow Drupal developers have posted their breadcrumbs as they faced this.

Drupal 6 or Drupal 7 does not matter, since this is at the JavaScript layer unless the possible solution requires jQuery only available in Drupal 7.

The only thing that I know of that's close to what you want is on Eric London's Drupal blog where he talks about themes and redirects for mobile versions of Drupal websites.  I'd be interested in knowing more about this too, sorry that I couldn't be of more help.


pager is not working when print views I've created one view with used of php code for some fields in it, and set pager on it too. It's working fine whenever i created given link of view but actually I print that same view on another basic page, using this php code:

<?php print views_embed_view($viewName); ?>

on that basic page pager is not working, because on that page the pager link is generated with that basic page url link not with views url link. can anyone give solution when i print the same view on basic page and also pager can work over there perfect?

Thanks in advance :)

If you used Views PHP, this is a known issue

Views Pager is hidden (7.x-2.x)

Pager disappears when Global: PHP used in Views 3.8

You have to apply one of the patches to fix it.


Views alter changes next row instead of current one I have a view that is showing event content types. Users can apply for these events. I am using a hook to alter the 'view applicants' so I can show how many applications already excist.

The following code works and shows the values but is somehow skipping the first row and printing all the values one row later.

function frontview_general_preprocess_views_view_field(&$vars) {

  $view = $vars['view'];

  if(isset($vars['view']) && ($vars['view']->id() == 'evenementen') && ($vars['view']->current_display == 'accreditaties_overzicht')) {

    if($vars['field']->options['id'] ==='nothing_1') {

      // Getting the values
      $accreditaties = $vars['row']->_entity->get('field_accreditaties');
      $accreditaties = $accreditaties->getValue('list');
      $amount = count($accreditaties);

      $vars['field']->options['alter']['text'] = 'View Applicants ('. $amount .')';
    }

  }
}

This is my current output, the first row still shows the normal values without the hook but the first row values are printed on the second row, second row on third row, ...

This is the output that I need

I'm not sure why it's doing that, when I dd() my code it looks fine.

Thanks in advance!

*Drupal 8

Got it to work with the following code. I needed to output the changed value in the $vars['output']. This would override the url in the nothing_1 field so I then had to create a new link and use that to alter the original value.

/**
 * Implements hook_preprocess_views_view_field().
 */
function frontview_general_preprocess_views_view_field(&$vars) {

  $view = $vars['view'];

  if(isset($vars['view']) && ($vars['view']->id() == 'evenementen') && ($vars['view']->current_display == 'accreditaties_overzicht')) {

    if($vars['field']->options['id'] ==='nothing_1') {
      $accreditaties = $vars['row']->_entity->get('field_accreditaties');
      $accreditaties = $accreditaties->getValue('list');
      $amount = count($accreditaties);

      // $vars['field']->options['alter']['text'] = 'View Applicants ('. $amount .')';

      $nid_value = $vars['row']->nid;
      $url = Link::fromTextAndUrl(t('View Applicants ('. $amount .')'), Url::fromRoute('view.evenementen.page_2', ['arg_0' => $nid_value]))->toString();

      $vars['output'] = $url;
    }
  }
}


Modify Default search to phrase search Is there a way to change the default search settings of the built in search module to default search to phrase match?

Phrase search as in by default terms would be searched with exact match:

"foo bar" over "foo" "bar"

The client doesn't seem to like the way the out of the box search works.

Even if it's kind of hacky you could do a hook_form_alter, set a submit function before the default one and look at the form input. Then wrap it with "" if it's not there already.

So what you need is

a custom module
hook_form_alter
Register a '#submit' function
Alter the value $form_state['values']


Render fields in a custom bean.tpl.php I have a custom tpl for bean block called: block--bean--image-footer-block.tpl.php, also I have custom tpl for both fields:

field--title-field--footer-block.tpl.php
field--field-block-footer-imagen--footer-block.tpl.php

I don't want to use the default <?php print render($content); ?>

But If I try to use

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

or

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

I get this error

Fatal error: Only variables can be passed by reference in

The beans fields are:

title_field
field_block_footer_imagen

Any idea to print both fields?

Thanks

Oskar

Note, to avoid getting the 'pass by reference' error, assign the output to a variable before passing it in as an argument to the render() or drupal_render() functions

Partial Solution, without preserving display settings

For reference, I tried:
How do I render a field value including its format?

Which gave me something similar to:

<?php
$banner = field_view_field('bean', $bean, 'field_banner_image')
echo render($banner);
?>

The only problem being that it was ignoring my output display formatting I had set on the block type. You can specify one, but I couldn't find a source readily available with the values of the $display array which would be passed as 4th parameter to field_view_field.

Full solution, preserving display settings

Since I wanted to preserve the setting specified by the configuration of the field, and not rely on display defaults (ie: showing the label above an image) I looked back at the bean.tpl.php. Within the content they were building the $elements array, and using drupal_render. Giving this a shot and it worked:

<?php
$banner = $elements['field_banner_image'];
echo drupal_render($banner);
?>

This also preserved my removal of the field label.

This was all done within my bean--banner.tpl.php which should be a similar setup to what you're facing. Hope this helped!


Taxonomy term empty fields in a ALL vocabulary I have this "screen" when I click on "manage fields" for all of my taxonomy vocabularies (new included):

All these "fields" empty. And I have no these fields.

It's an issue caused by the Commerce Services module version 7.x-1.x-dev (25-Apr-2014): https://www.drupal.org/node/2024813


views - get teasers of "related nodes" referenced in entity fields on current node I have a content type 'Article' which has a custom field of 'related articles'. This field uses the Entity Reference module and allows an admin to specify up to 4 related articles (nodes) to be shown on that page.

I'm trying to create a view block to display the teasers of those related articles on the page.

I'm struggling to set-up the view.

So far I've got it as:

The plan is that this view will be attached to an existing view which just shows the latest articles.

The view at the moment doesn't seem to be referencing the entity field (Related Articles) or showing those items...

Probably missing something obvious but would appreciate any pointers.

Don't use an Entity Reference relationship for this, but rather, change your Show: to "Fields" and add the referenced entity field. Then you will be able to set the "Formatter" to "Rendered entity", and the "View mode" to "Teaser".

You may need to add a contextual filter or set this up as an attachment display rather than a block.

I can post a few screen shots if my answer isn't clear.


Translate "Order total" I have translated my site into Japanese using all the required modules and po files.

But now I'm not able to translate the text "Order total" which appears in Checkout process.

I tried applying patches as suggested here but it didn't help me. Please tell me how to change this text.

This post discusses the very same issue. Also, as mentioned in this comment,

  1) You have to go to this page admin/config/regional/i18n/strings And
  set the language to english..than the translation strings can be made
  to your language.

  2) You need to go to admin/config/regional/translate/i18n_string and
  enable

  Select text groups  Fields 3) Then the fields are between the normal
  translation page to be able to translate:
  admin/config/regional/translate/translate

  4) After adding translation and nothing showing, back to
  admin/config/regional/translate/i18n_string Enable Fields and click
  REFRESH.

Hope this helps.


How to render HTML of entity? I have created my custom entities using Entity Construction Kit module.

Is it possible to  render an HTML output of entity programatically? So I could display an entity for example in block?

I have found function entity_view, but it returns only array, not whole HTML output.

For now, I am using Views to achieve this. I create a view that displays one instance, and  I am using function view_embed_view to display HTML.

But is there any direct function, so I don't need to create a view?

If you've got it working with entity_view, you probably just need to use:

print render($entity);

where $entity is the render array returned from entity_view.


Target different database for a single query? Can I set the target database on a db_select()?

Example:

$result = db_select('table', 't')->fields('t')->db_target('db_name')->execute();

One can use db_set_active() to change to which database a query should be sent, but that requires one to manually "reset" the active db, which is a potential cause of bugs.

From the comments above such as from @Clive, I do this alll the time:

$count_query = Database::getConnection('default', 'dew_remote_sources')
               ->select('survey', 's');
$count_query->addExpression('COUNT(DISTINCT(survey_number))', 'cnt');

For this to work you need to have various databases defined in your $databases value of settings.php (or you can add additional $databases[key] values to top of your module sometimes, or create such a connection on-the-fly using:

Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'migration_database',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
));

You see this pattern alot in the Migrate documentation pages, migrate examples and 3rd party modules that have implemented migrations. Because you are literally moving content from DatabaseX to DatabaseY alot and switching around with db_set_active can easily lead to confusion in such cases with the Object Oriented nature of the Migrate module.


Get tid as integer from tid array returned by EntityFieldQuery I am using an EntityFieldQuery to return an array of taxonomy terms matching a provided custom field value. Using the example given in this question, I wrote a function that accepts the vocabulary, field name, and field value as arguments and returns an array of matching terms. That works perfectly, but what I really want to get back is just the integer values corresponding to the matching terms, not the array of terms.

The problem is, the data structure that's being returned looks like this:

Array
(
    [6] => stdClass Object
        (
            [tid] => 6
            [vocabulary_machine_name] => features_of_interest
        )

)

for one item, and for another:

Array
(
    [79] => stdClass Object
        (
            [tid] => 79
            [vocabulary_machine_name] => features_of_interest
        )

)

Because of this, I can't see how to isolate the [tid] value (6 or 79 in the examples). I'd like to be able to say

$int_tid = $terms[XXX]['tid'];

but I can't get my head around whatever syntax is needed.

I've pasted my function below in case it helps. Ideally I would like to loop through the array of items, isolate each term ID value as an integer, and push it onto an array which the function would then return.

  function get_tids_from_custom_field($vocabulary, $field, $value) {

    $vocab_machine_name = taxonomy_vocabulary_machine_name_load($vocabulary);
    $query = new EntityFieldQuery();
    $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', $vocabulary)
      ->propertyCondition('vid', $vocab_machine_name->vid)
      ->fieldCondition($field, 'value', $value, '=');

    $terms = $query->execute();
    $int_ids = array();

    foreach ($terms as $term) {
      dpm($term);
      array_push($int_ids, $term);
    }
    return $int_ids;
 }

The standard(?) pattern to get ids from a query over a single entity type is to use array_keys().  Something like this:

function get_tids_from_custom_field($vocabulary, $field, $value) {
  $vocab_machine_name = taxonomy_vocabulary_machine_name_load($vocabulary);
  $query = new EntityFieldQuery();
  $query
    ->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', $vocabulary)
    ->propertyCondition('vid', $vocab_machine_name->vid)
    ->fieldCondition($field, 'value', $value, '=');

  $results = $query->execute();

  return !empty($results['taxonomy_term']) ? array_keys($results['taxonomy_term']) : array();
}

The results array is keyed by the entity ID.


I want my users to login through 'Last Name', rather than 'Password' I would like my users to log in through 'Email' and 'Last Name', rather than 'User Name' and 'Password'. I did manage to swap 'User Name' with 'Email', but I cannot replace 'Password' with the user's 'Last Name'.

I have added another customer profile with two new fields, i.e., 'First Name' and 'Last Name' and now want the field 'Last Name' to be used in place of 'Password'.

I tried everything. Any help or guideline will be highly appreciated.

You can do this by using a module called String overrides to redefine the strings exposed to your users during login and on their profile page.

Navigate to Administration » Configuration » Regional and language  » String overrides and fille in the following and click "Save configuration":

Now, login will look like this to your users:

Note that this just renames the fields.  This means that the last name will not have its own field and it will not be displayed on the user's profile page.  It is not clear from your question whether this will be a problem.

However, if you want a real "Last name" field, and you want to use this field for authentication, you can do this by creating a small module that uses hook_form_FORM_ID_alter() to make a couple of changes to the login form:

Hide the password field.
Add "Last name" as a field.

Now, in the form validation, check that the value of the "Last name" field matches the last name in the user's profile, and if it does, fill in the hidden password field with the correct password.  If you use the same password for all users in this set up, it can be hard-coded in your form validation.  This will make Drupal take care of all the heavy lifting of creating a session, book-keeping of logins, etc.

As for the (in)security of using the last name instead of a real password as a login credential, I'll take your word for security not being an issue here.  However, I am puzzled by why want this, so I have added a question about it as a comment.


Multiple nodes in a single Views row I have a content type Cars and a content type WheelManufacturer.
Of course a WheelManufactorer node is referenced by a Car node.

I'm trying to create a View (in D8) that will fetch some fields from the Car nodes and some fields from the corresponding WheelManufacturer node.

I'm trying to do that by using relationships in Views... but I have a problem: I can add relationships to, ie Term Reference or Image fields, but not to Entity Reference ones... those fields just don't appear in the list.

Any ideas why?

As far as I've understood, it is actually NOT possible in Drupal 8: https://drupal.org/node/1906806

EDIT: the patch at the above link DOES work for me with the interdiff I just posted, so if you feel adventurous, you can give it a try!


Drupal 7 | Associate dynamic user to a content type I have a  content type "Article", with a field "author".

Is it possible to assign users with "writers" role dynamically with this field ?

The goal is to display in the article node, a link which redirects to the writer(user) profile.

For example :

-Article Title

-MM/DD/YYYY

-Written by : randomWritter (dynamic link)

References module will enable you to do that.

It allows you to create fields and associate them with existing content/users on the site. It also features integration with Views so you can have more complex logic to filter out the available options.
The field can also be displayed as an autocomplete.


How to Render a field collection item in a Twig template in tabular view I have a field collection field having four fields.
I want to display the record in tabular format.
What I have done.
Created a field twig template file.
Added the code like
{% for item in items %}
    <div{{ item.attributes }}>{{ item.content }}</div>
{% endfor %}

Twig file is working properly. But i need to display the content in tabular form.
Coming like

Required

Available Variables

There is not only one twig template, there are three levels of twig templates in a field collection field:

1) The field template for the field-collection field: field--field-collection.html.twig

2) The field-collection template itself: field-collection-item.html.twig

3) The field templates for the fields inside of the field collection: field--field-collection-item--field-field1.html.twig

When you are in the top level, the fields of the field collection are not built yet and you have no access to the rendered fields.

The best approach is probably to put the table structure in all three levels, in 1) the header and footer, in 2) the row and in 3) the cells.

There is one problem with this approach. In 1) you don't have the labels for the header. If you don't want to hardcode them, you can try to get them from the configuration of the field collection in a preprocess hook.


Where are the watchdog logs located or how do I view the errors created? How do I view the watchdog logs that are created? Is there an interface to view them with, or are the logs stored somewhere on the filesystem?

Both Drupal 6 and Drupal 7 put the viewable version of watchdog logs at /admin/reports/dblog. The core database logging module needs to be enabled, and users who want to view them need the access site reports permission. The actual database table is watchdog.


Unable to use a hyphen in a Drupal 7 text field I've got a simple field of type "text", widget = "text field" (Drupal 7).

I am able to use special characters like &(%, but when I try to type a hyphen, there is no result. I can use a rich text field, but I only want plain text.

I am able to use the ASCII code like S&#45;26 where I really just want S-26.

This was not an issue in Drupal 6.

Thanks very much!

The zoom behavior of the map is responsible for this unwanted behavior.
You need to disable keyboard controls on the map in your node edit form.
This could be the default map or the default map installed by geofield.


How to hide terms with no nodes in "Simple Hierarchical Select" in views? I am using a Simple Hierarchical Select as an exposed filter in views.

How would I hide terms that have no nodes from the select box?

There is no simple way to do that without writing custom module to eliminate the terms you wanted. That said, you can write hook_form_alter to achieve this.

/**
 * Implements hook_form_alter
 *
 **/
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'YOUREXPOSEDFORMID') {
    foreach ($form['field_tags_tid']['#options'] as $tid => $term_name) {
      if (is_numeric($tid)) {
        $result_count = db_select('taxonomy_index', 'ti')
        ->fields('ti')
        ->condition('ti.tid', $tid, '=')
        ->execute()
        ->rowCount();

        // Removing the option for tags with no-content
        if (!$result_count) {
          unset($form['field_tags_tid']['#options'][$tid]);
        }
      }
    }
  }
}

NOTE: Here, I assumed field_tags_tid as the field name, should be replaced with the appropriate field name.


Gateway timeout error from proxy server I was recently developed a drupal site for a client who lives in HongKong. The site worked perfectly (is still functional when I access it)
But after deploying it for demo, the client compalained that the site wasnt working and constantly getting a 504 Gateway timeout error.
Apparently the client was on a proxy server (and I'm guessing the problem is due to that factor).
Does anyone know of such problem?? And, of course, the way to fix it?

P.S.

The site is built on Drupal 7.14

This is a screenshot that the client sent me

(The server, while acting as a gateway or a proxy, did not receive a time response from the upstream server it accessed in attempting to complete the request)

Update::

On further investigating with the client, He told me that

The site first worked fine until he logged in as admin and added content.
The timeout error showed when submitting the content form.
After the error, no other page of the site would open.
The site did function when he tried after waiting for a while (he did not account the time he waited)

UPDATE ::

ON checking the error log on the server, I found a bunch of "Page not found errors". But the weird thing is it was looking for a 406 page (for unacceptable header). Any idea why??

[Mon Sep 30 16:45:30 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/404.shtml
[Mon Sep 30 16:45:30 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/favicon.ico
[Mon Sep 30 16:45:29 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/404.shtml
[Mon Sep 30 16:45:29 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/demo
[Mon Sep 30 16:31:17 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/
[Mon Sep 30 16:20:40 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/content/mongolian-heart-live-hongkong-2012
[Mon Sep 30 16:20:13 2013] [error] [client 110.44.113.254] File does not exist: /home/ekmauka/public_html/406.shtml, referer: http://ekmauka.com/ekmauka/node/22/edit

Maybe the PHP memory_limit, after submit content it take a lot of memory for PHP and it die.

You can request they increase memory_limit to check. But to get more information correct, can they give the error.log of webserver and error_log of PHP for easy know what happend.


How to send out email based on matching taxonomy terms in user profiles? I'm using profiles 2 and have (one or many) taxonomy terms that can be selected by a specific profile type.  I have a webform that also has this taxonomy term in the select list.  When the webform is submitted, if it matches one of many taxonomy terms in any of these profiles I want an email sent to those profiles.  I can't figure out how to get Rules to do this.  Any help is appreciated.

This is what I have so far.  I just have it posting a message right now to test, but I want it to email, but I can't find the data I need to compare in the Rules.

{ "rules_webform_email" : {
"LABEL" : "Webform Email",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-3" : "webform-client-form-3" } }
    }
  },
  { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "webform" : "webform" } } } }
],
"DO" : [
  { "drupal_message" : { "message" : "Test submit webform\r\n[data:project_type-value]\r\n[data:project_description-value]" } }
]
}
}

The project_type is the taxonomy term in the webform.  I need to compare it with the field_service_provided (Term Reference field to the same taxonomy vocabulary) in the Profile.

Even though your question doesn't say so, from the format of your exported rule it's clear it is about D7. A possible answer to your question is by replacing the Rules Action in the rule you already have, and by also using the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

3. Create a rule using the view of display type 'Rules'
Replace the Rules Action in your current rule, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.


custom "register" button on a form - problem with redirection How to make a custom register button in the user login form (block) so that it redirects to 'user/register' ?

Currently, when I click my custom "Register" button, the code in _mymodule_register is executed (I debugged), but the page just reloads, it does not go to user/register. I tried both drupal_goto and form redirect, but nothing works.

function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#type' => 'submit',
    '#value' => t('Register'),
    '#submit' => array('_mymodule_register'),
    '#limit_validation_errors' => array(),
  );
}

function _mymodule_register($form, $form_state) {
  $form_state['redirect'] = 'user/register';
  //drupal_goto('user/register');
}

Use below code to achieve the same functionality.

function mymodule_form_user_login_block_alter(&$form, $form_state, $form_id) {
  $form['actions']['register'] = array(
    '#markup' => l('Register', 'user/register'),
  );
}

Theme it using css to look like a button. Done !


Drupal cache expire value of -1? What does a value of -1 mean when it's present in the expire field of a cache entry in the database?  I've honestly looked around and could not find an answer.

It is coming from includes/bootstrap.inc:

/**
 * Indicates that the item should be removed at the next general cache wipe.
 */
define('CACHE_TEMPORARY', -1);

Which is also defined in the docblock for cache_set($cid, $data, $bin, $expire):

  $expire: One of the following values:
   - CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
   - CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
   - A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.


Two Drush bam-backup errors: Command not Found & Could not find a Drupal setting.php file at I am trying to use Drush to backup a standard 7.12 local installation, but I am getting two error messages when running drush bam-backup:

The drush command 'bam-backup' could not be found.
Run `drush cache-clear drush` to clear the commandfile cache
if you have installed new extensions.

Could not find a Drupal settings.php file at ./sites/default/settings.php.

The bam module is enabled in my system.

Regarding the second issue, I have checked in the corresponding directory and it contains a default.settings.php file, but no settings.php file.

Is this a configuration issue, or a more fundamental bug? How can use Drush to backup my installation? Thanks.

P.S.:

I am on Windows 7 and I have used the Windows installer available here to install Drush. The bam version is 7.x-2.2 and Drush version is 5.0-dev.

Where is the settings.php file for your Drupal installation?

The problem Drush is having is that it cannot figure out where your settings.php file is.  By default, Drush only looks in sites/default.  There are a few ways that you can select the site you want if it is not in sites/default.  One is to cd to the directory that contains the settings.php file, then run your command.

cd /path/to/drupal/sites/mysite
drush status

The other way is to specify the site you mean via the --uri parameter:

drush --root=/path/to/drupal --uri=mysite.com status

Once the status command works per the above advice, try calling bam-backup again.


Is it possible to alias paths for contextually generated page views? I have a content type with a path pattern ([category]/[english_title]) that is generated based on its field values.
In the node's page there is a block with referencing news items and a count based more link to a page with more news items.The path generated from the more link is the same as the node's alias but with /news appended to it ([category]/[english_title]/news).

For that I passed the English title as token through a hook to the more link which was fetched from the page side as an argument to be matched against. It was fine until I had some fields with special characters, especially titles with apostrophes of possessive 'S's. I am unsure about how to proceed. An easier way would be since there. There is already a news section to do something like /news?nid, but it got me thinking.

Is it possible to alias contextually generated views pages or substitute an already patterned portion of a URL with its alias?

This is the use scenario behind the Sub-pathauto module. In your scenario, you're creating a "more link" page View with a /node/%/news path and a contextual filter for the NID to retrieve that specific node's contextual news view. With the sub-pathauto module installed, that page view should be viewable via [category]/[english_title]/news alias.


session_unset logs out user when viewing the page We have an application that we developed in Drupal 7 and I am tasked with migrating this form to Drupal 8.  I have a question about the session behavior which seems to have changed from Drupal 7 to 8.

Our application is a node and whenever that node is navigated to, or refreshed, the session is unset and restarted (for security purposes).

function fu_preprocess_node__application(&$vars) {
    session_unset();
    if(session_id() == ''){
        ini_set('session.gc_maxlifetime','28800');
        session_start();
    }
}

In Drupal 7, if I am logged in as an admin user and working on the form and I navigate to the application node to view it, I am fine.  However, in Drupal 8, when I am logged in to Drupal and I wish to view this page, the session_unset() logs me out and gives access denied errors for contentual/render and history/23/read.

What do I need to change so that we can unset the session for the application form but not get logged out as drupal user?  For the typical user of this form, who does not log in as a drupal user, this is not an issue.  But as an admin working on the form, it is an issue.

I was able to combine two of the responses to solve my problem.  I indeed updated it to use the symfony that is now part of drupal 8.  (Comment #3).  Reading https://www.drupal.org/docs/7/security/safely-impersonating-another-user gave me an idea to test for anonymity.  So I ended up changing the original code to:

if(\Drupal::currentUser()->isAnonymous()) {
    $request = \Drupal::request();
    $session = $request->getSession();
    $session->clear();
    if($session->getId() == '') {
        ini_set('session.gc_maxlifetime','28800');
        $session->start();
    }
}

This seemed to make my problem go away.  Not sure if this is the best solution, or a band-aid, but it worked for me.


Wildcard Loader function called multiple times (_load) I have a loader function which is called excessively whenever the user accesses the page. Naturally, I only need it to run once per page request, instead, it is called multiple times. Earlier the _load() ran only twice with MENU_CALLBACK, then I tested it with the default MENU_NORMAL_ITEM and it increased to four. Although I've changed it back, and cleared my cache, it still runs four times now, and I only want it to run once.

My question is, why is my loader function being called multiple times? Any insight would be greatly appreciated.

$items['daycare/%isValid/home'] = array(
    'title' => 'Daycare Admin Home',
    'page callback' => 'daycares_home_page',
    'load arguments' => array(0),//Passes 1st part of url 'daycare' as 2nd arg
    'page arguments' => array(0),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
);

function isValid_load($pageID, $pageType){
    /*Do stuff to validate wildcard part of URL. Will throw 404/403 if invalid*/
    return $pageId;
}

There's an issue for this. It looks like you have to implement caching in your loader.

I was curious and tried it out on admin/structure/types/manage/%node_type. I grepped for node_type_load and nothing seemed to be calling it directly, so I put a ddebug_backtrace() in the load function. I got 13 traces when visiting that path! 10 of these came from menu_local_tasks() which loops through the local tasks and calls _menu_translate() which calls _menu_load_objects() for each router item. The other two extra calls came via menu_set_active_trail() which also called _menu_translate(). So I guess it depends on your menu structure how many times a loader might be called. As far as I can tell the object's loaded only to check whether or not it can be (access is denied if it can't). I guess this just reinforces Damien's comment about implementing static caching in your loader.


How can I sort options in an exposed views filter alphabetically? I am using an exposed Views Selective Filter which limits the options available quite nicely. However the display order of the Options is what is causing me the trouble. Here is an example of my Select list:

Accomodation
 - Camp Sites
 - Hotels
 - Rural Hotels

Beauty
 - Hair and Nails
 - Makeup
 - Spa

In the results these display exactly as I want them which is grouped by the Parent term (Accomodation, Beauty etc...). The trouble is that when I use the Views Selective Filter to only show options with results the list of options shows like this:

Camp Sites
Hotels
Rural Hotel
Hair and Nails
Makeup
Spa

What I really want to do is to resort that list alphabetically before it is displayed to the User. I guess Hook Form Alter is the way to go but I can find anything anywhere on how to create the alpha sort option. I hope that all makes sense.
Thanks

j.Rowny's answer doesn't work because $form_state is not passed by reference.  You must actually modify the $form variable.  This worked for me:

function yourcustommodule_form_views_exposed_form_alter(&$form, $form_state) {
    foreach($form_state['view']->filter as $filter) {
        if($fid = $filter->options['expose']['identifier']) asort($form[$fid]['#options']);
    }
}


Drupal Caching strategies I read this interesting article on Drupal caching, but I'm not sure which caching method I should be using.

My code is implementing a menu callback, and returning a renderable array.
What is the difference between method #1 and method #2?

Please see the question embedded as a comment in method#2

// Method #1.
function my_module_menucallback() {
  $render_array = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $render_array = $cache->data;
    }
    else {
      // Do your expensive calculations here, and populate $render_array
      // with the correct stuff..
      cache_set('my_module_data', $render_array, 'cache');
    }
  }
  return $render_array;
}

// Method #2.
function my_module_menucallback() {
  // ** Do the calculations and population of $render_array that would occur here
  // get called repeatedly if this method of caching is used??? **

  $render_array ['my_content'] = array(
    '#cache' => array(
      'cid' => 'my_module_data',
      'bin' => 'cache',
      'expire' => time() + 360,
      ),
    // Other element properties go here...
    );
  return $render_array;
}

Please ignore the time specified, as this is just sample code.

So I tested and there is a significant difference between the two that I failed to understand originally.  Calculations not surrounded with ...

$render_array = &drupal_static(__FUNCTION__);
  if (!isset($my_data)) {
    if ($cache = cache_get('my_module_data')) {
      $render_array = $cache->data;
    }
    else {
      // Do your expensive calculations here
      cache_set('my_module_data', $render_array, 'cache');
    }
  }

...are executed every time the menu callback function is called (every time user visits that page).

Method #2 caches only the final, rendered output.  So if your calculations/processing in the method has changed the output value and you've cached the rendered output, you will not see the updated value until the cache is cleared.


Entity Reference on multilingual sites I am having a problem with getting Entity Reference to behave with a multilingual Drupal 7 installation using field translation (Entity Translation).

I have a node called 'Features' which has a bunch of dummy content entered in the default English and also in French. I have another node called 'Products' with an Entity Reference field in it for selecting the features.

So far so good, on the English form I see what I expect; I can select some of the references and save out.

When I create a French translation though, I see the following form:

I don't see any of the entities when creating or editing a French translation. Now, this in itself isn't a problem (for me) because the same selections should be made across all translations, but when I go ahead and save the French version, it will deselect all of the references in the English version of the node too.

Might I be missing something obvious with this? Is this expected behavior?

While this doesn't answer the behavior of the Entity Reference fields over different languages, switching the entity selection mode to a view seems to have solved it.

As suggested by Lester, I'm still unsure if the default 'Simple' selection mode was taking issue with the title of my fields, although rather than using the Title module - which can trip up other modules, i have found - I tend to keep the old title field and label it 'Administrative title' while adding a separate 'Translatable title' to work with - so in that sense there shouldn't have been an issue with the 'Simple' selection method.

Either way, setting up an Entity Reference View which displays and searches the 'Translatable title' of my Features node seems to have worked!

EDIT:

@Dan - these labels, are they node titles or fields which you created?

The issue with standard node titles is that they are different from other fields and as such are not 'entities' - this means that entity translation will not work on them. The workaround is to either use the Title module to replace the default title field with an entity (I had some issues with this), or use a different field which you create yourself.

Once the field you need to translate is an 'entity' (basically an field you create yourself, or one generated by the Title module) you can enable translation for it when adding the field to a content type.

Next you need to create a new view containing whatever content you want to use and click the + button to add an 'entity reference view'. After configuring this view with the fields you want to display and saving you should find that when editing the Entity Reference field in your content type, you can change the Entity selection mode to Views and select your newly created view.

I hope that makes sense!


Clustered Google Map I'm new in drupal(2 days), never used it before. I have taken over this site knowing nothing about it and right away got new assigment to create clustered looking map and markers should be put from already data in drupal site. So there is a page on the site https://esc.gsfc.nasa.gov/view-all-saves that shows all information needed to place markers on the map. How do I connect to that table, loop through records to call google API to place markers. Do I have to create my own php file and put inside the root? I looked in database and couldn't find any tables that stores that data.

The best way (the Drupal way) is to build on top of available Drupal features, rather than creating a custom solution that may do the narrow task at hand, but bypasses a lot of the built-in structure that carries a lot of value when using Drupal.

Views module is used to build the page you linked to, and Views is also the best module to use to list the geo-data to be displayed on a map.

Each node from that table has Longitude and Latitude coordinates (visible when you visit a node page, not directly in the table). These coordinates fields can be used to feed a Views map display.

You'll need to install a module that provides a special Views Format that renders a map. Then add that Display type to the same Views where the page you linked is built. Adjust the fields (override) to provide for the map display.

Are your Longitude/Latitude fields from Geolocation Field? Check under Structure > Content types > SAR Saves > Manage fields. Also check under Extend which geo-modules you have available.

With Geolocation Field you already have everything you need, you just need to configure a new map display in Views configuration, no coding required ;)